import type { Message } from "@poncho-ai/sdk"; import { type ConversationEntry, type NewConversationEntry, rebuildConversationFromEntries, } from "./storage/entries.js"; export interface ConversationState { runId: string; messages: Message[]; updatedAt: number; } export interface StateStore { get(runId: string): Promise; set(state: ConversationState): Promise; delete(runId: string): Promise; } /** * Whether a subagent actually accomplished its task — distinct from the *run* * status (`status` below), which is "completed" whenever the run merely * finished. A subagent that ran to completion but could not do the task (e.g. * lacked the required tools) is `runStatus:"completed"` but `taskOutcome: * "failed"`. Derived at subagent finalize; "unknown" when it can't be * determined. Consumed by the compaction subagent ledger so a failed task can * never be summarized as "completed". */ export type SubagentTaskOutcome = "succeeded" | "failed" | "partial" | "unknown"; export interface PendingSubagentResult { subagentId: string; task: string; status: "completed" | "error" | "stopped"; /** Did the subagent accomplish its task? See {@link SubagentTaskOutcome}. */ taskOutcome: SubagentTaskOutcome; result?: import("@poncho-ai/sdk").RunResult; error?: import("@poncho-ai/sdk").AgentFailure; timestamp: number; } export interface ArchivedToolResult { toolResultId: string; conversationId: string; toolName: string; toolCallId: string; createdAt: number; sizeBytes: number; payload: string; } export interface Conversation { conversationId: string; title: string; messages: Message[]; compactedHistory?: Message[]; runtimeRunId?: string; pendingApprovals?: Array<{ approvalId: string; runId: string; tool: string; toolCallId?: string; input: Record; checkpointMessages?: Message[]; baseMessageCount?: number; pendingToolCalls?: Array<{ id: string; name: string; input: Record }>; decision?: "approved" | "denied"; /** * Checkpoint kind discriminator. * - "approval" (default for legacy rows): user approve/deny gate. * - "device": tool executes on a connected client device (e.g. iOS); the * consumer of the harness POSTs a tool result back to resume. * Treat `undefined` as "approval" for backward compatibility with rows * persisted before this field existed. */ kind?: "approval" | "device"; }>; runStatus?: "running" | "idle"; ownerId: string; tenantId: string | null; contextTokens?: number; contextWindow?: number; parentConversationId?: string; parentMessageId?: string; threadMeta?: { /** First ~200 chars of the anchor message text, cached for cheap rendering. */ parentMessageSummary?: string; /** Length of the snapshot at fork time. messages[snapshotLength-1] is the anchor. */ snapshotLength: number; }; subagentMeta?: { task: string; status: "running" | "completed" | "error" | "stopped"; result?: import("@poncho-ai/sdk").RunResult; error?: import("@poncho-ai/sdk").AgentFailure; /** Inherited from the parent run at spawn time — when true, this * subagent's runs emit no telemetry (e.g. spawned from an incognito * turn). Read by the orchestrator's runSubagent / continuation. */ suppressTelemetry?: boolean; /** The parent's `spawn_subagent` tool call id — echoed onto subagent:* * events so a client can attach subagent state to that tool's pill. */ parentToolCallId?: string; }; channelMeta?: { platform: string; channelId: string; platformThreadId: string; }; pendingSubagentResults?: PendingSubagentResult[]; subagentCallbackCount?: number; runningCallbackSince?: number; lastActivityAt?: number; _continuationMessages?: Message[]; _continuationCount?: number; _harnessMessages?: Message[]; _toolResultArchive?: Record; createdAt: number; updatedAt: number; } export interface ConversationCreateInit { parentConversationId?: string; parentMessageId?: string; threadMeta?: Conversation["threadMeta"]; subagentMeta?: Conversation["subagentMeta"]; messages?: Message[]; channelMeta?: Conversation["channelMeta"]; } export interface ConversationStore { list(ownerId?: string, tenantId?: string | null): Promise; listSummaries(ownerId?: string, tenantId?: string | null): Promise; /** * Cheap column-level fetch — returns summary fields only, no data blob. * Use this on hot polling paths where the caller just needs to know * whether the conversation has changed since last fetch. */ getStatusSnapshot(conversationId: string): Promise; /** * Load a conversation WITHOUT the tool_result_archive blob. Default for * read paths — archive can grow unboundedly and most callers don't need it. */ get(conversationId: string): Promise; /** * Load a conversation WITH the tool_result_archive. Use this only on * run-entry paths that reseed the harness (via withToolResultArchiveParam * or by passing the archive to runCronAgent). */ getWithArchive(conversationId: string): Promise; create( ownerId?: string, title?: string, tenantId?: string | null, init?: ConversationCreateInit, ): Promise; update(conversation: Conversation): Promise; rename(conversationId: string, title: string): Promise; delete(conversationId: string): Promise; appendSubagentResult(conversationId: string, result: PendingSubagentResult): Promise; clearCallbackLock(conversationId: string): Promise; /** List thread conversations anchored under `parentConversationId`. */ listThreads(parentConversationId: string): Promise; /** * Append entries to a conversation's append-only log (Phase 3 substrate). * Assigns a per-conversation monotonic `seq` and a `createdAt` to each * entry, persists them in order, and returns the stored entries with those * fields filled in. Additive — no existing read path consumes these yet. */ appendEntries( conversationId: string, agentId: string, tenantId: string | null, entries: NewConversationEntry[], ): Promise; /** Read a conversation's entries ordered by `seq` ascending. */ readEntries( conversationId: string, opts?: { types?: string[]; afterSeq?: number; limit?: number }, ): Promise; } export type StateProviderName = | "local" | "memory" | "sqlite" | "postgresql" | "redis" | "upstash" | "dynamodb"; export interface StateConfig { provider?: StateProviderName; ttl?: number; urlEnv?: string; tokenEnv?: string; table?: string; region?: string; } const DEFAULT_OWNER = "local-owner"; const normalizeTitle = (title?: string): string => { return title && title.trim().length > 0 ? title.trim() : "New conversation"; }; export class InMemoryStateStore implements StateStore { private readonly store = new Map(); private readonly ttlMs?: number; constructor(ttlSeconds?: number) { this.ttlMs = typeof ttlSeconds === "number" ? ttlSeconds * 1000 : undefined; } private isExpired(state: ConversationState): boolean { return typeof this.ttlMs === "number" && Date.now() - state.updatedAt > this.ttlMs; } async get(runId: string): Promise { const state = this.store.get(runId); if (!state) return undefined; if (this.isExpired(state)) { this.store.delete(runId); return undefined; } return state; } async set(state: ConversationState): Promise { this.store.set(state.runId, { ...state, updatedAt: Date.now() }); } async delete(runId: string): Promise { this.store.delete(runId); } } export class InMemoryConversationStore implements ConversationStore { private readonly conversations = new Map(); private readonly entries = new Map(); private readonly ttlMs?: number; constructor(ttlSeconds?: number) { this.ttlMs = typeof ttlSeconds === "number" ? ttlSeconds * 1000 : undefined; } private isExpired(updatedAt: number): boolean { return typeof this.ttlMs === "number" && Date.now() - updatedAt > this.ttlMs; } private purgeExpired(): void { for (const [conversationId, conversation] of this.conversations.entries()) { if (this.isExpired(conversation.updatedAt)) { this.conversations.delete(conversationId); } } } async list(ownerId?: string, tenantId?: string | null): Promise { this.purgeExpired(); return Array.from(this.conversations.values()) .filter((conversation) => !ownerId || conversation.ownerId === ownerId) .filter((c) => tenantId === undefined || c.tenantId === tenantId) .sort((a, b) => b.updatedAt - a.updatedAt); } async listSummaries(ownerId?: string, tenantId?: string | null): Promise { this.purgeExpired(); return Array.from(this.conversations.values()) .filter((c) => !ownerId || c.ownerId === ownerId) .filter((c) => tenantId === undefined || c.tenantId === tenantId) .sort((a, b) => b.updatedAt - a.updatedAt) .map((c) => ({ conversationId: c.conversationId, title: c.title, updatedAt: c.updatedAt, createdAt: c.createdAt, ownerId: c.ownerId, tenantId: c.tenantId, parentConversationId: c.parentConversationId, parentMessageId: c.parentMessageId, messageCount: c.messages.length, hasPendingApprovals: Array.isArray(c.pendingApprovals) && c.pendingApprovals.length > 0, channelMeta: c.channelMeta, })); } async get(conversationId: string): Promise { this.purgeExpired(); const c = this.conversations.get(conversationId); if (!c) return undefined; // Phase 3c read cutover: rebuild reader-facing fields from the entry log // (blob fallback for un-migrated conversations). Clone first — the map // holds a live mutable reference and the rebuild overrides fields. return rebuildConversationFromEntries({ ...c }, (id) => this.readEntries(id, { types: ["subagent_result", "callback_started"] }), ); } // In-memory stores already hold the full conversation object, so there's // no separate archive blob to load. Both variants return the same data. async getWithArchive(conversationId: string): Promise { return this.get(conversationId); } async getStatusSnapshot(conversationId: string): Promise { const c = await this.get(conversationId); if (!c) return undefined; return { conversationId: c.conversationId, updatedAt: c.updatedAt, messageCount: c.messages.length, hasPendingApprovals: Array.isArray(c.pendingApprovals) && c.pendingApprovals.length > 0, hasContinuationMessages: Array.isArray(c._continuationMessages) && c._continuationMessages.length > 0, parentConversationId: c.parentConversationId ?? null, ownerId: c.ownerId, tenantId: c.tenantId, runStatus: c.runStatus ?? null, }; } async create( ownerId = DEFAULT_OWNER, title?: string, tenantId: string | null = null, init?: ConversationCreateInit, ): Promise { const now = Date.now(); const conversation: Conversation = { conversationId: globalThis.crypto?.randomUUID?.() ?? `${now}-${Math.random()}`, title: normalizeTitle(title), messages: init?.messages ?? [], ownerId, tenantId, createdAt: now, updatedAt: now, ...(init?.parentConversationId !== undefined ? { parentConversationId: init.parentConversationId } : {}), ...(init?.parentMessageId !== undefined ? { parentMessageId: init.parentMessageId } : {}), ...(init?.threadMeta !== undefined ? { threadMeta: init.threadMeta } : {}), ...(init?.subagentMeta !== undefined ? { subagentMeta: init.subagentMeta } : {}), ...(init?.channelMeta !== undefined ? { channelMeta: init.channelMeta } : {}), }; this.conversations.set(conversation.conversationId, conversation); return conversation; } async update(conversation: Conversation): Promise { this.conversations.set(conversation.conversationId, { ...conversation, updatedAt: Date.now(), }); } async rename(conversationId: string, title: string): Promise { const existing = await this.get(conversationId); if (!existing) return undefined; const updated: Conversation = { ...existing, title: normalizeTitle(title || existing.title), updatedAt: Date.now(), }; this.conversations.set(conversationId, updated); return updated; } async delete(conversationId: string): Promise { return this.conversations.delete(conversationId); } async appendSubagentResult(conversationId: string, result: PendingSubagentResult): Promise { const conversation = this.conversations.get(conversationId); if (!conversation) return; if (!conversation.pendingSubagentResults) conversation.pendingSubagentResults = []; conversation.pendingSubagentResults.push(result); conversation.updatedAt = Date.now(); } async clearCallbackLock(conversationId: string): Promise { const conversation = this.conversations.get(conversationId); if (!conversation) return undefined; conversation.runningCallbackSince = undefined; conversation.updatedAt = Date.now(); return conversation; } async listThreads(parentConversationId: string): Promise { this.purgeExpired(); return Array.from(this.conversations.values()) .filter( (c) => c.parentConversationId === parentConversationId && typeof c.parentMessageId === "string", ) .sort((a, b) => b.updatedAt - a.updatedAt) .map((c) => ({ conversationId: c.conversationId, title: c.title, updatedAt: c.updatedAt, createdAt: c.createdAt, ownerId: c.ownerId, tenantId: c.tenantId, parentConversationId: c.parentConversationId, parentMessageId: c.parentMessageId, messageCount: c.messages.length, hasPendingApprovals: Array.isArray(c.pendingApprovals) && c.pendingApprovals.length > 0, channelMeta: c.channelMeta, })); } async appendEntries( conversationId: string, _agentId: string, _tenantId: string | null, entries: NewConversationEntry[], ): Promise { const list = this.entries.get(conversationId) ?? []; // seq is per-conversation: max existing seq + 1, then consecutive. let nextSeq = list.reduce((max, e) => (e.seq > max ? e.seq : max), 0) + 1; const now = Date.now(); const stored: ConversationEntry[] = entries.map( (e) => ({ ...e, seq: nextSeq++, createdAt: now }) as ConversationEntry, ); this.entries.set(conversationId, [...list, ...stored]); return stored; } async readEntries( conversationId: string, opts?: { types?: string[]; afterSeq?: number; limit?: number }, ): Promise { let list = (this.entries.get(conversationId) ?? []) .slice() .sort((a, b) => a.seq - b.seq); if (opts?.types && opts.types.length > 0) { const allowed = new Set(opts.types); list = list.filter((e) => allowed.has(e.type)); } if (typeof opts?.afterSeq === "number") { list = list.filter((e) => e.seq > opts.afterSeq!); } if (typeof opts?.limit === "number") { list = list.slice(0, opts.limit); } return list; } } export type ConversationSummary = { conversationId: string; title: string; updatedAt: number; createdAt?: number; ownerId: string; tenantId?: string | null; parentConversationId?: string; parentMessageId?: string; messageCount?: number; hasPendingApprovals?: boolean; channelMeta?: { platform: string; channelId: string; platformThreadId: string; }; }; /** * Lightweight status snapshot — column-level reads only, no data blob. * Used by cheap polling endpoints that just need to know "has anything * changed?" without paying to deserialize the full conversation. */ export type ConversationStatusSnapshot = { conversationId: string; updatedAt: number; messageCount: number; hasPendingApprovals: boolean; hasContinuationMessages: boolean; parentConversationId: string | null; ownerId: string; tenantId: string | null; runStatus: "running" | "idle" | null; }; // --------------------------------------------------------------------------- // Legacy factories — return InMemory stores. The harness now uses // engine-backed stores via storage/store-adapters.ts. These factories // exist only for backward compatibility with external callers and tests. // --------------------------------------------------------------------------- export const createStateStore = ( config?: StateConfig, _options?: { workingDir?: string; agentId?: string }, ): StateStore => { const ttl = config?.ttl; return new InMemoryStateStore(ttl); }; export const createConversationStore = ( config?: StateConfig, _options?: { workingDir?: string; agentId?: string }, ): ConversationStore => { const ttl = config?.ttl; return new InMemoryConversationStore(ttl); };