import { LanguageModel } from 'ai'; import * as _poncho_ai_sdk from '@poncho-ai/sdk'; import { Message, ToolContext, ToolDefinition, JsonSchema, RunResult, AgentFailure, RunInput, AgentEvent, FileInput, Logger } from '@poncho-ai/sdk'; export { ToolDefinition, defineTool } from '@poncho-ai/sdk'; import { FsStat, IFileSystem, BufferEncoding, FileContent, MkdirOptions, RmOptions, CpOptions, Bash } from 'just-bash'; import { z } from 'zod'; interface AgentModelConfig { provider: string; name: string; temperature?: number; maxTokens?: number; contextWindow?: number; } interface AgentLimitsConfig { maxSteps?: number; timeout?: number; } interface CronJobConfig { schedule: string; task: string; timezone?: string; channel?: string; maxRuns?: number; } interface AgentFrontmatter { name: string; id?: string; description?: string; model?: AgentModelConfig; limits?: AgentLimitsConfig; allowedTools?: { mcp?: string[]; scripts?: string[]; }; approvalRequired?: { mcp?: string[]; scripts?: string[]; }; compaction?: CompactionConfig; cron?: Record; } interface CompactionConfig { enabled: boolean; trigger: number; /** * Primary retention unit: number of whole recent *turns* (a user message plus * the assistant/tool messages that follow it) preserved verbatim after the * summary. See `findSafeSplitPointByTurns`. */ keepRecentTurns: number; /** * Fallback retention floor, in messages, used only for the single-giant-turn * case where no turn boundary yields a safe split. */ keepRecentMessages: number; instructions?: string; } interface ParsedAgent { frontmatter: AgentFrontmatter; body: string; } interface RuntimeRenderContext { parameters?: Record; runtime?: { workingDir?: string; agentId?: string; runId?: string; environment?: string; }; } declare const parseAgentMarkdown: (content: string) => ParsedAgent; declare const parseAgentFile: (workingDir: string) => Promise; declare const renderAgentPrompt: (agent: ParsedAgent, context?: RuntimeRenderContext) => string; declare const STORAGE_SCHEMA_VERSION = "v1"; type AgentIdentity = { name: string; id: string; }; declare const getPonchoStoreRoot: () => string; declare const slugifyStorageComponent: (value: string) => string; declare const generateAgentId: () => string; declare const resolveAgentIdentity: (workingDir: string) => Promise; declare const ensureAgentIdentity: (workingDir: string) => Promise; declare const buildAgentDirectoryName: (identity: AgentIdentity) => string; declare const getAgentStoreDirectory: (identity: AgentIdentity) => string; declare const resolveCompactionConfig: (explicit?: Partial) => CompactionConfig; /** * Estimate the token count of a string using the chars/4 heuristic * with a conservative overhead multiplier. */ declare const estimateTokens: (text: string) => number; /** * Estimate the total token count of a system prompt + messages + tool defs. * * Tool definitions are structured JSON (property names, braces, enum values) * which tokenizes more efficiently than natural language — roughly 5-6 * chars/token vs ~4 chars/token for prose. We estimate them separately to * avoid inflating the count when there are many MCP tools (100+). */ declare const estimateTotalTokens: (systemPrompt: string, messages: Message[], toolDefinitionsJson?: string) => number; /** * Find the safe split index so that everything before it can be compacted * and everything from it onward is preserved. The split always lands just * before a `user` message to avoid breaking assistant+tool pairs. * * Defensive guard: even at a `user` boundary, refuse a split whose compacted * side would END on an assistant message with unanswered tool_calls (its * `tool` result having moved to the preserved side). Such a split would * orphan the tool_calls inside the summary boundary. When that happens we * walk earlier to the next safe `user` boundary. * * Returns -1 if no valid split point is found. */ declare const findSafeSplitPoint: (messages: Message[], keepRecentMessages: number) => number; /** * Find the split index that preserves the last `keepRecentTurns` whole *turns* * verbatim. A turn begins at a `role:"user"` message and runs until the next * `user` message. Everything before the split is folded into the summary; * everything from the split onward is kept as-is. * * Two guards make a candidate split acceptable: * 1. The compacted side has at least `MIN_COMPACTABLE_MESSAGES` messages. * 2. The preserved side estimates at most `maxPreservedTokens` — so keeping N * large turns can never leave the post-compaction context above the * compaction trigger (which caused re-compaction thrash / window overflow). * The tool-call-orphan guard (`splitOrphansToolCalls`) is preserved: a split * that would strand an assistant tool-call on the compacted side steps to an * earlier user boundary (which only preserves more, always safe). * * We try the largest N (up to `keepRecentTurns`) first and decrement, so we * keep as many turns as fit. If no turn boundary yields a safe split (e.g. a * single giant turn near the window), fall back to the message-based * `findSafeSplitPoint` so the middle of that turn still compacts. * * Returns -1 when nothing safe can be compacted. */ declare const findSafeSplitPointByTurns: (messages: Message[], keepRecentTurns: number, keepRecentMessagesFallback: number, maxPreservedTokens: number) => number; interface CompactMessagesOptions { instructions?: string; /** * The model's context window (tokens). Used to bound the preserved side of a * turn-based split so keeping N recent turns can't leave the post-compaction * context above the compaction trigger. Defaults to 200k when omitted. */ contextWindow?: number; } interface CompactResult { compacted: boolean; messages: Message[]; messagesBefore?: number; messagesAfter?: number; warning?: string; } /** * Compact a message array by summarizing older messages via an LLM call. * * @param model The language model instance to use for summarization * @param messages The full message array * @param config Compaction configuration * @param options Optional instructions override * @returns The compacted result */ declare const compactMessages: (model: LanguageModel, messages: Message[], config: CompactionConfig, options?: CompactMessagesOptions) => Promise; /** * The subagent delivery queue: append-only `conversation_entries` rows that * carry a finished subagent's result to its parent conversation. * * Why this exists: subagent results are the ONE conversation field with * concurrent writers. A subagent finishes whenever it finishes — possibly * while the parent turn is mid-stream doing whole-blob writes — so a * read-modify-write on the mutable conversation row could serialize a stale * snapshot over the result (the historical "lost subagent result" clobber). * An append-only INSERT can't express that race. Everything single-writer * (message history, metadata) stays on the conversation row, where the * orchestrator's per-conversation turn serialization already makes mutation * safe. * * Two entry types: * - `subagent_result`: a finished subagent's result, appended by the * orchestrator's result-delivery path. * - `callback_started`: marks which result entries a callback turn * consumed (by seq). Consumption is an append, never a delete — a * result is "pending" until a later callback_started lists its seq. * * Historical note: this module once defined a full transcript's worth of * entry types (user/assistant/harness messages, compaction overlays) as * groundwork for replacing the conversation blob entirely. The full read * cutover shipped briefly (harness 0.58.0), proved unfaithful for callback * turns, and was reverted; the unread types + dual-writes were then deleted * rather than maintained as drift-prone dead weight. If a future feature * needs real history semantics (editing, branching, audit), design that * migration fresh — and remember the 0.58.0 lesson: an append-only log is * only as good as the completeness of its writers. * * Ordering: every entry carries a monotonic per-conversation `seq`, * assigned by the engine at append time. Entries are sorted by `seq` * ascending when passed to the rebuild fn. */ interface BaseEntry { /** Stable cross-reference id (uuid). */ id: string; /** Monotonic per-conversation order. */ seq: number; createdAt: number; } /** A finished subagent's result arriving for the parent. Pending = a * subagent_result whose seq is not listed in any later callback_started. */ interface SubagentResultEntry extends BaseEntry { type: "subagent_result"; result: PendingSubagentResult; } /** Marks which subagent_result entries a callback turn consumed (by seq). * Consumption is an append, never a delete. */ interface CallbackStartedEntry extends BaseEntry { type: "callback_started"; consumedSeqs: number[]; } type ConversationEntry = SubagentResultEntry | CallbackStartedEntry; /** * An entry to append, before the engine assigns `seq` and `createdAt`. This * is a DISTRIBUTIVE omit — `Omit` over a union would * collapse to only the keys common to every member, so we distribute over * the union with a conditional type to omit those fields from each member * individually. */ type NewConversationEntry = ConversationEntry extends infer T ? T extends ConversationEntry ? Omit : never : never; /** * Subagent results that have arrived but not yet been consumed by a * callback turn — the append-only replacement for the mutable * `pendingSubagentResults` array. A result is pending unless a later * callback_started lists its seq in `consumedSeqs`. */ declare function getPendingSubagentResults(entries: ConversationEntry[]): PendingSubagentResult[]; interface ConversationState { runId: string; messages: Message[]; updatedAt: number; } 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". */ type SubagentTaskOutcome = "succeeded" | "failed" | "partial" | "unknown"; interface PendingSubagentResult { subagentId: string; task: string; status: "completed" | "error" | "stopped"; /** Did the subagent accomplish its task? See {@link SubagentTaskOutcome}. */ taskOutcome: SubagentTaskOutcome; result?: _poncho_ai_sdk.RunResult; error?: _poncho_ai_sdk.AgentFailure; timestamp: number; } interface ArchivedToolResult$1 { toolResultId: string; conversationId: string; toolName: string; toolCallId: string; createdAt: number; sizeBytes: number; payload: string; } 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?: _poncho_ai_sdk.RunResult; error?: _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; } interface ConversationCreateInit { parentConversationId?: string; parentMessageId?: string; threadMeta?: Conversation["threadMeta"]; subagentMeta?: Conversation["subagentMeta"]; messages?: Message[]; channelMeta?: Conversation["channelMeta"]; } 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; } type StateProviderName = "local" | "memory" | "sqlite" | "postgresql" | "redis" | "upstash" | "dynamodb"; interface StateConfig { provider?: StateProviderName; ttl?: number; urlEnv?: string; tokenEnv?: string; table?: string; region?: string; } declare class InMemoryStateStore implements StateStore { private readonly store; private readonly ttlMs?; constructor(ttlSeconds?: number); private isExpired; get(runId: string): Promise; set(state: ConversationState): Promise; delete(runId: string): Promise; } declare class InMemoryConversationStore implements ConversationStore { private readonly conversations; private readonly entries; private readonly ttlMs?; constructor(ttlSeconds?: number); private isExpired; private purgeExpired; list(ownerId?: string, tenantId?: string | null): Promise; listSummaries(ownerId?: string, tenantId?: string | null): Promise; get(conversationId: string): Promise; getWithArchive(conversationId: string): Promise; getStatusSnapshot(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; listThreads(parentConversationId: string): Promise; appendEntries(conversationId: string, _agentId: string, _tenantId: string | null, entries: NewConversationEntry[]): Promise; readEntries(conversationId: string, opts?: { types?: string[]; afterSeq?: number; limit?: number; }): Promise; } 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. */ type ConversationStatusSnapshot = { conversationId: string; updatedAt: number; messageCount: number; hasPendingApprovals: boolean; hasContinuationMessages: boolean; parentConversationId: string | null; ownerId: string; tenantId: string | null; runStatus: "running" | "idle" | null; }; declare const createStateStore: (config?: StateConfig, _options?: { workingDir?: string; agentId?: string; }) => StateStore; declare const createConversationStore: (config?: StateConfig, _options?: { workingDir?: string; agentId?: string; }) => ConversationStore; interface MainMemory { content: string; updatedAt: number; } interface MemoryConfig { enabled?: boolean; provider?: StateProviderName; urlEnv?: string; tokenEnv?: string; table?: string; region?: string; ttl?: number; maxRecallConversations?: number; /** * Optional cap on the characters of main memory injected into the * system prompt each turn. Default is **no cap** — the full memory is * injected (silently truncating a user's memory every turn is a * footgun). Set a positive number to opt into truncation for * prompt-cost control; content beyond it is sliced with a * `...[truncated]` marker. */ maxPromptChars?: number; } interface MemoryStore { getMainMemory(): Promise; updateMainMemory(input: { content: string; }): Promise; } declare const createMemoryStore: (agentId: string, config?: MemoryConfig, options?: { workingDir?: string; tenantId?: string; }) => MemoryStore; declare const createMemoryTools: (store: MemoryStore | ((context: ToolContext) => MemoryStore), options?: { maxRecallConversations?: number; }) => ToolDefinition[]; interface RemoteMcpServerConfig { name?: string; url: string; env?: string[]; auth?: { type: "bearer"; tokenEnv?: string; }; headers?: Record; timeoutMs?: number; reconnectAttempts?: number; reconnectDelayMs?: number; } interface McpConfig { mcp?: RemoteMcpServerConfig[]; } declare class LocalMcpBridge { private readonly remoteServers; private readonly rpcClients; private readonly toolCatalog; private readonly unavailableServers; private readonly authFailedServers; private envResolver?; /** * Per-tenant MCP client cache. For consumer/SaaS deployments where every * call resolves a different bearer token, building a fresh * `StreamableHttpMcpRpcClient` per call would force a fresh `initialize` * round-trip every time. We keep one client per `(serverName, tenantId)` * with TTL-based idle eviction; on token rotation we evict the entry * lazily and rebuild. */ private readonly tenantClients; /** Test/observability hook: bumped every time a new tenant client is constructed. */ tenantClientConstructions: number; private readonly tenantClientTtlMs; /** * Set a resolver for per-tenant env vars (e.g. MCP auth tokens). * Called by the harness after creating the secrets store. */ setEnvResolver(resolver: (tenantId: string | undefined, envName: string) => Promise): void; constructor(config: McpConfig | undefined, options?: { tenantClientTtlMs?: number; }); private getServerName; private log; /** Set of servers where discovery was deferred (no default token, has env resolver). */ private readonly deferredDiscoveryServers; discoverTools(): Promise; /** * Run deferred discovery and return ToolDefinitions for all newly discovered tools. * Call this during run() so the tools are available to the model immediately. */ discoverAndLoadDeferred(tenantId: string): Promise; private tryDeferredDiscovery; startLocalServers(): Promise; stopLocalServers(): Promise; private getOrCreateTenantClient; listServers(): RemoteMcpServerConfig[]; listRemoteServers(): RemoteMcpServerConfig[]; checkRemoteConnectivity(): Promise>; toSerializableConfig(): McpConfig; getLocalServers(): never[]; listDiscoveredTools(serverName?: string): string[]; hasDeferredServers(): boolean; /** * Return ToolDefinitions for catalog tools not already registered in the dispatcher. */ getUnregisteredTools(registeredNames: Set): ToolDefinition[]; loadTools(requestedPatterns: string[]): Promise; private toToolDefinitions; } interface StorageConfig { provider?: "local" | "memory" | "sqlite" | "postgresql" | "redis" | "upstash" | "dynamodb"; urlEnv?: string; tokenEnv?: string; table?: string; region?: string; ttl?: number | { conversations?: number; memory?: number; }; memory?: { enabled?: boolean; maxRecallConversations?: number; maxPromptChars?: number; }; limits?: { maxFileSize?: number; maxTotalStorage?: number; }; } interface UploadsConfig { provider?: "local" | "vercel-blob" | "s3"; /** Vercel Blob access mode. Must match the store's configuration. Defaults to "public". */ access?: "public" | "private"; bucket?: string; region?: string; endpoint?: string; } type ToolAccess = boolean | "approval" | { access?: "approval"; dispatch?: "device"; }; /** * Normalize any ToolAccess value into a {access, dispatch} struct. * `boolean` collapses to no special handling — the boolean only encodes * enable/disable, not dispatch — callers gate behavior on `dispatch` and * `access`. */ declare const normalizeToolAccess: (value: ToolAccess | undefined) => { access?: "approval"; dispatch?: "device"; }; /** @deprecated Use flat tool keys on `tools` instead. Kept for backward compat. */ type BuiltInToolToggles = { list_directory?: boolean; read_file?: boolean; write_file?: boolean; edit_file?: boolean; delete_file?: boolean; delete_directory?: boolean; todo_list?: boolean; todo_add?: boolean; todo_update?: boolean; todo_remove?: boolean; web_search?: boolean; web_fetch?: boolean; }; interface MessagingChannelConfig { platform: "slack" | "resend" | "telegram"; botTokenEnv?: string; signingSecretEnv?: string; apiKeyEnv?: string; webhookSecretEnv?: string; fromEnv?: string; replyToEnv?: string; allowedSenders?: string[]; mode?: "auto-reply" | "tool"; allowedRecipients?: string[]; maxSendsPerRun?: number; allowedUserIds?: number[]; } interface IsolateBinding { description: string; inputSchema: JsonSchema; handler: (input: Record) => Promise | unknown; } /** * Network access configuration for the bash sandbox (curl, wget). * Network access is disabled by default — you must explicitly allow URLs. */ interface NetworkConfig { /** * List of allowed URL prefixes. Each entry must be a full origin (scheme + host), * optionally followed by a path prefix. * * Examples: * - `"https://api.example.com"` — allows all paths on this origin * - `"https://api.example.com/v1/"` — allows only paths starting with /v1/ * * Entries can be plain strings or objects with header transforms for credentials brokering: * ``` * { url: "https://api.example.com", transform: [{ headers: { "Authorization": "Bearer ..." } }] } * ``` */ allowedUrls?: (string | { url: string; transform?: { headers: Record; }[]; })[]; /** Allowed HTTP methods. Defaults to `["GET", "HEAD"]`. */ allowedMethods?: ("GET" | "HEAD" | "POST" | "PUT" | "DELETE" | "PATCH" | "OPTIONS")[]; /** Bypass the allow-list and permit all URLs and methods. Only use in trusted environments. */ dangerouslyAllowAll?: boolean; /** Maximum number of redirects to follow. Default: 20. */ maxRedirects?: number; /** Request timeout in milliseconds. Default: 30000. */ timeoutMs?: number; /** Maximum response body size in bytes. Default: 10MB. */ maxResponseSize?: number; /** Reject URLs resolving to private/loopback IPs (SSRF protection). Default: false. */ denyPrivateRanges?: boolean; } interface BashExecutionLimits { /** Maximum function call/recursion depth. Default: 100. */ maxCallDepth?: number; /** Maximum number of commands to execute. Default: 10000. */ maxCommandCount?: number; /** Maximum loop iterations for while/for/until. Default: 10000. */ maxLoopIterations?: number; /** Maximum total output size (stdout + stderr) in bytes. Default: 10MB. */ maxOutputSize?: number; /** Maximum string length in bytes. Default: 10MB. */ maxStringLength?: number; /** Maximum array elements. Default: 100000. */ maxArrayElements?: number; } interface BashConfig { /** * Whitelist of allowed commands. When set, only these commands are available. * Omit to allow all built-in commands. * * @example ["cat", "grep", "jq", "echo", "ls", "head", "tail", "wc", "sort"] */ commands?: string[]; /** Execution limits to prevent runaway scripts. */ executionLimits?: BashExecutionLimits; /** Enable python3/python commands in the sandbox. Default: false. */ python?: boolean; /** Enable js-exec/node commands via QuickJS in the sandbox. Default: false. */ javascript?: boolean; /** Environment variables injected into every bash session. */ env?: Record; } interface IsolateConfig { /** V8 isolate memory limit in MB. Default: 128 */ memoryLimit?: number; /** Execution timeout in ms. Default: 10000 */ timeLimit?: number; /** Max combined stdout+stderr in bytes. Default: 65536 */ outputLimit?: number; /** Max code input size in bytes. Default: 102400 (100KB) */ codeLimit?: number; /** npm packages to bundle and make available via require() */ libraries?: string[]; /** External API access */ apis?: { fetch?: { allowedDomains: string[]; }; }; /** Builder-defined custom bindings injected into the isolate */ bindings?: Record; } interface PonchoConfig extends McpConfig { harness?: string; messaging?: MessagingChannelConfig[]; tools?: { defaults?: BuiltInToolToggles; byEnvironment?: { development?: Record; staging?: Record; production?: Record; }; [toolName: string]: ToolAccess | BuiltInToolToggles | Record> | undefined; }; auth?: { required?: boolean; type?: "bearer" | "header" | "custom"; headerName?: string; tokenEnv?: string; validate?: (token: string, req?: unknown) => Promise | boolean; }; state?: { provider?: "local" | "memory" | "redis" | "upstash" | "dynamodb"; ttl?: number; [key: string]: unknown; }; memory?: MemoryConfig; storage?: StorageConfig; providers?: { openai?: { apiKeyEnv?: string; }; openaiCodex?: { refreshTokenEnv?: string; accessTokenEnv?: string; accessTokenExpiresAtEnv?: string; accountIdEnv?: string; authFilePathEnv?: string; }; anthropic?: { apiKeyEnv?: string; }; }; telemetry?: { enabled?: boolean; otlp?: string | { url: string; headers?: Record; }; /** End-user identifier (e.g. an email) stamped as `user.id` on every * root trace span — observability backends (Latitude) group and * filter traces by it. Per-harness, so a harness-per-user consumer * sets it once at construction. */ userId?: string; handler?: (event: unknown) => Promise | void; }; skills?: Record>; /** Extra directories (relative to project root) to scan for skills. * `skills/` and `.poncho/skills/` are always scanned. */ skillPaths?: string[]; uploads?: UploadsConfig; build?: { vercel?: Record; docker?: Record; lambda?: Record; fly?: Record; }; /** One-off reminders. When enabled, the agent gets set_reminder / list_reminders / cancel_reminder tools. */ reminders?: { enabled?: boolean; /** Cron expression controlling how often the reminder poll runs (local and serverless). Default: every 10 minutes. */ pollSchedule?: string; }; /** * Declare env var names that tenants can self-manage via the web UI or API. * Key = env var name, value = human-readable label shown in the settings panel. * Example: { LINEAR_API_KEY: "Linear API Key", STRIPE_KEY: "Stripe Secret Key" } */ tenantSecrets?: Record; /** Set to `false` to disable the built-in web UI (headless / API-only mode). */ webUi?: false; /** Enable sandboxed V8 isolate code execution. */ isolate?: IsolateConfig; /** * Network access for sandboxed tools (bash curl/wget, isolate fetch). * Disabled by default — you must explicitly allow URLs. */ network?: NetworkConfig; /** Bash sandbox configuration. */ bash?: BashConfig; /** Enable browser automation tools. Set `true` for defaults, or provide config. */ browser?: boolean | { viewport?: { width?: number; height?: number; }; quality?: number; everyNthFrame?: number; profileDir?: string; sessionName?: string; executablePath?: string; headless?: boolean; /** Custom user-agent string. When stealth is enabled (default) a * realistic Chrome UA is used automatically. */ userAgent?: string; /** Reduce bot-detection fingerprints. Defaults to `true`. */ stealth?: boolean; /** Cloud browser provider for serverless/remote deployments. * Requires the provider's API key env var (e.g. `BROWSERBASE_API_KEY`). */ provider?: "browserbase" | "browseruse" | "kernel"; /** Connect to an existing browser via CDP URL or port. * Mutually exclusive with `provider`. */ cdpUrl?: string; /** Host-supplied persistence for the browser's storage state * (cookies + localStorage as a Playwright storageState JSON). When * provided, the harness uses this instead of its built-in file-based * persistence — letting an embedding app store session state in its * own (e.g. encrypted, per-tenant) backend. */ storagePersistence?: { save(json: string): Promise; load(): Promise; }; /** When true, the host owns the live viewport: the harness will NOT * wire frame/status listeners during run() (so no `browser:frame` / * `browser:status` events are emitted into the agent event stream). * The host is expected to subscribe to the BrowserSession's * `onFrame`/`onStatus` directly and stream frames out-of-band. */ hostManagedStreaming?: boolean; }; } declare const resolveStateConfig: (config: PonchoConfig | undefined) => StateConfig | undefined; declare const resolveMemoryConfig: (config: PonchoConfig | undefined) => MemoryConfig | undefined; declare const loadPonchoConfig: (workingDir: string) => Promise; interface DefaultAgentDefinitionOptions { /** Display name for the agent. Default: "agent". */ name?: string; /** * Stable identifier embedded in the frontmatter. Default: a fresh * `agent_<32hex>`. Note: when an injected `StorageEngine` is also passed * to `AgentHarness`, the engine's `agentId` overrides this at runtime, so * SDK consumers can leave it default. */ id?: string; /** Frontmatter description. Default: "A helpful Poncho assistant". */ description?: string; /** Model provider. Default: "anthropic". */ modelProvider?: "anthropic" | "openai" | "openai-codex"; /** Model name. Default: "claude-opus-4-5". */ modelName?: string; /** * Sampling temperature. When unset, it is omitted from the generated * frontmatter entirely and the harness sends no temperature (provider * default). Newer models (Fable 5, Opus 4.7+) reject `temperature` — leave * this unset for them. */ temperature?: number; /** Max tool-call steps per run. Default: 20. */ maxSteps?: number; /** Hard timeout in seconds. Default: 300. */ timeout?: number; /** * The descriptor that follows the name in the opening line * ("You are **{name}**, {tagline}."). Default: * "a helpful assistant built with Poncho". SDK consumers shipping a * differently-branded product can override this so the framework name * does not leak into the agent's system prompt. */ tagline?: string; } declare const DEFAULT_AGENT_NAME = "agent"; declare const DEFAULT_AGENT_DESCRIPTION = "A helpful Poncho assistant"; declare const DEFAULT_TAGLINE = "a helpful assistant built with Poncho"; declare const DEFAULT_MODEL_PROVIDER: "anthropic"; declare const DEFAULT_MODEL_NAME = "claude-opus-4-5"; declare const DEFAULT_TEMPERATURE = 0.2; declare const DEFAULT_MAX_STEPS = 20; declare const DEFAULT_TIMEOUT = 300; /** * Returns the canonical default agent definition as a markdown string, * ready to pass to `new AgentHarness({ agentDefinition })`. This is the * exact same template `poncho init` writes to `AGENT.md`. */ declare const defaultAgentDefinition: (opts?: DefaultAgentDefinitionOptions) => string; declare const createDefaultTools: (workingDir: string) => ToolDefinition[]; declare const createWriteTool: (workingDir: string) => ToolDefinition; declare const createEditTool: (workingDir: string) => ToolDefinition; declare const createDeleteTool: (workingDir: string) => ToolDefinition; declare const createDeleteDirectoryTool: (workingDir: string) => ToolDefinition; declare const ponchoDocsTool: ToolDefinition; declare const PONCHO_UPLOAD_SCHEME = "poncho-upload://"; declare const VFS_SCHEME = "vfs://"; interface UploadStore { put(key: string, data: Buffer, mediaType: string): Promise; get(urlOrKey: string): Promise; delete(urlOrKey: string): Promise; } /** Derive a content-addressed key from file data. */ declare const deriveUploadKey: (data: Buffer, mediaType: string) => string; /** * Decode the `FileInput.data` field per its documented contract: it may be a * raw base64 string, a `data:;base64,<…>` URI, or an `https?://` URL. * Returns the decoded bytes. Older versions of the harness called * `Buffer.from(data, "base64")` unconditionally; that silently produced * garbage bytes for data URIs (the `:` / `;` / `,` in the prefix are not * valid base64 chars but Node's decoder ignores them rather than throwing). */ declare const decodeFileInputData: (data: string) => Promise; declare class LocalUploadStore implements UploadStore { private readonly uploadsDir; constructor(workingDir: string); put(_key: string, data: Buffer, mediaType: string): Promise; get(urlOrKey: string): Promise; delete(urlOrKey: string): Promise; } declare class VercelBlobUploadStore implements UploadStore { private sdk; private readonly workingDir?; private readonly access; constructor(workingDir?: string, access?: "public" | "private"); loadSdk(): Promise; put(key: string, data: Buffer, mediaType: string): Promise; get(urlOrKey: string): Promise; delete(urlOrKey: string): Promise; } declare class S3UploadStore implements UploadStore { private s3Sdk; private presignerSdk; private client; private readonly bucket; private readonly region?; private readonly endpoint?; private readonly workingDir?; constructor(bucket: string, region?: string, endpoint?: string, workingDir?: string); ensureClient(): Promise; put(key: string, data: Buffer, mediaType: string): Promise; get(urlOrKey: string): Promise; delete(urlOrKey: string): Promise; } declare const createUploadStore: (config: UploadsConfig | undefined, workingDir: string) => Promise; type TodoStatus = "pending" | "in_progress" | "completed"; type TodoPriority = "high" | "medium" | "low"; interface TodoItem { id: string; content: string; status: TodoStatus; priority: TodoPriority; createdAt: number; updatedAt: number; } interface TodoStore { get(conversationId: string): Promise; set(conversationId: string, todos: TodoItem[]): Promise; } type ReminderStatus = "pending" | "fired" | "cancelled"; type RecurrenceType = "daily" | "weekly" | "monthly" | "cron"; interface Recurrence { type: RecurrenceType; /** Repeat every N units (e.g. every 2 days). Defaults to 1. */ interval?: number; /** For weekly: which days (0=Sun … 6=Sat). */ daysOfWeek?: number[]; /** For type "cron": a 5-field cron expression. */ expression?: string; /** Stop recurring after this epoch-ms timestamp. */ endsAt?: number; /** Stop recurring after this many total firings. */ maxOccurrences?: number; } interface Reminder { id: string; task: string; scheduledAt: number; timezone?: string; status: ReminderStatus; createdAt: number; conversationId: string; ownerId?: string; tenantId?: string | null; recurrence?: Recurrence | null; occurrenceCount?: number; } interface ReminderCreateInput { task: string; scheduledAt: number; timezone?: string; conversationId: string; ownerId?: string; tenantId?: string | null; recurrence?: Recurrence | null; } interface ReminderStore { list(): Promise; create(input: ReminderCreateInput): Promise; update(id: string, fields: { scheduledAt?: number; occurrenceCount?: number; status?: ReminderStatus; }): Promise; cancel(id: string): Promise; delete(id: string): Promise; } /** * Given a reminder's current scheduledAt and its recurrence config, compute the * next fire time. Returns null if the recurrence is exhausted (maxOccurrences * reached or endsAt passed). */ declare const computeNextOccurrence: (reminder: Reminder) => number | null; declare const createReminderStore: (_agentId: string, _config?: StateConfig, _options?: { workingDir?: string; }) => ReminderStore; interface VfsStat { type: "file" | "directory" | "symlink"; size: number; mode: number; mimeType?: string; symlinkTarget?: string; createdAt: number; updatedAt: number; } interface VfsDirEntry { name: string; type: "file" | "directory" | "symlink"; } interface StorageEngine { /** Partition key: every read/write is scoped to this agent id. */ readonly agentId: string; /** Run migrations and prepare the storage backend. */ initialize(): Promise; /** Gracefully release resources. */ close(): Promise; conversations: { list(ownerId?: string, tenantId?: string | null): Promise; /** * Load a conversation WITHOUT the tool_result_archive blob. Use this on * read paths (UI loads, existence checks, etc.) — the archive can grow * unboundedly as tool calls accumulate, and most callers never touch it. */ get(conversationId: string): Promise; /** * Load a conversation WITH the tool_result_archive. Only use this when * starting/resuming a harness run — the archive needs to be reseeded so * the agent can retrieve previously-archived tool results by id. */ getWithArchive(conversationId: string): Promise; /** * Cheap column-level snapshot — no data blob, no heavy columns. For hot * polling paths. Returns undefined if the conversation doesn't exist. */ getStatusSnapshot(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; search(query: string, tenantId?: string | null): 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 `createdAt` to each entry, * persists them in order, and returns the stored entries. Additive — no * 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; }; memory: { get(tenantId?: string | null): Promise; update(content: string, tenantId?: string | null): Promise; }; todos: { get(conversationId: string): Promise; set(conversationId: string, todos: TodoItem[]): Promise; }; reminders: { list(tenantId?: string | null): Promise; create(input: ReminderCreateInput): Promise; update(id: string, fields: { scheduledAt?: number; occurrenceCount?: number; status?: ReminderStatus; }): Promise; cancel(id: string): Promise; delete(id: string): Promise; }; vfs: { readFile(tenantId: string, path: string): Promise; writeFile(tenantId: string, path: string, content: Uint8Array, mimeType?: string): Promise; appendFile(tenantId: string, path: string, content: Uint8Array): Promise; deleteFile(tenantId: string, path: string): Promise; deleteDir(tenantId: string, path: string, recursive?: boolean): Promise; stat(tenantId: string, path: string): Promise; readdir(tenantId: string, path: string): Promise; mkdir(tenantId: string, path: string, recursive?: boolean): Promise; rename(tenantId: string, oldPath: string, newPath: string): Promise; chmod(tenantId: string, path: string, mode: number): Promise; utimes(tenantId: string, path: string, mtime: Date): Promise; symlink(tenantId: string, target: string, linkPath: string): Promise; readlink(tenantId: string, path: string): Promise; lstat(tenantId: string, path: string): Promise; listAllPaths(tenantId: string): string[]; getUsage(tenantId: string): Promise<{ fileCount: number; totalBytes: number; }>; }; } /** * Read-only data source for a virtual mount whose contents don't live on * local disk. Lets a host (e.g. PonchOS) back a VFS prefix with a database * row set, object-store keys, or anything else expressible as * `(tenantId, relative) -> bytes/listing/stat`. * * All three methods are read-only; writes through the adapter still throw * `EROFS` for routed mounts the same way disk-backed mounts do (see * `routeToMount` checks in writeFile/mkdir/rm/cp/mv/chmod/utimes/symlink/link). * `relative` is the path within the mount; `""` means the mount root. */ interface MountProvider { /** List entries directly under `relative`. The mount root is `""`. */ readdir(tenantId: string, relative: string): Promise>; /** Stat a single entry. Throw ENOENT-like for missing paths. */ stat(tenantId: string, relative: string): Promise; /** Read raw bytes for a file entry. */ readFileBuffer(tenantId: string, relative: string): Promise; } /** * Read-only virtual mount mapping a VFS path prefix to either a local * filesystem directory (`source`) OR a custom provider (`provider`). * Exactly one of the two must be set. All read operations under the prefix * resolve via the chosen backend; writes throw. The prefix is normalised * internally to end with "/". */ interface VirtualMount { /** VFS prefix, e.g. "/system/". Leading slash required; trailing slash * optional (normalised). Must be a single non-root segment in practice * but no validation is enforced here. */ prefix: string; /** Absolute local FS path to serve from, e.g. "/srv/poncho/system". */ source?: string; /** Custom backend serving reads for this mount. Mutually exclusive with * `source` — set exactly one. Use when the data doesn't live on local * disk (e.g. database-backed upload listings). */ provider?: MountProvider; } declare class PonchoFsAdapter implements IFileSystem { private engine; private tenantId; private limits; private mounts; constructor(engine: StorageEngine, tenantId: string, limits: { maxFileSize: number; maxTotalStorage: number; }, mounts?: VirtualMount[]); /** Find which mount, if any, a normalised VFS path falls under. * Returns the relative path within the mount's source dir (empty string * when the path is exactly the mount root). */ private routeToMount; /** Treat `np` as a directory and return mount-root segments that should be * listed as virtual subdirectories. E.g. with mount "/system/", reading * "/" returns ["system"]; reading "/system" goes via routeToMount and * serves from local FS instead. */ private virtualChildrenAt; private toLocal; /** Build an FsStat from a node fs.Stats. */ private toFsStat; /** Synthesise a directory stat for a virtual ancestor (e.g. "/system" * when "/system/jobs/" is mounted but "/system" itself isn't a real dir * on disk). Used so `ls /` and `stat /system` work without surprises. */ private syntheticDirStat; readFile(path: string, _options?: { encoding?: BufferEncoding | null; } | BufferEncoding): Promise; readFileBuffer(path: string): Promise; exists(path: string): Promise; stat(path: string): Promise; readdir(path: string): Promise; readdirWithFileTypes(path: string): Promise>; writeFile(path: string, content: FileContent, _options?: { encoding?: BufferEncoding; } | BufferEncoding): Promise; appendFile(path: string, content: FileContent, _options?: { encoding?: BufferEncoding; } | BufferEncoding): Promise; mkdir(path: string, options?: MkdirOptions): Promise; rm(path: string, options?: RmOptions): Promise; cp(src: string, dest: string, options?: CpOptions): Promise; mv(src: string, dest: string): Promise; resolvePath(base: string, path: string): string; realpath(path: string): Promise; getAllPaths(): string[]; chmod(path: string, mode: number): Promise; utimes(path: string, _atime: Date, mtime: Date): Promise; symlink(target: string, linkPath: string): Promise; link(existingPath: string, newPath: string): Promise; readlink(path: string): Promise; lstat(path: string): Promise; } interface SecretsStore { get(tenantId: string): Promise>; set(tenantId: string, key: string, value: string): Promise; delete(tenantId: string, key: string): Promise; list(tenantId: string): Promise; } declare const createSecretsStore: (_agentId: string, signingKey: string, _config?: StateConfig, options?: { workingDir?: string; }) => SecretsStore; /** * Resolve an env var name: check tenant secrets first, then process.env. */ declare function resolveEnv(secretsStore: SecretsStore | undefined, tenantId: string | null | undefined, envName: string): Promise; declare const OPENAI_CODEX_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann"; interface OpenAICodexAuthConfig { refreshTokenEnv?: string; accessTokenEnv?: string; accessTokenExpiresAtEnv?: string; accountIdEnv?: string; authFilePathEnv?: string; } interface OpenAICodexSession { refreshToken: string; accessToken?: string; accessTokenExpiresAt?: number; accountId?: string; } declare const getOpenAICodexAuthFilePath: (config?: OpenAICodexAuthConfig) => string; declare const readOpenAICodexSession: (config?: OpenAICodexAuthConfig) => Promise; declare const writeOpenAICodexSession: (session: OpenAICodexSession, config?: OpenAICodexAuthConfig) => Promise; declare const deleteOpenAICodexSession: (config?: OpenAICodexAuthConfig) => Promise; declare const getOpenAICodexAccessToken: (config?: OpenAICodexAuthConfig) => Promise<{ accessToken: string; accountId?: string; }>; interface OpenAICodexDeviceAuthRequest { deviceAuthId: string; userCode: string; verificationUrl: string; intervalMs: number; } declare const getOpenAICodexRequiredScopes: () => string[]; declare const startOpenAICodexDeviceAuth: () => Promise; declare const completeOpenAICodexDeviceAuth: (request: OpenAICodexDeviceAuthRequest) => Promise; type ModelProviderFactory = (modelName: string) => LanguageModel; /** * Returns the context window size (in tokens) for a given model name. * Uses startsWith matching so dated variants (e.g. claude-opus-4-6-20260217) * resolve via the base prefix. Longest match wins. */ declare const getModelContextWindow: (modelName: string) => number; interface ProviderConfig { openai?: { apiKeyEnv?: string; }; openaiCodex?: OpenAICodexAuthConfig; anthropic?: { apiKeyEnv?: string; }; } /** * Creates a model provider factory for the specified AI provider. * API keys are read from environment variables; override the env var * name via the `providers` config in `poncho.config.js`. */ declare const createModelProvider: (provider?: string, config?: ProviderConfig) => ModelProviderFactory; interface SubagentResult { subagentId: string; status: "completed" | "error" | "stopped"; latestMessages?: Message[]; result?: RunResult; error?: AgentFailure; } interface SubagentSummary { subagentId: string; task: string; status: string; messageCount: number; } interface SubagentSpawnResult { subagentId: string; } type SubagentTranscriptMode = "final" | "assistant" | "full"; interface SubagentTranscript { subagentId: string; task: string; status: string; totalMessages: number; startIndex: number; messages: Message[]; truncated: boolean; } interface SubagentManager { spawn(opts: { task: string; parentConversationId: string; ownerId: string; tenantId?: string | null; /** Inherit the parent run's telemetry choice — when true, the subagent * run (and its re-runs) emit no telemetry. */ suppressTelemetry?: boolean; /** The id of the `spawn_subagent` tool call that produced this subagent, * so its events can carry `parentToolCallId` and a client can attach * subagent state to the spawning tool's pill. */ parentToolCallId?: string; }): Promise; sendMessage(subagentId: string, message: string): Promise; stop(subagentId: string): Promise; list(parentConversationId: string): Promise; getTranscript(opts: { subagentId: string; parentConversationId: string; mode: SubagentTranscriptMode; sinceIndex?: number; maxMessages?: number; }): Promise; } interface ToolCall { id: string; name: string; input: Record; } interface ToolExecutionResult { callId: string; tool: string; output?: unknown; error?: string; } declare class ToolDispatcher { private readonly tools; register(tool: ToolDefinition): void; registerMany(tools: ToolDefinition[]): void; unregister(name: string): void; unregisterMany(names: Iterable): void; list(): ToolDefinition[]; get(name: string): ToolDefinition | undefined; execute(call: ToolCall, context: ToolContext): Promise; executeBatch(calls: ToolCall[], context: ToolContext): Promise; } interface HarnessOptions { workingDir?: string; environment?: "development" | "staging" | "production"; toolDefinitions?: ToolDefinition[]; modelProvider?: ModelProviderFactory; uploadStore?: UploadStore; /** * Inject the agent definition directly instead of reading AGENT.md from * `workingDir`. Pass raw markdown (string) or a pre-parsed `ParsedAgent`. * When provided, `storageEngine` is also required — the engine's * `agentId` becomes the source of truth for partitioning, and the * filesystem identity dance (`ensureAgentIdentity`) is skipped. */ agentDefinition?: string | ParsedAgent; /** * Pre-constructed storage engine. When provided, the harness will not * create one internally. The engine's `agentId` is used wherever the * harness today reads `parsedAgent.frontmatter.id`. */ storageEngine?: StorageEngine; /** * Inject a `PonchoConfig` object directly instead of importing * `poncho.config.js` from `workingDir`. When provided, the disk-based * loader is skipped. Downstream resolvers (`resolveMemoryConfig`, * `resolveStateConfig`, etc.) run as today regardless of source. */ config?: PonchoConfig; /** * Read-only virtual mounts overlaid on the VFS. Each mount maps a VFS * prefix (e.g. "/system/") to a local filesystem directory; reads under * the prefix are served from local disk, writes are rejected. Used by * platforms like PonchOS to expose deployment-shipped defaults (system * jobs, system skills) without storing them in each tenant's VFS. * Empty by default — no system mounts in the CLI / dev workflow. */ virtualMounts?: VirtualMount[]; /** * Absolute directories of platform-shipped "system" skills. Each is * scanned for `/SKILL.md` at init; the bodies live on local disk * and ship with the deploy. System skills are surfaced in * `` like any other skill, but sit at the LOWEST * precedence: a tenant's own `/skills//` (and a repo skill) * overrides a system skill of the same name. Pair with a read-only * `virtualMounts` entry (e.g. "/system/skills/") if the same files * should also be browsable in the VFS. Empty by default. */ systemSkillPaths?: string[]; /** * Override the per-run hard wall-clock timeout, in seconds, taking * precedence over the agent definition's `limits.timeout`. Platforms use * this to give background subagents a longer budget than the foreground * agent without forking the agent definition (e.g. a 1h research subagent * vs. a 5-min foreground turn). `0` disables the hard timeout. */ runTimeoutSecOverride?: number; } interface HarnessRunOutput { runId: string; result: RunResult; events: AgentEvent[]; messages: Message[]; } interface ArchivedToolResult { toolResultId: string; conversationId: string; toolName: string; toolCallId: string; createdAt: number; sizeBytes: number; payload: string; } declare class AgentHarness { private readonly workingDir; private readonly environment; private readonly runTimeoutSecOverride?; private modelProvider; private readonly modelProviderInjected; private readonly dispatcher; readonly uploadStore?: UploadStore; private memoryStore?; private readonly tenantMemoryStores; private memoryConfig?; private todoStore?; reminderStore?: ReminderStore; secretsStore?: SecretsStore; private loadedConfig?; private readonly injectedConfig?; private loadedSkills; private systemSkills; private readonly systemSkillPaths; private skillFingerprint; private lastSkillRefreshAt; private readonly activeSkillNames; private readonly skillCache; private readonly vfsSkillCollisionWarnings; private readonly registeredMcpToolNames; private otlpSpanProcessor?; private otlpTracerProvider?; private hasOtlpExporter; /** End-user id (config.telemetry.userId) stamped as `user.id` on root spans. */ private telemetryUserId?; private _browserSession?; private _browserMod?; private parsedAgent?; private agentFileFingerprint; private injectedAgentDefinition?; private injectedStorageEngine; private mcpBridge?; private subagentManager?; private readonly archivedToolResultsByConversation; /** Last explicit `RunInput.volatileContext` per conversation, reused by * orchestrator-initiated turns (continuations, subagent-callback * resumes) that build their own RunInput and can't know the embedder's * volatile blocks. Values are small (the field's contract) and entries * live for the harness instance's lifetime. */ private readonly volatileContextByConversation; /** Unified storage engine (replaces individual KV-backed stores). */ storageEngine?: StorageEngine; /** Bash environment manager (creates per-tenant bash instances). */ private bashManager?; /** Read-only virtual mounts overlaid on the VFS. Empty by default. */ private virtualMounts; private resolveToolAccess; /** Returns the normalized {access, dispatch} mode for the tool. */ private resolveToolMode; private isToolEnabled; private registerIfMissing; /** * Register additional tools after construction (e.g. messaging adapter tools). * Existing tools with the same name are overwritten. * Tools disabled via `tools` config are skipped. */ registerTools(tools: ToolDefinition[]): void; unregisterTools(names: string[]): void; setSubagentManager(manager: SubagentManager): void; private registerConfiguredBuiltInTools; private createGetToolResultByIdTool; private createVfsAccess; private shouldEnableWriteTool; constructor(options?: HarnessOptions); get frontmatter(): AgentFrontmatter | undefined; getToolResultArchive(conversationId: string): Record; private seedToolResultArchive; /** * Guard a single FRESH tool result against overflowing the context window. * `serialized` is the JSON-serialized (media-stripped) output. Returns a * replacement value to put in front of the model (a handle or a truncated * preview) when the result is oversized, or `null` to leave it untouched. * Spilling writes the full payload to a VFS file; on any write failure it * falls back to inline truncation, so this never throws into the run loop. */ private guardOversizedToolResult; /** Best-effort: keep only the newest `keepLast` files in the spill dir. */ private pruneSpillDir; private truncateHistoricalToolResults; private shouldPreserveSkillToolResult; getTodos(conversationId: string): Promise; /** * Get a memory store, optionally scoped to a tenant. * Returns the default (agent-wide) store when tenantId is null/undefined. */ private getMemoryStore; private listActiveSkills; /** * Resolve the skill set visible to a given tenant. Three tiers, by * precedence: repo skills > the tenant's own VFS skills > platform * system skills. So a repo skill wins over a same-named VFS skill * (unchanged), and a tenant's `/skills//` overrides a same-named * system skill (the deploy-shipped default). Cached per tenant; cache * invalidates on VFS writes under /skills/ via invalidateSkillsForTenant. * System skills are static within a process, so they don't participate * in the fingerprint — but a VFS override does (it changes a /skills * path), which recomputes the cache and lets the override take effect. */ private getSkillsForTenant; invalidateSkillsForTenant(tenantId: string): void; private computeVfsSkillFingerprint; private getAgentMcpIntent; private getAgentScriptIntent; private getAgentMcpApprovalPatterns; private getAgentScriptApprovalPatterns; /** * Return the set of MCP server names that have at least one tool claimed by * any loaded skill's `allowedTools.mcp`. When ANY skill claims tools from a * server, the entire server is considered "skill-managed" — none of its tools * are auto-exposed globally; only explicitly declared tools become available * (via agent-level allowed-tools or active skill allowed-tools). */ private getSkillManagedMcpServers; private getRequestedMcpPatterns; private getRequestedScriptPatterns; private getRequestedMcpApprovalPatterns; private getRequestedScriptApprovalPatterns; private isScriptAllowedByPolicy; private isRootScriptAllowedByPolicy; private requiresApprovalForToolCall; private refreshMcpTools; private buildSkillFingerprint; private registerSkillTools; private static readonly SKILL_REFRESH_DEBOUNCE_MS; /** * Re-read AGENT.md and update the parsed agent when the file has changed * on disk. Returns `true` when the agent was actually re-parsed. * * Preserves the agent identity (id) across reloads so conversation * continuity isn't broken. */ private refreshAgentIfChanged; /** * Re-scan skill directories and update metadata, tools, and context window * when skills have changed on disk. Returns `true` when the skill set was * actually updated. * * @param force - bypass the time-based debounce (used for mid-run refreshes * after the agent may have written new skill files). */ private refreshSkillsIfChanged; initialize(): Promise; private buildBrowserStoragePersistence; private initBrowserTools; get browserSession(): unknown; shutdown(): Promise; listTools(): ToolDefinition[]; listSkills(): Array<{ name: string; description: string; }>; listSkillsForTenant(tenantId: string | undefined | null): Promise>; /** * Wraps the run() generator with an OTel root span (invoke_agent) so all * child spans (LLM calls via AI SDK, tool execution) group under one trace. */ runWithTelemetry(input: RunInput): AsyncGenerator; compact(messages: Message[], options?: CompactMessagesOptions): Promise; run(input: RunInput): AsyncGenerator; executeTools(calls: ToolCall[], context: ToolContext): Promise; continueFromToolResult(input: { messages: Message[]; toolResults: Array<{ callId: string; toolName: string; result?: unknown; error?: string; }>; conversationId?: string; /** Must be forwarded for the continuation run, otherwise tenant-scoped * tool stores (memory, VFS, todos) resolve the default "__default__" * tenant on resume instead of the caller's — e.g. memory_main_get * returns empty after an approval checkpoint. */ tenantId?: string; parameters?: Record; abortSignal?: AbortSignal; /** Emit no telemetry for the continuation run (e.g. resuming an * incognito turn after an approval). */ suppressTelemetry?: boolean; /** Per-run model override for the continuation run — same semantics as * `RunInput.model`. Forward the model the checkpointed run was using, * otherwise the continuation falls back to the agent definition's * (possibly concurrently-mutated) frontmatter model. */ model?: string; /** Same as `RunInput.volatileContext`. Pass it explicitly on resume — * the per-conversation capture covers same-process continuations, but * a checkpoint resumed after a restart would otherwise lose the * embedder's volatile blocks. */ volatileContext?: string; /** Same as `RunInput.telemetryAttributes`, for the continuation run. */ telemetryAttributes?: Record; }): AsyncGenerator; runToCompletion(input: RunInput): Promise; } /** * Converts a JSON Schema object to a Zod schema * * Supports: * - Primitives: string, number, integer, boolean, null * - Objects with properties * - Arrays * - Enums * - Required/optional fields * - Nested structures * * Falls back to z.any() for unsupported patterns */ declare function jsonSchemaToZod(schema: JsonSchema): z.ZodType; declare const createSearchTools: () => ToolDefinition[]; /** * Resolve the full list of skill directories to scan. * Merges the defaults with any extra paths provided via config. */ declare const resolveSkillDirs: (workingDir: string, extraPaths?: string[]) => string[]; type SkillSource = { kind: "repo"; } | { kind: "vfs"; tenantId: string; }; interface SkillMetadata { /** Unique skill name from frontmatter. */ name: string; /** What the skill does and when to use it. */ description: string; /** Tool intent declared in frontmatter (parsed from allowed-tools). */ allowedTools: { mcp: string[]; scripts: string[]; }; approvalRequired: { mcp: string[]; scripts: string[]; }; /** Where this skill came from. */ source: SkillSource; /** Absolute fs path (repo) or VFS path (vfs) to the skill directory. */ skillDir: string; /** Absolute fs path (repo) or VFS path (vfs) to the SKILL.md file. */ skillPath: string; } /** * @deprecated Use {@link SkillMetadata} instead. Kept for backward compatibility. */ type SkillContextEntry = SkillMetadata & { instructions: string; }; declare const parseSkillFrontmatter: (content: string) => { name: string; description: string; allowedTools: { mcp: string[]; scripts: string[]; }; approvalRequired: { mcp: string[]; scripts: string[]; }; } | undefined; declare const loadSkillMetadata: (workingDir: string, extraSkillPaths?: string[]) => Promise; declare const loadSkillMetadataFromDirs: (skillDirs: string[]) => Promise; declare const buildSkillContextWindow: (skills: SkillMetadata[]) => string; declare const loadVfsSkillMetadata: (engine: StorageEngine, tenantId: string) => Promise; declare const mergeSkills: (repoSkills: SkillMetadata[], vfsSkills: SkillMetadata[], onCollision?: (vfsSkill: SkillMetadata) => void) => SkillMetadata[]; declare const loadSkillInstructions: (skill: SkillMetadata, engine?: StorageEngine) => Promise; declare const readSkillResource: (skill: SkillMetadata, relativePath: string, engine?: StorageEngine) => Promise; declare const loadSkillContext: (workingDir: string) => Promise; interface CreateSkillToolsOptions { workingDir?: string; /** Resolve the skill set visible to a given tenant (repo + that tenant's VFS). */ getSkills: (tenantId: string | undefined | null) => Promise; /** Lazy accessor for the engine used for VFS reads when a skill's source is `vfs`. */ storageEngine?: () => StorageEngine | undefined; onActivateSkill?: (name: string) => Promise | string[]; onDeactivateSkill?: (name: string) => Promise | string[]; onListActiveSkills?: () => string[]; isScriptAllowed?: (skill: string, scriptPath: string) => boolean; isRootScriptAllowed?: (scriptPath: string) => boolean; } declare const createSkillTools: (options: CreateSkillToolsOptions) => ToolDefinition[]; declare const normalizeScriptPolicyPath: (relativePath: string) => string; declare const createReminderTools: (store: ReminderStore) => ToolDefinition[]; interface OtlpConfig { url: string; headers?: Record; } type OtlpOption = string | OtlpConfig; declare function normalizeOtlp(opt: OtlpOption | undefined): OtlpConfig | undefined; interface TelemetryConfig { enabled?: boolean; otlp?: OtlpOption; handler?: (event: AgentEvent) => Promise | void; } declare class TelemetryEmitter { private readonly config; constructor(config?: TelemetryConfig); emit(event: AgentEvent): Promise; private sendOtlp; } declare class InMemoryEngine implements StorageEngine { readonly agentId: string; private convs; private entries; private mem; private todoData; private reminderData; private vfsData; constructor(agentId: string); initialize(): Promise; close(): Promise; conversations: { list: (ownerId?: string, tenantId?: string | null) => Promise; get: (conversationId: string) => Promise; getWithArchive: (conversationId: string) => Promise; getStatusSnapshot: (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; search: (query: string, tenantId?: string | null) => Promise; appendSubagentResult: (conversationId: string, result: PendingSubagentResult) => Promise; clearCallbackLock: (conversationId: string) => Promise; listThreads: (parentConversationId: string) => Promise; appendEntries: (conversationId: string, _agentId: string, _tenantId: string | null, entries: NewConversationEntry[]) => Promise; readEntries: (conversationId: string, opts?: { types?: string[]; afterSeq?: number; limit?: number; }) => Promise; }; memory: { get: (tenantId?: string | null) => Promise; update: (content: string, tenantId?: string | null) => Promise; }; todos: { get: (conversationId: string) => Promise; set: (conversationId: string, todos: TodoItem[]) => Promise; }; reminders: { list: (tenantId?: string | null) => Promise; create: (input: ReminderCreateInput) => Promise; update: (id: string, fields: { scheduledAt?: number; occurrenceCount?: number; status?: ReminderStatus; }) => Promise; cancel: (id: string) => Promise; delete: (id: string) => Promise; }; vfs: { readFile: (tenantId: string, path: string) => Promise; writeFile: (tenantId: string, path: string, content: Uint8Array, mimeType?: string) => Promise; appendFile: (tenantId: string, path: string, content: Uint8Array) => Promise; deleteFile: (tenantId: string, path: string) => Promise; deleteDir: (tenantId: string, path: string, recursive?: boolean) => Promise; stat: (tenantId: string, path: string) => Promise; readdir: (tenantId: string, path: string) => Promise; mkdir: (tenantId: string, path: string, recursive?: boolean) => Promise; rename: (tenantId: string, oldPath: string, newPath: string) => Promise; chmod: (tenantId: string, path: string, mode: number) => Promise; utimes: (tenantId: string, path: string, mtime: Date) => Promise; symlink: (tenantId: string, target: string, linkPath: string) => Promise; readlink: (tenantId: string, path: string) => Promise; lstat: (tenantId: string, path: string) => Promise; listAllPaths: (tenantId: string) => string[]; getUsage: (tenantId: string) => Promise<{ fileCount: number; totalBytes: number; }>; }; private toSummary; private ensureParentDirs; private mkdirSingle; private resolveSymlink; } /** Tag used by migrations to branch on backend. */ type DialectTag = "sqlite" | "postgresql"; interface Dialect { tag: DialectTag; /** Return a positional parameter placeholder. 1-indexed. */ param(index: number): string; /** BLOB type name */ blob: string; /** JSON type name */ json: string; /** Current-timestamp expression */ now(): string; /** UPSERT conflict clause for a given PK column list */ upsert(pkCols: string[]): string; } interface QueryRow { [key: string]: unknown; } interface QueryExecutor { run(sql: string, params?: unknown[]): Promise; get(sql: string, params?: unknown[]): Promise; all(sql: string, params?: unknown[]): Promise; /** Execute raw SQL (for migrations). */ exec(sql: string): Promise; /** Run multiple statements in a transaction. */ transaction(fn: () => Promise): Promise; } interface EgressBucket { calls: number; bytes: number; } declare class ConversationEgressMeter { readonly read: Record; readonly write: Record; private lastLogAt; private readonly logIntervalMs; private readonly enabled; constructor(logIntervalMs?: number); trackRead(method: string, bytes: number): void; trackWrite(method: string, bytes: number): void; private maybeLog; flush(): void; } declare abstract class SqlStorageEngine implements StorageEngine { protected readonly dialect: Dialect; readonly agentId: string; protected abstract readonly executor: QueryExecutor; protected readonly egressMeter: ConversationEgressMeter; constructor(dialect: Dialect, agentId: string); initialize(): Promise; abstract close(): Promise; /** Flush egress stats before shutdown. Subclasses should call super. */ protected flushEgressStats(): void; /** Hook for subclass-specific setup (e.g. WAL mode). */ protected onBeforeInit(): Promise; private runMigrations; conversations: { list: (ownerId?: string, tenantId?: string | null) => Promise; get: (conversationId: string) => Promise; getStatusSnapshot: (conversationId: string) => Promise; 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; search: (query: string, tenantId?: string | null) => Promise; appendSubagentResult: (conversationId: string, result: PendingSubagentResult) => Promise; clearCallbackLock: (conversationId: string) => Promise; listThreads: (parentConversationId: string) => Promise; appendEntries: (conversationId: string, agentId: string, tenantId: string | null, entries: NewConversationEntry[]) => Promise; readEntries: (conversationId: string, opts?: { types?: string[]; afterSeq?: number; limit?: number; }) => Promise; }; memory: { get: (tenantId?: string | null) => Promise; update: (content: string, tenantId?: string | null) => Promise; }; todos: { get: (conversationId: string) => Promise; set: (conversationId: string, todos: TodoItem[]) => Promise; }; reminders: { list: (tenantId?: string | null) => Promise; create: (input: ReminderCreateInput) => Promise; update: (id: string, fields: { scheduledAt?: number; occurrenceCount?: number; status?: ReminderStatus; }) => Promise; cancel: (id: string) => Promise; delete: (id: string) => Promise; }; vfs: { readFile: (tenantId: string, path: string) => Promise; writeFile: (tenantId: string, path: string, content: Uint8Array, mimeType?: string) => Promise; appendFile: (tenantId: string, path: string, content: Uint8Array) => Promise; deleteFile: (tenantId: string, path: string) => Promise; deleteDir: (tenantId: string, path: string, recursive?: boolean) => Promise; stat: (tenantId: string, path: string) => Promise; readdir: (tenantId: string, path: string) => Promise; mkdir: (tenantId: string, path: string, recursive?: boolean) => Promise; rename: (tenantId: string, oldPath: string, newPath: string) => Promise; chmod: (tenantId: string, path: string, mode: number) => Promise; utimes: (tenantId: string, path: string, mtime: Date) => Promise; symlink: (tenantId: string, target: string, linkPath: string) => Promise; readlink: (tenantId: string, path: string) => Promise; lstat: (tenantId: string, path: string) => Promise; listAllPaths: (_tenantId: string) => string[]; getUsage: (tenantId: string) => Promise<{ fileCount: number; totalBytes: number; }>; }; private parseConversation; private rowToSummary; private rowToReminder; protected toUint8Array(value: unknown): Uint8Array; private ensureParentDirs; private mkdirSingle; private resolveSymlink; } declare class SqliteEngine extends SqlStorageEngine { private db; private readonly dbPath; protected readonly executor: QueryExecutor; constructor(options: { workingDir: string; agentId: string; dbPath?: string; }); protected onBeforeInit(): Promise; initialize(): Promise; close(): Promise; } declare class PostgresEngine extends SqlStorageEngine { private sql; private readonly urlEnv; protected readonly executor: QueryExecutor; /** In-memory path cache per tenant for sync getAllPaths(). */ private pathCache; constructor(options: { agentId: string; urlEnv?: string; }); protected onBeforeInit(): Promise; initialize(): Promise; close(): Promise; /** Refresh the path cache for a tenant (call before bash.exec()). */ refreshPathCache(tenantId: string): Promise; private patchVfs; private query; /** * Retry on transient connection-layer failures. Three attempts * with exponential-ish backoff (0, 50ms, 200ms) — the pool may * have multiple stale sockets accumulated during an idle period * (especially on managed Postgres after boot when no traffic * has flowed for a while), so a single retry can land on a * second stale socket and still fail. Three attempts virtually * always exhausts the staleness wave; if all three throw, the * failure is real and the caller should see it. * * Applied to every pg path the executor exposes: * - `query()` (run/get/all) — natural retry: queries are * idempotent at the connection-failure boundary because the * server-side rollback runs cleanly on socket close. * - `exec(sql)` for DDL — `CREATE TABLE IF NOT EXISTS` and * friends are idempotent by construction. * - `transaction(fn)` — only retried when the * CONNECTION_ENDED reject arrives *before* the transaction * body started executing on the connection; if it errors * mid-transaction, the postgres.js client surfaces a * different error class (the inner SQL error) and bypasses * this retry, preserving the all-or-nothing semantics. */ private runWithRetry; private addToPathCache; private removeFromPathCache; } type StorageProvider = "memory" | "sqlite" | "postgresql" | "local"; interface StorageFactoryOptions { provider?: StorageProvider; workingDir: string; agentId: string; /** Env var name for the PostgreSQL connection URL (default: DATABASE_URL). */ urlEnv?: string; /** Override the SQLite database file path. */ dbPath?: string; } declare function createStorageEngine(options: StorageFactoryOptions): StorageEngine; declare function createConversationStoreFromEngine(engine: StorageEngine): ConversationStore; declare function createMemoryStoreFromEngine(engine: StorageEngine, tenantId?: string | null): MemoryStore; declare function createTodoStoreFromEngine(engine: StorageEngine): TodoStore; declare function createReminderStoreFromEngine(engine: StorageEngine): ReminderStore; declare class BashEnvironmentManager { private engine; private limits; private environments; private filesystems; private readonly workingDir; private readonly bashOptions; private readonly virtualMounts; constructor(engine: StorageEngine, limits: { maxFileSize: number; maxTotalStorage: number; }, workingDir: string | null, bashConfig?: BashConfig, network?: NetworkConfig, virtualMounts?: VirtualMount[]); /** Return the combined IFileSystem (VFS + optional /project mount) for a tenant. */ getFs(tenantId: string): IFileSystem; getOrCreate(tenantId: string): Bash; getAdapter(tenantId: string): PonchoFsAdapter; /** Refresh the PostgreSQL path cache before a bash.exec() call. */ refreshPathCache(tenantId: string): Promise; destroy(tenantId: string): void; destroyAll(): void; } declare const createBashTool: (bashManager: BashEnvironmentManager) => ToolDefinition; interface TenantTokenPayload { tenantId: string; metadata?: Record; } /** * Verify a tenant JWT (HS256) signed with the given key. * Returns the decoded payload on success, or undefined on any failure. */ declare function verifyTenantToken(signingKey: string, token: string): Promise; declare const createSubagentTools: (manager: SubagentManager) => ToolDefinition[]; type HistorySource = "harness" | "continuation" | "messages"; type RunRequest = { conversationId: string; messages: Message[]; preferContinuation?: boolean; }; type RunOutcome = { source: HistorySource; shouldRebuildCanonical: boolean; messages: Message[]; }; declare const isMessageArray: (value: unknown) => value is Message[]; declare const loadCanonicalHistory: (conversation: Conversation) => { messages: Message[]; source: HistorySource; }; declare const loadRunHistory: (conversation: Conversation, options?: { preferContinuation?: boolean; }) => { messages: Message[]; source: HistorySource; shouldRebuildCanonical: boolean; }; declare const resolveRunRequest: (conversation: Conversation, request: RunRequest) => RunOutcome; type StoredApproval = NonNullable[number]; type PendingToolCall = { id: string; name: string; input: Record; }; type ApprovalEventItem = { approvalId: string; tool: string; toolCallId?: string; input: Record; }; type TurnSection = { type: "text" | "tools"; content: string | string[]; }; type TurnDraftState = { assistantResponse: string; toolTimeline: string[]; sections: TurnSection[]; currentTools: string[]; currentText: string; }; type ExecuteTurnResult = { latestRunId: string; runCancelled: boolean; runContinuation: boolean; runContinuationMessages?: Message[]; runHarnessMessages?: Message[]; runContextTokens: number; runContextWindow: number; runSteps: number; runMaxSteps?: number; draft: TurnDraftState; }; type TurnResultMetadata = { latestRunId: string; contextTokens: number; contextWindow: number; continuation?: boolean; continuationMessages?: Message[]; harnessMessages?: Message[]; toolResultArchive?: Conversation["_toolResultArchive"]; }; declare const createTurnDraftState: () => TurnDraftState; declare const cloneSections: (sections: TurnSection[]) => TurnSection[]; declare const flushTurnDraft: (draft: TurnDraftState) => void; /** Build enriched tool:completed text with input details (bash command, URL, etc.) */ declare const buildToolCompletedText: (event: AgentEvent & { type: "tool:completed"; }) => string; declare const stripPillMetaTokens: (line: string) => string; declare const recordStandardTurnEvent: (draft: TurnDraftState, event: AgentEvent) => void; declare const buildAssistantMetadata: (draft: TurnDraftState, sectionsOverride?: TurnSection[], opts?: { id?: string; timestamp?: number; }) => Message["metadata"] | undefined; declare const executeConversationTurn: ({ harness, runInput, events, initialContextTokens, initialContextWindow, onEvent, }: { harness: AgentHarness; runInput?: Parameters[0]; events?: AsyncIterable; initialContextTokens?: number; initialContextWindow?: number; onEvent?: (event: AgentEvent, draft: TurnDraftState) => void | Promise; }) => Promise; declare const normalizeApprovalCheckpoint: (approval: StoredApproval, fallbackMessages: Message[]) => StoredApproval; declare const buildApprovalCheckpoints: ({ approvals, runId, checkpointMessages, baseMessageCount, pendingToolCalls, kind, }: { approvals: ApprovalEventItem[]; runId: string; checkpointMessages: Message[]; baseMessageCount: number; pendingToolCalls: PendingToolCall[]; kind?: "approval" | "device"; }) => NonNullable; /** Reconstruct the full canonical transcript a checkpoint resumes from: the * prior history (before the checkpointed turn) + the checkpoint delta. * Handles both storage conventions via `normalizeApprovalCheckpoint` — the * initial checkpoint (base = prior length, delta) and a resume-created one * (base 0, full canonical). */ declare const assembleCheckpointMessages: (conversation: Conversation, checkpoint: StoredApproval) => Message[]; /** Pair an assistant tool-call message's `tool_calls` with externally-computed * results into the single `role:"tool"` message a continuation reads. * Returns undefined when `assistantMsg` isn't an assistant message with * parseable tool calls. Used to persist the resume's canonical history so it * matches what `continueFromToolResult` fed the model. Missing results * default to the deferred-error marker (same text the run uses). */ declare const buildToolResultMessage: (assistantMsg: Message | undefined, toolResults: Array<{ callId: string; toolName: string; result?: unknown; error?: string; }>) => Message | undefined; /** Build the `pendingApprovals` rows for a checkpoint reached DURING a resume * continuation. Stores the WHOLE canonical history the continuation ran with * (`priorMessages` = prior + tool result + new delta) with * `baseMessageCount: 0`. Keeping the full history here — rather than a delta * + a base count into a different message array — is what lets the next * resume reconstruct with no index arithmetic. */ declare const buildResumeCheckpoints: ({ priorMessages, checkpointEvent, runId, kind, }: { priorMessages: Message[]; checkpointEvent: { approvals: ApprovalEventItem[]; checkpointMessages: Message[]; pendingToolCalls: PendingToolCall[]; }; runId: string; kind?: "approval" | "device"; }) => NonNullable; declare const applyTurnMetadata: (conv: Conversation, meta: TurnResultMetadata, opts?: { clearContinuation?: boolean; clearApprovals?: boolean; setIdle?: boolean; shouldRebuildCanonical?: boolean; }) => void; declare const TOOL_RESULT_ARCHIVE_PARAM = "__toolResultArchive"; declare const withToolResultArchiveParam: (parameters: Record | undefined, conversation: Conversation) => Record; declare const MAX_CONTINUATION_COUNT = 20; type ActiveSubagentRun = { abortController: AbortController; harness: AgentHarness; parentConversationId: string; }; type PendingSubagentApproval = { resolve: (decidedApprovals: NonNullable) => void; childHarness: AgentHarness; checkpoint: NonNullable[number]; childConversationId: string; parentConversationId: string; }; /** root -> L1 -> L2 = 3 levels; L2 cannot spawn further */ declare const MAX_SUBAGENT_NESTING = 3; declare const MAX_CONCURRENT_SUBAGENTS = 2; declare const MAX_SUBAGENT_CALLBACK_COUNT = 20; declare const CALLBACK_LOCK_STALE_MS: number; declare const STALE_SUBAGENT_THRESHOLD_MS: number; /** * Find the last non-empty assistant text in a subagent transcript. Walking * backwards (rather than reading only the final message) means a subagent * that ended on a tool-call turn still yields the prose it produced just * before — instead of surfacing to the parent as an empty result. */ declare const lastAssistantText: (messages: Message[]) => string; /** * The run loop stuffs a synthetic `[Error: ...]` placeholder into the draft / * persisted assistant text when a run ends on `run:error` (e.g. a timeout). * That placeholder is not real model output — strip it so we don't surface it * to the parent as the subagent's "response". */ declare const realResponseText: (text: string | undefined) => string; /** * Build the result text delivered to the parent when a subagent ended * abnormally (timeout / error) with no RunResult. We never drop the work it * gathered, and the parent is told it didn't finish — e.g. it may not have * written its output files — plus how to recover (use what's here, send a * write-only follow-up, or read the full transcript). */ declare const abnormalEndResponse: (opts: { subagentId: string; gathered: string; runError?: { code?: string; message?: string; }; }) => string; type ActiveConversationRun = { ownerId: string; abortController: AbortController; runId: string | null; }; type EventSink = (conversationId: string, event: AgentEvent) => void | Promise; interface OrchestratorHooks { /** Called before a continuation run starts. Resets/creates event streams. */ onContinuationStart?(conversationId: string): void; /** Called after a continuation run finishes. Cleans up event streams. */ onContinuationEnd?(conversationId: string): void; /** Called when an approval checkpoint is stored during resumeRunFromCheckpoint. * Transport layer can use this for platform-specific notifications (e.g. Telegram). */ onApprovalCheckpoint?(conversationId: string, approvals: Array<{ approvalId: string; tool: string; input: Record; }>): void; /** Called after resumeRunFromCheckpoint completes. Transport layer can check * for pending subagent callbacks and manage stream lifecycle. * @deprecated Orchestrator handles post-resume subagent work internally in Phase 5+. */ onResumeComplete?(conversationId: string, checkpointedRun: boolean): void; /** Create a child AgentHarness for subagent execution. Required for subagent support. */ createChildHarness?(): Promise; /** Build recall parameters injected into run parameters for conversation context. */ buildRecallParams?(opts: { ownerId: string; tenantId?: string | null; excludeConversationId: string; }): Record; /** Dispatch a background task via serverless self-fetch. If not provided, * the orchestrator calls methods directly (long-lived mode). */ dispatchBackground?(type: "subagent-run" | "subagent-callback" | "continuation", conversationId: string): void; /** Called when a conversation's event stream should be closed/finished. */ onStreamEnd?(conversationId: string): void; /** Called when processSubagentCallback needs to open/reset the parent's event stream. */ onCallbackStreamReset?(conversationId: string): void; /** Notify a messaging platform about a subagent callback result. */ onMessagingNotify?(conversationId: string, text: string): void; } /** @deprecated Use OrchestratorHooks instead */ type ContinuationHooks = OrchestratorHooks; interface OrchestratorOptions { harness: AgentHarness; conversationStore: ConversationStore; eventSink: EventSink; telemetry?: TelemetryEmitter; hooks?: OrchestratorHooks; /** @deprecated Use hooks instead */ continuationHooks?: OrchestratorHooks; /** Agent identity ID for tool context. Falls back to harness frontmatter ID. */ agentId?: string; /** Working directory for tool context. */ workingDir?: string; } declare class AgentOrchestrator { readonly harness: AgentHarness; readonly conversationStore: ConversationStore; readonly eventSink: EventSink; readonly telemetry?: TelemetryEmitter; /** @internal */ hooks?: OrchestratorHooks; private readonly agentId; private readonly workingDir; readonly activeConversationRuns: Map; readonly runOwners: Map; readonly runConversations: Map; readonly approvalDecisionTracker: Map>; readonly activeSubagentRuns: Map; readonly recentlySpawnedParents: Map; readonly pendingSubagentApprovals: Map; readonly pendingCallbackNeeded: Set; constructor(options: OrchestratorOptions); setHooks(hooks: OrchestratorHooks): void; /** @deprecated Use setHooks instead */ setContinuationHooks(hooks: OrchestratorHooks): void; private get isServerless(); runContinuation(conversationId: string, onYield?: (event: AgentEvent) => void | Promise): Promise; runChatContinuation(conversationId: string, conversation: Conversation, continuationMessages: Message[], onYield?: (event: AgentEvent) => void | Promise): Promise; findPendingApproval(approvalId: string, owner: string): Promise<{ conversation: Conversation; approval: StoredApproval; } | undefined>; resumeRunFromCheckpoint(conversationId: string, conversation: Conversation, checkpoint: StoredApproval, toolResults: Array<{ callId: string; toolName: string; result?: unknown; error?: string; }>): Promise; /** After a resume completes, check for deferred subagent callbacks. */ private _handlePostResumeWork; hasRunningSubagentsForParent(parentConversationId: string): boolean; getRunningSubagentCountForParent(parentId: string): number; getSubagentDepth(conversationId: string): Promise; hasPendingSubagentWorkForParent(parentConversationId: string, _owner: string): Promise; /** * Submit an approval decision for a pending subagent approval. * Returns whether the approval was found, the child conversation, and whether all approvals are now decided. */ submitSubagentApprovalDecision(approvalId: string, approved: boolean): Promise<{ found: boolean; childConversationId?: string; allDecided: boolean; }>; handleSubagentCompletion(subagentId: string): Promise; resumeSubagentFromCheckpoint(subagentId: string): Promise; runSubagent(childConversationId: string, parentConversationId: string, task: string, ownerId: string): Promise; triggerParentCallback(parentConversationId: string): Promise; processSubagentCallback(conversationId: string, skipLockCheck?: boolean): Promise; runSubagentContinuation(conversationId: string, conversation: Conversation, continuationMessages: Message[]): AsyncGenerator; createSubagentManager(): SubagentManager; /** * Append a subagent result to its parent, retrying once on a transient * store failure before giving up loudly. A silently dropped result is the * worst subagent failure mode — the parent waits forever on a subagent it * thinks is still running — so this never swallows the error the way the * old `.catch(() => {})` call sites did. Returns whether the result landed. */ private appendSubagentResultReliable; /** * A subagent's fire-and-forget background run rejected outside its own * error handling (e.g. it threw before entering its try block, or the * catch block itself threw). Without this the parent is left waiting on a * subagent that will never report back. Record the failure on the child * and hand the parent an error result so the turn can resume. */ private handleSpawnFailure; recoverStaleSubagents(): Promise; } interface RunConversationTurnOpts { /** Initialised harness instance. */ harness: AgentHarness; /** Conversation store backing the turn (typically `engine.conversations` from a StorageEngine). */ conversationStore: ConversationStore; conversationId: string; /** The user's new message text. Required (use `""` if you only want to attach files). */ task: string; /** * Optional file attachments (FileInput.data is base64 / data URI / https URL). * Files are uploaded via `harness.uploadStore` first so the persisted user * message references stable URLs instead of fat base64 blobs. */ files?: FileInput[]; /** * Extra parameters merged into runInput.parameters. Use this for recall * corpus, archive lookup keys, messaging metadata, etc. Do NOT include * `__activeConversationId`, `__ownerId`, or the tool-result-archive — the * helper sets those itself. */ parameters?: Record; abortSignal?: AbortSignal; tenantId?: string | null; /** * Forwarded to `RunInput.disablePromptCache`. Only worth it for runs * that are both single-step and one-shot — see the RunInput doc; a * multi-step run reads its own growing history through the tail * breakpoint, so disabling it costs more than the write it saves. */ disablePromptCache?: boolean; /** * Forwarded to `RunInput.volatileContext`: per-run context appended to * the uncached dynamic tail of the system prompt. Keep it small — it is * re-sent raw every step. Also captured per conversation so * orchestrator-initiated turns (subagent-callback resumes) reuse the * value from the turn that spawned the subagent. */ volatileContext?: string; /** * Forwarded to `RunInput.suppressTelemetry`. Set true to emit no telemetry * for this run (e.g. an incognito / telemetry-off turn) even on a harness * built with an OTLP exporter attached. */ suppressTelemetry?: boolean; /** * Forwarded to `RunInput.maxSteps`: per-run step-ceiling override. Lets the * foreground chat turn run a higher ceiling than background/job turns that * share the same agent definition. */ maxSteps?: number; /** * Forwarded to `RunInput.telemetryAttributes` — extra attributes for the * `invoke_agent` root span (e.g. run kind / job name for segmentation). */ telemetryAttributes?: Record; /** * Forwarded to `RunInput.model`. Per-run model override, captured once at * run start — safe under concurrent runs on a shared harness, unlike * mutating the parsed agent's frontmatter. */ model?: string; /** Per-event hook — called for every AgentEvent yielded by the run, in order. */ onEvent?: (event: AgentEvent) => void | Promise; } interface RunConversationTurnResult { /** runId of the most recent run started during this turn. */ latestRunId: string; /** True if the run was cancelled (via abortSignal or run:cancelled event). */ cancelled: boolean; /** True if the run errored. The error has been emitted via onEvent as run:error. */ errored: boolean; /** True if the run requested a continuation. Caller is responsible for triggering the continuation. */ continuation: boolean; /** True if the run paused at a tool-approval checkpoint. */ checkpointed: boolean; contextTokens: number; contextWindow: number; } declare const runConversationTurn: (opts: RunConversationTurnOpts) => Promise; type NewEntryNoId = NewConversationEntry extends infer T ? T extends NewConversationEntry ? Omit : never : never; /** * Append entries to the conversation's queue. Best-effort by contract: * - stamps a fresh uuid `id` on each entry (required input column), * - never throws (logs and returns [] on failure), * - safe to `void` when the caller doesn't need the stored rows. * * Returns the stored entries (with seq/createdAt) — the callback path needs * the seqs to record consumption. */ declare const appendEntriesSafe: (store: ConversationStore, conversation: Pick, entries: NewEntryNoId[], log: Logger) => Promise; export { type ActiveConversationRun, type ActiveSubagentRun, type AgentFrontmatter, AgentHarness, type AgentIdentity, type AgentLimitsConfig, type AgentModelConfig, AgentOrchestrator, type ApprovalEventItem, type ArchivedToolResult$1 as ArchivedToolResult, type BashConfig, BashEnvironmentManager, type BashExecutionLimits, type BuiltInToolToggles, CALLBACK_LOCK_STALE_MS, type CallbackStartedEntry, type CompactMessagesOptions, type CompactResult, type CompactionConfig, type ContinuationHooks, type Conversation, type ConversationCreateInit, type ConversationEntry, type ConversationState, type ConversationStatusSnapshot, type ConversationStore, type ConversationSummary, type CreateSkillToolsOptions, type CronJobConfig, DEFAULT_AGENT_DESCRIPTION, DEFAULT_AGENT_NAME, DEFAULT_MAX_STEPS, DEFAULT_MODEL_NAME, DEFAULT_MODEL_PROVIDER, DEFAULT_TAGLINE, DEFAULT_TEMPERATURE, DEFAULT_TIMEOUT, type DefaultAgentDefinitionOptions, type EventSink, type ExecuteTurnResult, type HarnessOptions, type HarnessRunOutput, type HistorySource, InMemoryConversationStore, InMemoryEngine, InMemoryStateStore, type IsolateBinding, type IsolateConfig, LocalMcpBridge, LocalUploadStore, MAX_CONCURRENT_SUBAGENTS, MAX_CONTINUATION_COUNT, MAX_SUBAGENT_CALLBACK_COUNT, MAX_SUBAGENT_NESTING, type MainMemory, type McpConfig, type MemoryConfig, type MemoryStore, type MessagingChannelConfig, type ModelProviderFactory, type MountProvider, type NetworkConfig, type NewConversationEntry, OPENAI_CODEX_CLIENT_ID, type OpenAICodexAuthConfig, type OpenAICodexDeviceAuthRequest, type OpenAICodexSession, type OrchestratorHooks, type OrchestratorOptions, type OtlpConfig, type OtlpOption, PONCHO_UPLOAD_SCHEME, type ParsedAgent, type PendingSubagentApproval, type PendingSubagentResult, type PendingToolCall, type PonchoConfig, PonchoFsAdapter, PostgresEngine, type ProviderConfig, type Recurrence, type RecurrenceType, type Reminder, type ReminderCreateInput, type ReminderStatus, type ReminderStore, type RemoteMcpServerConfig, type RunConversationTurnOpts, type RunConversationTurnResult, type RunOutcome, type RunRequest, type RuntimeRenderContext, S3UploadStore, STALE_SUBAGENT_THRESHOLD_MS, STORAGE_SCHEMA_VERSION, type SecretsStore, type SkillContextEntry, type SkillMetadata, type SkillSource, SqliteEngine, type StateConfig, type StateProviderName, type StateStore, type StorageConfig, type StorageEngine, type StorageFactoryOptions, type StorageProvider, type StoredApproval, type SubagentManager, type SubagentResult, type SubagentResultEntry, type SubagentSpawnResult, type SubagentSummary, type SubagentTaskOutcome, type SubagentTranscript, type SubagentTranscriptMode, TOOL_RESULT_ARCHIVE_PARAM, type TelemetryConfig, TelemetryEmitter, type TenantTokenPayload, type ToolAccess, type ToolCall, ToolDispatcher, type ToolExecutionResult, type TurnDraftState, type TurnResultMetadata, type TurnSection, type UploadStore, type UploadsConfig, VFS_SCHEME, VercelBlobUploadStore, type VfsDirEntry, type VfsStat, type VirtualMount, abnormalEndResponse, appendEntriesSafe, applyTurnMetadata, assembleCheckpointMessages, buildAgentDirectoryName, buildApprovalCheckpoints, buildAssistantMetadata, buildResumeCheckpoints, buildSkillContextWindow, buildToolCompletedText, buildToolResultMessage, cloneSections, compactMessages, completeOpenAICodexDeviceAuth, computeNextOccurrence, createBashTool, createConversationStore, createConversationStoreFromEngine, createDefaultTools, createDeleteDirectoryTool, createDeleteTool, createEditTool, createMemoryStore, createMemoryStoreFromEngine, createMemoryTools, createModelProvider, createReminderStore, createReminderStoreFromEngine, createReminderTools, createSearchTools, createSecretsStore, createSkillTools, createStateStore, createStorageEngine, createSubagentTools, createTodoStoreFromEngine, createTurnDraftState, createUploadStore, createWriteTool, decodeFileInputData, defaultAgentDefinition, deleteOpenAICodexSession, deriveUploadKey, ensureAgentIdentity, estimateTokens, estimateTotalTokens, executeConversationTurn, findSafeSplitPoint, findSafeSplitPointByTurns, flushTurnDraft, generateAgentId, getAgentStoreDirectory, getModelContextWindow, getOpenAICodexAccessToken, getOpenAICodexAuthFilePath, getOpenAICodexRequiredScopes, getPendingSubagentResults, getPonchoStoreRoot, isMessageArray, jsonSchemaToZod, lastAssistantText, loadCanonicalHistory, loadPonchoConfig, loadRunHistory, loadSkillContext, loadSkillInstructions, loadSkillMetadata, loadSkillMetadataFromDirs, loadVfsSkillMetadata, mergeSkills, normalizeApprovalCheckpoint, normalizeOtlp, normalizeScriptPolicyPath, normalizeToolAccess, parseAgentFile, parseAgentMarkdown, parseSkillFrontmatter, ponchoDocsTool, readOpenAICodexSession, readSkillResource, realResponseText, recordStandardTurnEvent, renderAgentPrompt, resolveAgentIdentity, resolveCompactionConfig, resolveEnv, resolveMemoryConfig, resolveRunRequest, resolveSkillDirs, resolveStateConfig, runConversationTurn, slugifyStorageComponent, startOpenAICodexDeviceAuth, stripPillMetaTokens, verifyTenantToken, withToolResultArchiveParam, writeOpenAICodexSession };