omk-agent-core 0.98.1 → 0.98.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +644 -0
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +3 -5
- package/dist/agent.js.map +1 -1
- package/dist/effects/effect-journal.d.ts +43 -0
- package/dist/effects/effect-journal.d.ts.map +1 -0
- package/dist/effects/effect-journal.js +186 -0
- package/dist/effects/effect-journal.js.map +1 -0
- package/dist/effects/effect-recovery.d.ts +70 -0
- package/dist/effects/effect-recovery.d.ts.map +1 -0
- package/dist/effects/effect-recovery.js +120 -0
- package/dist/effects/effect-recovery.js.map +1 -0
- package/dist/effects/effect-transitions.d.ts +34 -0
- package/dist/effects/effect-transitions.d.ts.map +1 -0
- package/dist/effects/effect-transitions.js +148 -0
- package/dist/effects/effect-transitions.js.map +1 -0
- package/dist/effects/effect-types.d.ts +135 -0
- package/dist/effects/effect-types.d.ts.map +1 -0
- package/dist/effects/effect-types.js +32 -0
- package/dist/effects/effect-types.js.map +1 -0
- package/dist/harness/abort-delivery.d.ts +26 -0
- package/dist/harness/abort-delivery.d.ts.map +1 -0
- package/dist/harness/abort-delivery.js +36 -0
- package/dist/harness/abort-delivery.js.map +1 -0
- package/dist/harness/agent-harness.d.ts +38 -6
- package/dist/harness/agent-harness.d.ts.map +1 -1
- package/dist/harness/agent-harness.js +327 -325
- package/dist/harness/agent-harness.js.map +1 -1
- package/dist/harness/canonical-digest.d.ts +32 -0
- package/dist/harness/canonical-digest.d.ts.map +1 -0
- package/dist/harness/canonical-digest.js +164 -0
- package/dist/harness/canonical-digest.js.map +1 -0
- package/dist/harness/compaction/operation.d.ts +7 -0
- package/dist/harness/compaction/operation.d.ts.map +1 -1
- package/dist/harness/compaction/operation.js.map +1 -1
- package/dist/harness/deferred-commands.d.ts +53 -0
- package/dist/harness/deferred-commands.d.ts.map +1 -0
- package/dist/harness/deferred-commands.js +96 -0
- package/dist/harness/deferred-commands.js.map +1 -0
- package/dist/harness/harness-session.d.ts +5 -58
- package/dist/harness/harness-session.d.ts.map +1 -1
- package/dist/harness/harness-session.js +15 -18
- package/dist/harness/harness-session.js.map +1 -1
- package/dist/harness/operation-lifecycle-controller.d.ts +68 -0
- package/dist/harness/operation-lifecycle-controller.d.ts.map +1 -0
- package/dist/harness/operation-lifecycle-controller.js +199 -0
- package/dist/harness/operation-lifecycle-controller.js.map +1 -0
- package/dist/harness/operation-lifecycle-reducer.d.ts +19 -0
- package/dist/harness/operation-lifecycle-reducer.d.ts.map +1 -0
- package/dist/harness/operation-lifecycle-reducer.js +201 -0
- package/dist/harness/operation-lifecycle-reducer.js.map +1 -0
- package/dist/harness/operation-lifecycle-types.d.ts +130 -0
- package/dist/harness/operation-lifecycle-types.d.ts.map +1 -0
- package/dist/harness/operation-lifecycle-types.js +34 -0
- package/dist/harness/operation-lifecycle-types.js.map +1 -0
- package/dist/harness/operation-outcome.d.ts +79 -0
- package/dist/harness/operation-outcome.d.ts.map +1 -0
- package/dist/harness/operation-outcome.js +167 -0
- package/dist/harness/operation-outcome.js.map +1 -0
- package/dist/harness/operation-trace-divergence.d.ts +60 -0
- package/dist/harness/operation-trace-divergence.d.ts.map +1 -0
- package/dist/harness/operation-trace-divergence.js +199 -0
- package/dist/harness/operation-trace-divergence.js.map +1 -0
- package/dist/harness/operation-trace.d.ts +134 -0
- package/dist/harness/operation-trace.d.ts.map +1 -0
- package/dist/harness/operation-trace.js +161 -0
- package/dist/harness/operation-trace.js.map +1 -0
- package/dist/harness/session-write-coordinator.d.ts +76 -0
- package/dist/harness/session-write-coordinator.d.ts.map +1 -0
- package/dist/harness/session-write-coordinator.js +126 -0
- package/dist/harness/session-write-coordinator.js.map +1 -0
- package/dist/harness/subscriber-fanout.d.ts +50 -0
- package/dist/harness/subscriber-fanout.d.ts.map +1 -0
- package/dist/harness/subscriber-fanout.js +92 -0
- package/dist/harness/subscriber-fanout.js.map +1 -0
- package/dist/harness/tree-navigation.d.ts +45 -0
- package/dist/harness/tree-navigation.d.ts.map +1 -0
- package/dist/harness/tree-navigation.js +59 -0
- package/dist/harness/tree-navigation.js.map +1 -0
- package/dist/harness/types.d.ts +34 -3
- package/dist/harness/types.d.ts.map +1 -1
- package/dist/harness/types.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/listener-delivery.d.ts +22 -0
- package/dist/listener-delivery.d.ts.map +1 -0
- package/dist/listener-delivery.js +36 -0
- package/dist/listener-delivery.js.map +1 -0
- package/package.json +4 -3
package/dist/agent.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,YAAY,EACjB,KAAK,OAAO,EAEZ,KAAK,mBAAmB,EAGxB,KAAK,eAAe,EACpB,KAAK,SAAS,EACd,MAAM,QAAQ,CAAC;AAGhB,OAAO,KAAK,EACX,oBAAoB,EACpB,mBAAmB,EAEnB,UAAU,EACV,eAAe,EACf,mBAAmB,EACnB,YAAY,EACZ,UAAU,EAEV,qBAAqB,EACrB,oBAAoB,EACpB,SAAS,EACT,QAAQ,EACR,iBAAiB,EACjB,MAAM,YAAY,CAAC;AAEpB,YAAY,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AA2D5C,iDAAiD;AACjD,MAAM,WAAW,YAAY;IAC5B,YAAY,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,UAAU,EAAE,kBAAkB,GAAG,aAAa,GAAG,kBAAkB,GAAG,cAAc,CAAC,CAAC,CAAC;IACnH,YAAY,CAAC,EAAE,CAAC,QAAQ,EAAE,YAAY,EAAE,KAAK,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;IAC5E,gBAAgB,CAAC,EAAE,CAAC,QAAQ,EAAE,YAAY,EAAE,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,aAAa;CA8D3B","sourcesContent":["import {\n\ttype ImageContent,\n\ttype Message,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"omk-ai\";\nimport { planFailureTermination, runAgentLoop, runAgentLoopContinue } from \"./agent-loop.ts\";\nimport { createImmutableSnapshot } from \"./tool-execution-boundary.ts\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tQueueMode,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.ts\";\n\nexport type { QueueMode } from \"./types.ts\";\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) => message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\",\n\t);\n}\n\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\nfunction createMutableAgentState(\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>,\n): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\n\treturn {\n\t\tsystemPrompt: initialState?.systemPrompt ?? \"\",\n\t\tsystemPromptCacheBoundary: initialState?.systemPromptCacheBoundary,\n\t\tsystemPromptCacheBoundaryBypass: initialState?.systemPromptCacheBoundaryBypass,\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tprepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\tmaxTurns?: AgentLoopConfig[\"maxTurns\"];\n\ttoolExecution?: ToolExecutionMode;\n\ttoolTimeoutMs?: AgentLoopConfig[\"toolTimeoutMs\"];\n\ttoolTimeouts?: AgentLoopConfig[\"toolTimeouts\"];\n\ttoolScheduler?: AgentLoopConfig[\"toolScheduler\"];\n\tmaxToolConcurrency?: AgentLoopConfig[\"maxToolConcurrency\"];\n\tstrictExtensionClaims?: AgentLoopConfig[\"strictExtensionClaims\"];\n\tcwd?: AgentLoopConfig[\"cwd\"];\n\tresourceKeyResolver?: AgentLoopConfig[\"resourceKeyResolver\"];\n\ttoolExecutionPolicy?: AgentLoopConfig[\"toolExecutionPolicy\"];\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\tpublic mode: QueueMode;\n\n\tconstructor(mode: QueueMode) {\n\t\tthis.mode = mode;\n\t}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.messages.slice();\n\t\t\tthis.messages = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.messages[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.messages = this.messages.slice(1);\n\t\treturn [first];\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFn: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic prepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Optional provider-turn budget for each prompt or continuation run. */\n\tpublic maxTurns?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\n\tpublic toolExecution: ToolExecutionMode;\n\t/** Default execution timeout for tools; provider request timeout remains separate. */\n\tpublic toolTimeoutMs?: number;\n\t/** Per-tool-name execution timeout overrides. */\n\tpublic toolTimeouts?: Record<string, number>;\n\t/** Deterministic tool scheduler selection. */\n\tpublic toolScheduler: NonNullable<AgentLoopConfig[\"toolScheduler\"]>;\n\t/** Optional dag-v2 concurrency cap. */\n\tpublic maxToolConcurrency?: number;\n\t/** Require explicit resource claims for parallel extension tools. */\n\tpublic strictExtensionClaims: boolean;\n\t/** Working directory used to resolve path-scoped resource claims. */\n\tpublic cwd?: string;\n\t/** Optional dag-v2 platform identity resolver for path-claim aliases. */\n\tpublic resourceKeyResolver?: AgentLoopConfig[\"resourceKeyResolver\"];\n\t/** Execution-policy defaults (late-settlement audit policy). */\n\tpublic toolExecutionPolicy?: AgentLoopConfig[\"toolExecutionPolicy\"];\n\n\tconstructor(options: AgentOptions = {}) {\n\t\tthis._state = createMutableAgentState(options.initialState);\n\t\tthis.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = options.transformContext;\n\t\tthis.streamFn = options.streamFn ?? streamSimple;\n\t\tthis.getApiKey = options.getApiKey;\n\t\tthis.onPayload = options.onPayload;\n\t\tthis.onResponse = options.onResponse;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.prepareNextTurn = options.prepareNextTurn;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.maxTurns = options.maxTurns;\n\t\tthis.toolExecution = options.toolExecution ?? \"parallel\";\n\t\tthis.toolTimeoutMs = options.toolTimeoutMs;\n\t\tthis.toolTimeouts = options.toolTimeouts;\n\t\tthis.toolScheduler = options.toolScheduler ?? \"dag-v2\";\n\t\tthis.maxToolConcurrency = options.maxToolConcurrency;\n\t\tthis.strictExtensionClaims = options.strictExtensionClaims ?? false;\n\t\tthis.cwd = options.cwd;\n\t\tthis.resourceKeyResolver = options.resourceKeyResolver;\n\t\tthis.toolExecutionPolicy = options.toolExecutionPolicy;\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order except for\n\t * observation-only `tool_execution_update` delivery, which is detached so a\n\t * listener cannot delay timeout/abort closure. Listeners receive the active\n\t * abort signal. `agent_end` remains awaited before the agent becomes idle.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear transcript state, runtime state, and queued messages. */\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Last message is a completed assistant turn. Two sub-cases:\n\t\t\t// 1. The assistant message carries pending tool calls without matching\n\t\t\t// tool results -> the provider will reject this, so fail fast with a\n\t\t\t// clear, actionable error.\n\t\t\t// 2. The assistant message is plain text/thinking (no tool calls). This is\n\t\t\t// a finished turn (e.g. after compaction, session resume, or an\n\t\t\t// explicit \"continue\" request). We honour it by injecting an empty\n\t\t\t// user prompt so the model can extend its previous answer rather than\n\t\t\t// throwing the opaque \"Cannot continue from message role: assistant\".\n\t\t\tconst hasPendingToolCalls = lastMessage.content.some((c) => c.type === \"toolCall\");\n\t\t\tif (hasPendingToolCalls) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Cannot continue: the last assistant message has pending tool calls without results. \" +\n\t\t\t\t\t\t\"Provide tool results (or a new user message) before continuing.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tawait this.runPromptMessages([{ role: \"user\", content: [{ type: \"text\", text: \"\" }], timestamp: Date.now() }]);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tsystemPromptCacheBoundary: this._state.systemPromptCacheBoundary,\n\t\t\tsystemPromptCacheBoundaryBypass: this._state.systemPromptCacheBoundaryBypass,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\tmaxTurns: this.maxTurns,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\ttoolTimeoutMs: this.toolTimeoutMs,\n\t\t\ttoolTimeouts: this.toolTimeouts,\n\t\t\ttoolScheduler: this.toolScheduler,\n\t\t\tmaxToolConcurrency: this.maxToolConcurrency,\n\t\t\tstrictExtensionClaims: this.strictExtensionClaims,\n\t\t\tcwd: this.cwd,\n\t\t\tresourceKeyResolver: this.resourceKeyResolver,\n\t\t\ttoolExecutionPolicy: this.toolExecutionPolicy,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tprepareNextTurn: this.prepareNextTurn ? async () => await this.prepareNextTurn?.(this.signal) : undefined,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tconst failure = error instanceof Error ? error : new Error(String(error));\n\t\t\tawait this.handleRunFailure(failure, abortController.signal.aborted);\n\t\t} finally {\n\t\t\tthis.finishRun();\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\t// Apply the same failure-termination contract as the low-level loop so the\n\t\t// disposition of any unresolved tool calls matches transcript repair:\n\t\t// an unambiguous open turn is closed with exactly one synthetic result per\n\t\t// missing call before a single coherent failure assistant, and an ambiguous\n\t\t// transcript fails closed without fabricating a turn over corruption.\n\t\tconst plan = planFailureTermination(this._state.messages, this._state.model, error, aborted);\n\n\t\tfor (const result of plan.closureResults) {\n\t\t\tawait this.processEvents({ type: \"message_start\", message: result });\n\t\t\tawait this.processEvents({ type: \"message_end\", message: result });\n\t\t}\n\n\t\tif (plan.failureMessage) {\n\t\t\tawait this.processEvents({ type: \"message_start\", message: plan.failureMessage });\n\t\t\tawait this.processEvents({ type: \"message_end\", message: plan.failureMessage });\n\t\t\tawait this.processEvents({ type: \"turn_end\", message: plan.failureMessage, toolResults: [] });\n\t\t}\n\n\t\tawait this.processEvents({ type: \"agent_end\", messages: plan.messages });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/** Reduce state, detach update observation, and await all terminal listeners. */\n\tprivate async processEvents(sourceEvent: AgentEvent): Promise<void> {\n\t\tconst event = createImmutableSnapshot(sourceEvent);\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\tthis._state.pendingToolCalls = new Set(this._state.pendingToolCalls).add(event.toolCallId);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\t// A tool's real promise may settle after the run already ended. The\n\t\t\t// late-settlement event is audit-only by contract, so it is still\n\t\t\t// delivered (with an inert signal) instead of being dropped; every\n\t\t\t// other event outside an active run remains a hard invariant break.\n\t\t\tif (event.type === \"tool_execution_late_settlement\") {\n\t\t\t\tconst inertSignal = new AbortController().signal;\n\t\t\t\tfor (const listener of this.listeners) await listener(createImmutableSnapshot(event), inertSignal);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tif (event.type === \"tool_execution_update\") {\n\t\t\tfor (const listener of this.listeners) {\n\t\t\t\tconst snapshot = createImmutableSnapshot(event);\n\t\t\t\tvoid Promise.resolve()\n\t\t\t\t\t.then(() => listener(snapshot, signal))\n\t\t\t\t\t.catch(() => undefined);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tfor (const listener of this.listeners) await listener(createImmutableSnapshot(event), signal);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,YAAY,EACjB,KAAK,OAAO,EAEZ,KAAK,mBAAmB,EAGxB,KAAK,eAAe,EACpB,KAAK,SAAS,EACd,MAAM,QAAQ,CAAC;AAIhB,OAAO,KAAK,EACX,oBAAoB,EACpB,mBAAmB,EAEnB,UAAU,EACV,eAAe,EACf,mBAAmB,EACnB,YAAY,EACZ,UAAU,EAEV,qBAAqB,EACrB,oBAAoB,EACpB,SAAS,EACT,QAAQ,E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AC,OAAO,EAAE,YAAY,GAAG,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9D,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAWpE,oGAAoG;IAC9F,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CA6C9B;IAED,OAAO,CAAC,oBAAoB;YAmBd,iBAAiB;YAgBjB,eAAe;IAY7B,OAAO,CAAC,qBAAqB;IAU7B,OAAO,CAAC,gBAAgB;YAsCV,gBAAgB;YA0BhB,gBAAgB;IAsB9B,OAAO,CAAC,SAAS;YASH,aAAa;CA6D3B","sourcesContent":["import {\n\ttype ImageContent,\n\ttype Message,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"omk-ai\";\nimport { planFailureTermination, runAgentLoop, runAgentLoopContinue } from \"./agent-loop.ts\";\nimport { deliverToListeners } from \"./listener-delivery.ts\";\nimport { createImmutableSnapshot } from \"./tool-execution-boundary.ts\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tQueueMode,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.ts\";\n\nexport type { QueueMode } from \"./types.ts\";\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) => message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\",\n\t);\n}\n\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\nfunction createMutableAgentState(\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>,\n): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\n\treturn {\n\t\tsystemPrompt: initialState?.systemPrompt ?? \"\",\n\t\tsystemPromptCacheBoundary: initialState?.systemPromptCacheBoundary,\n\t\tsystemPromptCacheBoundaryBypass: initialState?.systemPromptCacheBoundaryBypass,\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tprepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\tmaxTurns?: AgentLoopConfig[\"maxTurns\"];\n\ttoolExecution?: ToolExecutionMode;\n\ttoolTimeoutMs?: AgentLoopConfig[\"toolTimeoutMs\"];\n\ttoolTimeouts?: AgentLoopConfig[\"toolTimeouts\"];\n\ttoolScheduler?: AgentLoopConfig[\"toolScheduler\"];\n\tmaxToolConcurrency?: AgentLoopConfig[\"maxToolConcurrency\"];\n\tstrictExtensionClaims?: AgentLoopConfig[\"strictExtensionClaims\"];\n\tcwd?: AgentLoopConfig[\"cwd\"];\n\tresourceKeyResolver?: AgentLoopConfig[\"resourceKeyResolver\"];\n\ttoolExecutionPolicy?: AgentLoopConfig[\"toolExecutionPolicy\"];\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\tpublic mode: QueueMode;\n\n\tconstructor(mode: QueueMode) {\n\t\tthis.mode = mode;\n\t}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.messages.slice();\n\t\t\tthis.messages = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.messages[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.messages = this.messages.slice(1);\n\t\treturn [first];\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFn: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic prepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Optional provider-turn budget for each prompt or continuation run. */\n\tpublic maxTurns?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\n\tpublic toolExecution: ToolExecutionMode;\n\t/** Default execution timeout for tools; provider request timeout remains separate. */\n\tpublic toolTimeoutMs?: number;\n\t/** Per-tool-name execution timeout overrides. */\n\tpublic toolTimeouts?: Record<string, number>;\n\t/** Deterministic tool scheduler selection. */\n\tpublic toolScheduler: NonNullable<AgentLoopConfig[\"toolScheduler\"]>;\n\t/** Optional dag-v2 concurrency cap. */\n\tpublic maxToolConcurrency?: number;\n\t/** Require explicit resource claims for parallel extension tools. */\n\tpublic strictExtensionClaims: boolean;\n\t/** Working directory used to resolve path-scoped resource claims. */\n\tpublic cwd?: string;\n\t/** Optional dag-v2 platform identity resolver for path-claim aliases. */\n\tpublic resourceKeyResolver?: AgentLoopConfig[\"resourceKeyResolver\"];\n\t/** Execution-policy defaults (late-settlement audit policy). */\n\tpublic toolExecutionPolicy?: AgentLoopConfig[\"toolExecutionPolicy\"];\n\n\tconstructor(options: AgentOptions = {}) {\n\t\tthis._state = createMutableAgentState(options.initialState);\n\t\tthis.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = options.transformContext;\n\t\tthis.streamFn = options.streamFn ?? streamSimple;\n\t\tthis.getApiKey = options.getApiKey;\n\t\tthis.onPayload = options.onPayload;\n\t\tthis.onResponse = options.onResponse;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.prepareNextTurn = options.prepareNextTurn;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.maxTurns = options.maxTurns;\n\t\tthis.toolExecution = options.toolExecution ?? \"parallel\";\n\t\tthis.toolTimeoutMs = options.toolTimeoutMs;\n\t\tthis.toolTimeouts = options.toolTimeouts;\n\t\tthis.toolScheduler = options.toolScheduler ?? \"dag-v2\";\n\t\tthis.maxToolConcurrency = options.maxToolConcurrency;\n\t\tthis.strictExtensionClaims = options.strictExtensionClaims ?? false;\n\t\tthis.cwd = options.cwd;\n\t\tthis.resourceKeyResolver = options.resourceKeyResolver;\n\t\tthis.toolExecutionPolicy = options.toolExecutionPolicy;\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order except for\n\t * observation-only `tool_execution_update` delivery, which is detached so a\n\t * listener cannot delay timeout/abort closure. Listeners receive the active\n\t * abort signal. `agent_end` remains awaited before the agent becomes idle.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear transcript state, runtime state, and queued messages. */\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Last message is a completed assistant turn. Two sub-cases:\n\t\t\t// 1. The assistant message carries pending tool calls without matching\n\t\t\t// tool results -> the provider will reject this, so fail fast with a\n\t\t\t// clear, actionable error.\n\t\t\t// 2. The assistant message is plain text/thinking (no tool calls). This is\n\t\t\t// a finished turn (e.g. after compaction, session resume, or an\n\t\t\t// explicit \"continue\" request). We honour it by injecting an empty\n\t\t\t// user prompt so the model can extend its previous answer rather than\n\t\t\t// throwing the opaque \"Cannot continue from message role: assistant\".\n\t\t\tconst hasPendingToolCalls = lastMessage.content.some((c) => c.type === \"toolCall\");\n\t\t\tif (hasPendingToolCalls) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Cannot continue: the last assistant message has pending tool calls without results. \" +\n\t\t\t\t\t\t\"Provide tool results (or a new user message) before continuing.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tawait this.runPromptMessages([{ role: \"user\", content: [{ type: \"text\", text: \"\" }], timestamp: Date.now() }]);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tsystemPromptCacheBoundary: this._state.systemPromptCacheBoundary,\n\t\t\tsystemPromptCacheBoundaryBypass: this._state.systemPromptCacheBoundaryBypass,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\tmaxTurns: this.maxTurns,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\ttoolTimeoutMs: this.toolTimeoutMs,\n\t\t\ttoolTimeouts: this.toolTimeouts,\n\t\t\ttoolScheduler: this.toolScheduler,\n\t\t\tmaxToolConcurrency: this.maxToolConcurrency,\n\t\t\tstrictExtensionClaims: this.strictExtensionClaims,\n\t\t\tcwd: this.cwd,\n\t\t\tresourceKeyResolver: this.resourceKeyResolver,\n\t\t\ttoolExecutionPolicy: this.toolExecutionPolicy,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tprepareNextTurn: this.prepareNextTurn ? async () => await this.prepareNextTurn?.(this.signal) : undefined,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tconst failure = error instanceof Error ? error : new Error(String(error));\n\t\t\tawait this.handleRunFailure(failure, abortController.signal.aborted);\n\t\t} finally {\n\t\t\tthis.finishRun();\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\t// Apply the same failure-termination contract as the low-level loop so the\n\t\t// disposition of any unresolved tool calls matches transcript repair:\n\t\t// an unambiguous open turn is closed with exactly one synthetic result per\n\t\t// missing call before a single coherent failure assistant, and an ambiguous\n\t\t// transcript fails closed without fabricating a turn over corruption.\n\t\tconst plan = planFailureTermination(this._state.messages, this._state.model, error, aborted);\n\n\t\tfor (const result of plan.closureResults) {\n\t\t\tawait this.processEvents({ type: \"message_start\", message: result });\n\t\t\tawait this.processEvents({ type: \"message_end\", message: result });\n\t\t}\n\n\t\tif (plan.failureMessage) {\n\t\t\tawait this.processEvents({ type: \"message_start\", message: plan.failureMessage });\n\t\t\tawait this.processEvents({ type: \"message_end\", message: plan.failureMessage });\n\t\t\tawait this.processEvents({ type: \"turn_end\", message: plan.failureMessage, toolResults: [] });\n\t\t}\n\n\t\tawait this.processEvents({ type: \"agent_end\", messages: plan.messages });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/** Reduce state, detach update observation, and await all terminal listeners. */\n\tprivate async processEvents(sourceEvent: AgentEvent): Promise<void> {\n\t\tconst event = createImmutableSnapshot(sourceEvent);\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\tthis._state.pendingToolCalls = new Set(this._state.pendingToolCalls).add(event.toolCallId);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\t// A tool's real promise may settle after the run already ended. The\n\t\t\t// late-settlement event is audit-only by contract, so it is still\n\t\t\t// delivered (with an inert signal) instead of being dropped; every\n\t\t\t// other event outside an active run remains a hard invariant break.\n\t\t\tif (event.type === \"tool_execution_late_settlement\") {\n\t\t\t\tawait deliverToListeners(this.listeners, event, new AbortController().signal);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tif (event.type === \"tool_execution_update\") {\n\t\t\tfor (const listener of this.listeners) {\n\t\t\t\tconst snapshot = createImmutableSnapshot(event);\n\t\t\t\tvoid Promise.resolve()\n\t\t\t\t\t.then(() => listener(snapshot, signal))\n\t\t\t\t\t.catch(() => undefined);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tawait deliverToListeners(this.listeners, event, signal);\n\t}\n}\n"]}
|
package/dist/agent.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { streamSimple, } from "omk-ai";
|
|
2
2
|
import { planFailureTermination, runAgentLoop, runAgentLoopContinue } from "./agent-loop.js";
|
|
3
|
+
import { deliverToListeners } from "./listener-delivery.js";
|
|
3
4
|
import { createImmutableSnapshot } from "./tool-execution-boundary.js";
|
|
4
5
|
function defaultConvertToLlm(messages) {
|
|
5
6
|
return messages.filter((message) => message.role === "user" || message.role === "assistant" || message.role === "toolResult");
|
|
@@ -437,9 +438,7 @@ export class Agent {
|
|
|
437
438
|
// delivered (with an inert signal) instead of being dropped; every
|
|
438
439
|
// other event outside an active run remains a hard invariant break.
|
|
439
440
|
if (event.type === "tool_execution_late_settlement") {
|
|
440
|
-
|
|
441
|
-
for (const listener of this.listeners)
|
|
442
|
-
await listener(createImmutableSnapshot(event), inertSignal);
|
|
441
|
+
await deliverToListeners(this.listeners, event, new AbortController().signal);
|
|
443
442
|
return;
|
|
444
443
|
}
|
|
445
444
|
throw new Error("Agent listener invoked outside active run");
|
|
@@ -453,8 +452,7 @@ export class Agent {
|
|
|
453
452
|
}
|
|
454
453
|
return;
|
|
455
454
|
}
|
|
456
|
-
|
|
457
|
-
await listener(createImmutableSnapshot(event), signal);
|
|
455
|
+
await deliverToListeners(this.listeners, event, signal);
|
|
458
456
|
}
|
|
459
457
|
}
|
|
460
458
|
//# sourceMappingURL=agent.js.map
|
package/dist/agent.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAKN,YAAY,GAIZ,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,sBAAsB,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAC7F,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAoBvE,SAAS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,IAAI,CAAC,SAAS,EAAE,eAAe,CAAC,MAAM,CAAC;QACtD,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,oEAAoE;YACpE,kEAAkE;YAClE,mEAAmE;YACnE,oEAAoE;YACpE,IAAI,KAAK,CAAC,IAAI,KAAK,gCAAgC,EAAE,CAAC;gBACrD,MAAM,WAAW,GAAG,IAAI,eAAe,EAAE,CAAC,MAAM,CAAC;gBACjD,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS;oBAAE,MAAM,QAAQ,CAAC,uBAAuB,CAAC,KAAK,CAAC,EAAE,WAAW,CAAC,CAAC;gBACnG,OAAO;YACR,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;QAC9D,CAAC;QACD,IAAI,KAAK,CAAC,IAAI,KAAK,uBAAuB,EAAE,CAAC;YAC5C,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;gBACvC,MAAM,QAAQ,GAAG,uBAAuB,CAAC,KAAK,CAAC,CAAC;gBAChD,KAAK,OAAO,CAAC,OAAO,EAAE;qBACpB,IAAI,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;qBACtC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;YAC1B,CAAC;YACD,OAAO;QACR,CAAC;QACD,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS;YAAE,MAAM,QAAQ,CAAC,uBAAuB,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC,CAAC;IAAA,CAC9F;CACD","sourcesContent":["import {\n\ttype ImageContent,\n\ttype Message,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"omk-ai\";\nimport { planFailureTermination, runAgentLoop, runAgentLoopContinue } from \"./agent-loop.ts\";\nimport { createImmutableSnapshot } from \"./tool-execution-boundary.ts\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tQueueMode,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.ts\";\n\nexport type { QueueMode } from \"./types.ts\";\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) => message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\",\n\t);\n}\n\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\nfunction createMutableAgentState(\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>,\n): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\n\treturn {\n\t\tsystemPrompt: initialState?.systemPrompt ?? \"\",\n\t\tsystemPromptCacheBoundary: initialState?.systemPromptCacheBoundary,\n\t\tsystemPromptCacheBoundaryBypass: initialState?.systemPromptCacheBoundaryBypass,\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tprepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\tmaxTurns?: AgentLoopConfig[\"maxTurns\"];\n\ttoolExecution?: ToolExecutionMode;\n\ttoolTimeoutMs?: AgentLoopConfig[\"toolTimeoutMs\"];\n\ttoolTimeouts?: AgentLoopConfig[\"toolTimeouts\"];\n\ttoolScheduler?: AgentLoopConfig[\"toolScheduler\"];\n\tmaxToolConcurrency?: AgentLoopConfig[\"maxToolConcurrency\"];\n\tstrictExtensionClaims?: AgentLoopConfig[\"strictExtensionClaims\"];\n\tcwd?: AgentLoopConfig[\"cwd\"];\n\tresourceKeyResolver?: AgentLoopConfig[\"resourceKeyResolver\"];\n\ttoolExecutionPolicy?: AgentLoopConfig[\"toolExecutionPolicy\"];\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\tpublic mode: QueueMode;\n\n\tconstructor(mode: QueueMode) {\n\t\tthis.mode = mode;\n\t}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.messages.slice();\n\t\t\tthis.messages = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.messages[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.messages = this.messages.slice(1);\n\t\treturn [first];\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFn: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic prepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Optional provider-turn budget for each prompt or continuation run. */\n\tpublic maxTurns?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\n\tpublic toolExecution: ToolExecutionMode;\n\t/** Default execution timeout for tools; provider request timeout remains separate. */\n\tpublic toolTimeoutMs?: number;\n\t/** Per-tool-name execution timeout overrides. */\n\tpublic toolTimeouts?: Record<string, number>;\n\t/** Deterministic tool scheduler selection. */\n\tpublic toolScheduler: NonNullable<AgentLoopConfig[\"toolScheduler\"]>;\n\t/** Optional dag-v2 concurrency cap. */\n\tpublic maxToolConcurrency?: number;\n\t/** Require explicit resource claims for parallel extension tools. */\n\tpublic strictExtensionClaims: boolean;\n\t/** Working directory used to resolve path-scoped resource claims. */\n\tpublic cwd?: string;\n\t/** Optional dag-v2 platform identity resolver for path-claim aliases. */\n\tpublic resourceKeyResolver?: AgentLoopConfig[\"resourceKeyResolver\"];\n\t/** Execution-policy defaults (late-settlement audit policy). */\n\tpublic toolExecutionPolicy?: AgentLoopConfig[\"toolExecutionPolicy\"];\n\n\tconstructor(options: AgentOptions = {}) {\n\t\tthis._state = createMutableAgentState(options.initialState);\n\t\tthis.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = options.transformContext;\n\t\tthis.streamFn = options.streamFn ?? streamSimple;\n\t\tthis.getApiKey = options.getApiKey;\n\t\tthis.onPayload = options.onPayload;\n\t\tthis.onResponse = options.onResponse;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.prepareNextTurn = options.prepareNextTurn;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.maxTurns = options.maxTurns;\n\t\tthis.toolExecution = options.toolExecution ?? \"parallel\";\n\t\tthis.toolTimeoutMs = options.toolTimeoutMs;\n\t\tthis.toolTimeouts = options.toolTimeouts;\n\t\tthis.toolScheduler = options.toolScheduler ?? \"dag-v2\";\n\t\tthis.maxToolConcurrency = options.maxToolConcurrency;\n\t\tthis.strictExtensionClaims = options.strictExtensionClaims ?? false;\n\t\tthis.cwd = options.cwd;\n\t\tthis.resourceKeyResolver = options.resourceKeyResolver;\n\t\tthis.toolExecutionPolicy = options.toolExecutionPolicy;\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order except for\n\t * observation-only `tool_execution_update` delivery, which is detached so a\n\t * listener cannot delay timeout/abort closure. Listeners receive the active\n\t * abort signal. `agent_end` remains awaited before the agent becomes idle.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear transcript state, runtime state, and queued messages. */\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Last message is a completed assistant turn. Two sub-cases:\n\t\t\t// 1. The assistant message carries pending tool calls without matching\n\t\t\t// tool results -> the provider will reject this, so fail fast with a\n\t\t\t// clear, actionable error.\n\t\t\t// 2. The assistant message is plain text/thinking (no tool calls). This is\n\t\t\t// a finished turn (e.g. after compaction, session resume, or an\n\t\t\t// explicit \"continue\" request). We honour it by injecting an empty\n\t\t\t// user prompt so the model can extend its previous answer rather than\n\t\t\t// throwing the opaque \"Cannot continue from message role: assistant\".\n\t\t\tconst hasPendingToolCalls = lastMessage.content.some((c) => c.type === \"toolCall\");\n\t\t\tif (hasPendingToolCalls) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Cannot continue: the last assistant message has pending tool calls without results. \" +\n\t\t\t\t\t\t\"Provide tool results (or a new user message) before continuing.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tawait this.runPromptMessages([{ role: \"user\", content: [{ type: \"text\", text: \"\" }], timestamp: Date.now() }]);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tsystemPromptCacheBoundary: this._state.systemPromptCacheBoundary,\n\t\t\tsystemPromptCacheBoundaryBypass: this._state.systemPromptCacheBoundaryBypass,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\tmaxTurns: this.maxTurns,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\ttoolTimeoutMs: this.toolTimeoutMs,\n\t\t\ttoolTimeouts: this.toolTimeouts,\n\t\t\ttoolScheduler: this.toolScheduler,\n\t\t\tmaxToolConcurrency: this.maxToolConcurrency,\n\t\t\tstrictExtensionClaims: this.strictExtensionClaims,\n\t\t\tcwd: this.cwd,\n\t\t\tresourceKeyResolver: this.resourceKeyResolver,\n\t\t\ttoolExecutionPolicy: this.toolExecutionPolicy,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tprepareNextTurn: this.prepareNextTurn ? async () => await this.prepareNextTurn?.(this.signal) : undefined,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tconst failure = error instanceof Error ? error : new Error(String(error));\n\t\t\tawait this.handleRunFailure(failure, abortController.signal.aborted);\n\t\t} finally {\n\t\t\tthis.finishRun();\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\t// Apply the same failure-termination contract as the low-level loop so the\n\t\t// disposition of any unresolved tool calls matches transcript repair:\n\t\t// an unambiguous open turn is closed with exactly one synthetic result per\n\t\t// missing call before a single coherent failure assistant, and an ambiguous\n\t\t// transcript fails closed without fabricating a turn over corruption.\n\t\tconst plan = planFailureTermination(this._state.messages, this._state.model, error, aborted);\n\n\t\tfor (const result of plan.closureResults) {\n\t\t\tawait this.processEvents({ type: \"message_start\", message: result });\n\t\t\tawait this.processEvents({ type: \"message_end\", message: result });\n\t\t}\n\n\t\tif (plan.failureMessage) {\n\t\t\tawait this.processEvents({ type: \"message_start\", message: plan.failureMessage });\n\t\t\tawait this.processEvents({ type: \"message_end\", message: plan.failureMessage });\n\t\t\tawait this.processEvents({ type: \"turn_end\", message: plan.failureMessage, toolResults: [] });\n\t\t}\n\n\t\tawait this.processEvents({ type: \"agent_end\", messages: plan.messages });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/** Reduce state, detach update observation, and await all terminal listeners. */\n\tprivate async processEvents(sourceEvent: AgentEvent): Promise<void> {\n\t\tconst event = createImmutableSnapshot(sourceEvent);\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\tthis._state.pendingToolCalls = new Set(this._state.pendingToolCalls).add(event.toolCallId);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\t// A tool's real promise may settle after the run already ended. The\n\t\t\t// late-settlement event is audit-only by contract, so it is still\n\t\t\t// delivered (with an inert signal) instead of being dropped; every\n\t\t\t// other event outside an active run remains a hard invariant break.\n\t\t\tif (event.type === \"tool_execution_late_settlement\") {\n\t\t\t\tconst inertSignal = new AbortController().signal;\n\t\t\t\tfor (const listener of this.listeners) await listener(createImmutableSnapshot(event), inertSignal);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tif (event.type === \"tool_execution_update\") {\n\t\t\tfor (const listener of this.listeners) {\n\t\t\t\tconst snapshot = createImmutableSnapshot(event);\n\t\t\t\tvoid Promise.resolve()\n\t\t\t\t\t.then(() => listener(snapshot, signal))\n\t\t\t\t\t.catch(() => undefined);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tfor (const listener of this.listeners) await listener(createImmutableSnapshot(event), signal);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAKN,YAAY,GAIZ,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,sBAAsB,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAC7F,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAoBvE,SAAS,mBAAmB,CAAC,QAAwB,EAAa;IACjE,OAAO,QAAQ,CAAC,MAAM,CACrB,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW,IAAI,OAAO,CAAC,IAAI,KAAK,YAAY,CACrG,CAAC;AAAA,CACF;AAED,MAAM,aAAa,GAAG;IACrB,EAAE,EAAE,SAAS;IACb,IAAI,EAAE,SAAS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M,CAAC,CAAC;gBAC9E,OAAO;YACR,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;QAC9D,CAAC;QACD,IAAI,KAAK,CAAC,IAAI,KAAK,uBAAuB,EAAE,CAAC;YAC5C,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;gBACvC,MAAM,QAAQ,GAAG,uBAAuB,CAAC,KAAK,CAAC,CAAC;gBAChD,KAAK,OAAO,CAAC,OAAO,EAAE;qBACpB,IAAI,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;qBACtC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;YAC1B,CAAC;YACD,OAAO;QACR,CAAC;QACD,MAAM,kBAAkB,CAAC,IAAI,CAAC,SAAS,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;IAAA,CACxD;CACD","sourcesContent":["import {\n\ttype ImageContent,\n\ttype Message,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"omk-ai\";\nimport { planFailureTermination, runAgentLoop, runAgentLoopContinue } from \"./agent-loop.ts\";\nimport { deliverToListeners } from \"./listener-delivery.ts\";\nimport { createImmutableSnapshot } from \"./tool-execution-boundary.ts\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tQueueMode,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.ts\";\n\nexport type { QueueMode } from \"./types.ts\";\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) => message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\",\n\t);\n}\n\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\nfunction createMutableAgentState(\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>,\n): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\n\treturn {\n\t\tsystemPrompt: initialState?.systemPrompt ?? \"\",\n\t\tsystemPromptCacheBoundary: initialState?.systemPromptCacheBoundary,\n\t\tsystemPromptCacheBoundaryBypass: initialState?.systemPromptCacheBoundaryBypass,\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tprepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\tmaxTurns?: AgentLoopConfig[\"maxTurns\"];\n\ttoolExecution?: ToolExecutionMode;\n\ttoolTimeoutMs?: AgentLoopConfig[\"toolTimeoutMs\"];\n\ttoolTimeouts?: AgentLoopConfig[\"toolTimeouts\"];\n\ttoolScheduler?: AgentLoopConfig[\"toolScheduler\"];\n\tmaxToolConcurrency?: AgentLoopConfig[\"maxToolConcurrency\"];\n\tstrictExtensionClaims?: AgentLoopConfig[\"strictExtensionClaims\"];\n\tcwd?: AgentLoopConfig[\"cwd\"];\n\tresourceKeyResolver?: AgentLoopConfig[\"resourceKeyResolver\"];\n\ttoolExecutionPolicy?: AgentLoopConfig[\"toolExecutionPolicy\"];\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\tpublic mode: QueueMode;\n\n\tconstructor(mode: QueueMode) {\n\t\tthis.mode = mode;\n\t}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.messages.slice();\n\t\t\tthis.messages = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.messages[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.messages = this.messages.slice(1);\n\t\treturn [first];\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFn: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic prepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Optional provider-turn budget for each prompt or continuation run. */\n\tpublic maxTurns?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\n\tpublic toolExecution: ToolExecutionMode;\n\t/** Default execution timeout for tools; provider request timeout remains separate. */\n\tpublic toolTimeoutMs?: number;\n\t/** Per-tool-name execution timeout overrides. */\n\tpublic toolTimeouts?: Record<string, number>;\n\t/** Deterministic tool scheduler selection. */\n\tpublic toolScheduler: NonNullable<AgentLoopConfig[\"toolScheduler\"]>;\n\t/** Optional dag-v2 concurrency cap. */\n\tpublic maxToolConcurrency?: number;\n\t/** Require explicit resource claims for parallel extension tools. */\n\tpublic strictExtensionClaims: boolean;\n\t/** Working directory used to resolve path-scoped resource claims. */\n\tpublic cwd?: string;\n\t/** Optional dag-v2 platform identity resolver for path-claim aliases. */\n\tpublic resourceKeyResolver?: AgentLoopConfig[\"resourceKeyResolver\"];\n\t/** Execution-policy defaults (late-settlement audit policy). */\n\tpublic toolExecutionPolicy?: AgentLoopConfig[\"toolExecutionPolicy\"];\n\n\tconstructor(options: AgentOptions = {}) {\n\t\tthis._state = createMutableAgentState(options.initialState);\n\t\tthis.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = options.transformContext;\n\t\tthis.streamFn = options.streamFn ?? streamSimple;\n\t\tthis.getApiKey = options.getApiKey;\n\t\tthis.onPayload = options.onPayload;\n\t\tthis.onResponse = options.onResponse;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.prepareNextTurn = options.prepareNextTurn;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.maxTurns = options.maxTurns;\n\t\tthis.toolExecution = options.toolExecution ?? \"parallel\";\n\t\tthis.toolTimeoutMs = options.toolTimeoutMs;\n\t\tthis.toolTimeouts = options.toolTimeouts;\n\t\tthis.toolScheduler = options.toolScheduler ?? \"dag-v2\";\n\t\tthis.maxToolConcurrency = options.maxToolConcurrency;\n\t\tthis.strictExtensionClaims = options.strictExtensionClaims ?? false;\n\t\tthis.cwd = options.cwd;\n\t\tthis.resourceKeyResolver = options.resourceKeyResolver;\n\t\tthis.toolExecutionPolicy = options.toolExecutionPolicy;\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order except for\n\t * observation-only `tool_execution_update` delivery, which is detached so a\n\t * listener cannot delay timeout/abort closure. Listeners receive the active\n\t * abort signal. `agent_end` remains awaited before the agent becomes idle.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear transcript state, runtime state, and queued messages. */\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Last message is a completed assistant turn. Two sub-cases:\n\t\t\t// 1. The assistant message carries pending tool calls without matching\n\t\t\t// tool results -> the provider will reject this, so fail fast with a\n\t\t\t// clear, actionable error.\n\t\t\t// 2. The assistant message is plain text/thinking (no tool calls). This is\n\t\t\t// a finished turn (e.g. after compaction, session resume, or an\n\t\t\t// explicit \"continue\" request). We honour it by injecting an empty\n\t\t\t// user prompt so the model can extend its previous answer rather than\n\t\t\t// throwing the opaque \"Cannot continue from message role: assistant\".\n\t\t\tconst hasPendingToolCalls = lastMessage.content.some((c) => c.type === \"toolCall\");\n\t\t\tif (hasPendingToolCalls) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Cannot continue: the last assistant message has pending tool calls without results. \" +\n\t\t\t\t\t\t\"Provide tool results (or a new user message) before continuing.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tawait this.runPromptMessages([{ role: \"user\", content: [{ type: \"text\", text: \"\" }], timestamp: Date.now() }]);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tsystemPromptCacheBoundary: this._state.systemPromptCacheBoundary,\n\t\t\tsystemPromptCacheBoundaryBypass: this._state.systemPromptCacheBoundaryBypass,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\tmaxTurns: this.maxTurns,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\ttoolTimeoutMs: this.toolTimeoutMs,\n\t\t\ttoolTimeouts: this.toolTimeouts,\n\t\t\ttoolScheduler: this.toolScheduler,\n\t\t\tmaxToolConcurrency: this.maxToolConcurrency,\n\t\t\tstrictExtensionClaims: this.strictExtensionClaims,\n\t\t\tcwd: this.cwd,\n\t\t\tresourceKeyResolver: this.resourceKeyResolver,\n\t\t\ttoolExecutionPolicy: this.toolExecutionPolicy,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tprepareNextTurn: this.prepareNextTurn ? async () => await this.prepareNextTurn?.(this.signal) : undefined,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tconst failure = error instanceof Error ? error : new Error(String(error));\n\t\t\tawait this.handleRunFailure(failure, abortController.signal.aborted);\n\t\t} finally {\n\t\t\tthis.finishRun();\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\t// Apply the same failure-termination contract as the low-level loop so the\n\t\t// disposition of any unresolved tool calls matches transcript repair:\n\t\t// an unambiguous open turn is closed with exactly one synthetic result per\n\t\t// missing call before a single coherent failure assistant, and an ambiguous\n\t\t// transcript fails closed without fabricating a turn over corruption.\n\t\tconst plan = planFailureTermination(this._state.messages, this._state.model, error, aborted);\n\n\t\tfor (const result of plan.closureResults) {\n\t\t\tawait this.processEvents({ type: \"message_start\", message: result });\n\t\t\tawait this.processEvents({ type: \"message_end\", message: result });\n\t\t}\n\n\t\tif (plan.failureMessage) {\n\t\t\tawait this.processEvents({ type: \"message_start\", message: plan.failureMessage });\n\t\t\tawait this.processEvents({ type: \"message_end\", message: plan.failureMessage });\n\t\t\tawait this.processEvents({ type: \"turn_end\", message: plan.failureMessage, toolResults: [] });\n\t\t}\n\n\t\tawait this.processEvents({ type: \"agent_end\", messages: plan.messages });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/** Reduce state, detach update observation, and await all terminal listeners. */\n\tprivate async processEvents(sourceEvent: AgentEvent): Promise<void> {\n\t\tconst event = createImmutableSnapshot(sourceEvent);\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\tthis._state.pendingToolCalls = new Set(this._state.pendingToolCalls).add(event.toolCallId);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\t// A tool's real promise may settle after the run already ended. The\n\t\t\t// late-settlement event is audit-only by contract, so it is still\n\t\t\t// delivered (with an inert signal) instead of being dropped; every\n\t\t\t// other event outside an active run remains a hard invariant break.\n\t\t\tif (event.type === \"tool_execution_late_settlement\") {\n\t\t\t\tawait deliverToListeners(this.listeners, event, new AbortController().signal);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tif (event.type === \"tool_execution_update\") {\n\t\t\tfor (const listener of this.listeners) {\n\t\t\t\tconst snapshot = createImmutableSnapshot(event);\n\t\t\t\tvoid Promise.resolve()\n\t\t\t\t\t.then(() => listener(snapshot, signal))\n\t\t\t\t\t.catch(() => undefined);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tawait deliverToListeners(this.listeners, event, signal);\n\t}\n}\n"]}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hash-chained effect journal reducer.
|
|
3
|
+
*
|
|
4
|
+
* Two entry points, one invariant. `reduceEffectJournal` is the write path:
|
|
5
|
+
* it turns a command into the next record — sequence, previous hash, and
|
|
6
|
+
* record hash all derived, never supplied — and refuses illegal moves.
|
|
7
|
+
* `appendEffectRecord` is the read/replay path: it re-verifies a persisted
|
|
8
|
+
* record against the same rules plus the chain, so a journal that was
|
|
9
|
+
* tampered with, truncated in the middle, or produced by a reducer with a
|
|
10
|
+
* different transition table fails to replay instead of silently loading.
|
|
11
|
+
*
|
|
12
|
+
* The state is plain data: the head hash, the last sequence, and the latest
|
|
13
|
+
* record per effect. It is a pure fold over the record list, so recovery
|
|
14
|
+
* cost is linear in journal length and replaying twice yields equal states.
|
|
15
|
+
*/
|
|
16
|
+
import { type EffectCommand, type EffectJournalResult, type EffectJournalState, type EffectRecord } from "./effect-types.ts";
|
|
17
|
+
export declare const EFFECT_ID_DOMAIN = "omk.effect.v2";
|
|
18
|
+
export declare const EFFECT_RECORD_DOMAIN = "omk.effect.record.v2";
|
|
19
|
+
export interface EffectIdInput {
|
|
20
|
+
readonly operationId: string;
|
|
21
|
+
/** Logical attempt index of the action. A provider retry that keeps the same logical action keeps this. */
|
|
22
|
+
readonly attemptLogicalIndex: number;
|
|
23
|
+
readonly toolCallId: string;
|
|
24
|
+
readonly intentDigest: string;
|
|
25
|
+
/** Explicit resume token; without one, a different logical index yields a different effect. */
|
|
26
|
+
readonly resumeToken?: string;
|
|
27
|
+
}
|
|
28
|
+
/** Stable effect identity per plan §6.5. Two logically distinct actions never share an id. */
|
|
29
|
+
export declare function deriveEffectId(input: EffectIdInput): string;
|
|
30
|
+
export declare function initialEffectJournalState(): EffectJournalState;
|
|
31
|
+
export declare function computeEffectRecordHash(record: Omit<EffectRecord, "recordHash">): string;
|
|
32
|
+
export declare function lookupEffect(state: EffectJournalState, effectId: string): EffectRecord | undefined;
|
|
33
|
+
export interface EffectJournalStep {
|
|
34
|
+
readonly state: EffectJournalState;
|
|
35
|
+
readonly record: EffectRecord;
|
|
36
|
+
}
|
|
37
|
+
/** Write path: derive and chain the next record for `command`, or reject it. */
|
|
38
|
+
export declare function reduceEffectJournal(state: EffectJournalState, command: EffectCommand): EffectJournalResult<EffectJournalStep>;
|
|
39
|
+
/** Replay path: verify a persisted record against the chain and the transition table, then apply it. */
|
|
40
|
+
export declare function appendEffectRecord(state: EffectJournalState, record: EffectRecord): EffectJournalResult<EffectJournalState>;
|
|
41
|
+
/** Fold a persisted record list into journal state; the first bad record stops the replay. */
|
|
42
|
+
export declare function replayEffectJournal(records: readonly EffectRecord[]): EffectJournalResult<EffectJournalState>;
|
|
43
|
+
//# sourceMappingURL=effect-journal.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"effect-journal.d.ts","sourceRoot":"","sources":["../../src/effects/effect-journal.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,OAAO,EAGN,KAAK,aAAa,EAGlB,KAAK,mBAAmB,EACxB,KAAK,kBAAkB,EAEvB,KAAK,YAAY,EAEjB,MAAM,mBAAmB,CAAC;AAE3B,eAAO,MAAM,gBAAgB,kBAAkB,CAAC;AAChD,eAAO,MAAM,oBAAoB,yBAAyB,CAAC;AAI3D,MAAM,WAAW,aAAa;IAC7B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,2GAA2G;IAC3G,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAC;IACrC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,+FAA+F;IAC/F,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;CAC9B;AAED,+FAA8F;AAC9F,wBAAgB,cAAc,CAAC,KAAK,EAAE,aAAa,GAAG,MAAM,CAI3D;AAED,wBAAgB,yBAAyB,IAAI,kBAAkB,CAE9D;AAED,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,IAAI,CAAC,YAAY,EAAE,YAAY,CAAC,GAAG,MAAM,CAExF;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,GAAG,YAAY,GAAG,SAAS,CAElG;AAiDD,MAAM,WAAW,iBAAiB;IACjC,QAAQ,CAAC,KAAK,EAAE,kBAAkB,CAAC;IACnC,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAC;CAC9B;AAED,gFAAgF;AAChF,wBAAgB,mBAAmB,CAClC,KAAK,EAAE,kBAAkB,EACzB,OAAO,EAAE,aAAa,GACpB,mBAAmB,CAAC,iBAAiB,CAAC,CAkCxC;AAcD,wGAAwG;AACxG,wBAAgB,kBAAkB,CACjC,KAAK,EAAE,kBAAkB,EACzB,MAAM,EAAE,YAAY,GAClB,mBAAmB,CAAC,kBAAkB,CAAC,CA8CzC;AAED,8FAA8F;AAC9F,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,SAAS,YAAY,EAAE,GAAG,mBAAmB,CAAC,kBAAkB,CAAC,CAe7G","sourcesContent":["/**\n * Hash-chained effect journal reducer.\n *\n * Two entry points, one invariant. `reduceEffectJournal` is the write path:\n * it turns a command into the next record — sequence, previous hash, and\n * record hash all derived, never supplied — and refuses illegal moves.\n * `appendEffectRecord` is the read/replay path: it re-verifies a persisted\n * record against the same rules plus the chain, so a journal that was\n * tampered with, truncated in the middle, or produced by a reducer with a\n * different transition table fails to replay instead of silently loading.\n *\n * The state is plain data: the head hash, the last sequence, and the latest\n * record per effect. It is a pure fold over the record list, so recovery\n * cost is linear in journal length and replaying twice yields equal states.\n */\n\nimport { canonicalDigest, domainDigest } from \"../harness/canonical-digest.ts\";\nimport { legalNextPhases, reduceEffectPhase } from \"./effect-transitions.ts\";\nimport {\n\tEFFECT_JOURNAL_GENESIS_HASH,\n\tEFFECT_RECORD_SCHEMA_VERSION,\n\ttype EffectCommand,\n\ttype EffectIdentity,\n\ttype EffectIntent,\n\ttype EffectJournalResult,\n\ttype EffectJournalState,\n\tEffectJournalViolation,\n\ttype EffectRecord,\n\ttype EffectSemantics,\n} from \"./effect-types.ts\";\n\nexport const EFFECT_ID_DOMAIN = \"omk.effect.v2\";\nexport const EFFECT_RECORD_DOMAIN = \"omk.effect.record.v2\";\n\nconst SEMANTICS: readonly EffectSemantics[] = [\"pure\", \"idempotent\", \"inspectable\", \"compensatable\", \"opaque\"];\n\nexport interface EffectIdInput {\n\treadonly operationId: string;\n\t/** Logical attempt index of the action. A provider retry that keeps the same logical action keeps this. */\n\treadonly attemptLogicalIndex: number;\n\treadonly toolCallId: string;\n\treadonly intentDigest: string;\n\t/** Explicit resume token; without one, a different logical index yields a different effect. */\n\treadonly resumeToken?: string;\n}\n\n/** Stable effect identity per plan §6.5. Two logically distinct actions never share an id. */\nexport function deriveEffectId(input: EffectIdInput): string {\n\tconst attemptPart =\n\t\tinput.resumeToken === undefined ? `index:${input.attemptLogicalIndex}` : `resume:${input.resumeToken}`;\n\treturn domainDigest(EFFECT_ID_DOMAIN, [input.operationId, attemptPart, input.toolCallId, input.intentDigest]);\n}\n\nexport function initialEffectJournalState(): EffectJournalState {\n\treturn { headHash: EFFECT_JOURNAL_GENESIS_HASH, lastSequence: 0, effects: {} };\n}\n\nexport function computeEffectRecordHash(record: Omit<EffectRecord, \"recordHash\">): string {\n\treturn canonicalDigest({ domain: EFFECT_RECORD_DOMAIN, record });\n}\n\nexport function lookupEffect(state: EffectJournalState, effectId: string): EffectRecord | undefined {\n\treturn Object.hasOwn(state.effects, effectId) ? state.effects[effectId] : undefined;\n}\n\nfunction fail<T>(code: EffectJournalViolation[\"code\"], message: string, effectId?: string): EffectJournalResult<T> {\n\treturn { ok: false, error: new EffectJournalViolation(code, message, effectId) };\n}\n\nfunction nonEmpty(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.trim().length > 0;\n}\n\nfunction validatePrepare(identity: EffectIdentity, intent: EffectIntent, timestamp: string): string | undefined {\n\tfor (const [name, value] of [\n\t\t[\"effectId\", identity.effectId],\n\t\t[\"operationId\", identity.operationId],\n\t\t[\"attemptId\", identity.attemptId],\n\t\t[\"processIncarnation\", identity.processIncarnation],\n\t\t[\"capabilityDigest\", intent.capabilityDigest],\n\t\t[\"intentDigest\", intent.intentDigest],\n\t\t[\"timestamp\", timestamp],\n\t] as const) {\n\t\tif (!nonEmpty(value)) return `${name} must be a non-empty string`;\n\t}\n\tif (!SEMANTICS.includes(intent.semantics)) return `unknown semantics ${String(intent.semantics)}`;\n\tif (intent.semantics === \"idempotent\" && !nonEmpty(intent.idempotencyKey)) {\n\t\treturn \"idempotent effects require an idempotencyKey\";\n\t}\n\tif (intent.semantics === \"compensatable\" && intent.compensationDescriptor === undefined) {\n\t\treturn \"compensatable effects require a compensationDescriptor\";\n\t}\n\tif (intent.semantics === \"inspectable\" && intent.inspectDescriptor === undefined) {\n\t\treturn \"inspectable effects require an inspectDescriptor\";\n\t}\n\tif (identity.laneEpoch !== undefined && (!Number.isInteger(identity.laneEpoch) || identity.laneEpoch < 0)) {\n\t\treturn \"laneEpoch must be a non-negative integer\";\n\t}\n\treturn undefined;\n}\n\nfunction seal(state: EffectJournalState, body: Omit<EffectRecord, \"recordHash\" | \"sequence\" | \"previousRecordHash\">) {\n\tconst unsealed = { ...body, sequence: state.lastSequence + 1, previousRecordHash: state.headHash };\n\tconst record: EffectRecord = Object.freeze({ ...unsealed, recordHash: computeEffectRecordHash(unsealed) });\n\tconst next: EffectJournalState = Object.freeze({\n\t\theadHash: record.recordHash,\n\t\tlastSequence: record.sequence,\n\t\teffects: Object.freeze({ ...state.effects, [record.effectId]: record }),\n\t});\n\treturn { ok: true as const, value: { state: next, record } };\n}\n\nexport interface EffectJournalStep {\n\treadonly state: EffectJournalState;\n\treadonly record: EffectRecord;\n}\n\n/** Write path: derive and chain the next record for `command`, or reject it. */\nexport function reduceEffectJournal(\n\tstate: EffectJournalState,\n\tcommand: EffectCommand,\n): EffectJournalResult<EffectJournalStep> {\n\tif (command.type === \"prepare\") {\n\t\tconst problem = validatePrepare(command.identity, command.intent, command.timestamp);\n\t\tif (problem !== undefined) return fail(\"invalid_record\", problem, command.identity.effectId);\n\t\tif (lookupEffect(state, command.identity.effectId) !== undefined) {\n\t\t\treturn fail(\n\t\t\t\t\"duplicate_effect\",\n\t\t\t\t`Effect ${command.identity.effectId} is already journaled`,\n\t\t\t\tcommand.identity.effectId,\n\t\t\t);\n\t\t}\n\t\treturn seal(state, {\n\t\t\t...command.identity,\n\t\t\t...command.intent,\n\t\t\tschemaVersion: EFFECT_RECORD_SCHEMA_VERSION,\n\t\t\tphase: \"prepared\",\n\t\t\ttimestamp: command.timestamp,\n\t\t\treasonCode: \"effect.prepared\",\n\t\t});\n\t}\n\tconst latest = lookupEffect(state, command.effectId);\n\tif (latest === undefined)\n\t\treturn fail(\"unknown_effect\", `Effect ${command.effectId} is not journaled`, command.effectId);\n\tif (!nonEmpty(command.timestamp))\n\t\treturn fail(\"invalid_record\", \"timestamp must be a non-empty string\", command.effectId);\n\tconst moved = reduceEffectPhase(latest, command);\n\tif (!moved.ok) return moved;\n\tconst { recordHash: _hash, sequence: _sequence, previousRecordHash: _previous, ...carried } = latest;\n\treturn seal(state, {\n\t\t...carried,\n\t\tphase: moved.value.phase,\n\t\ttimestamp: command.timestamp,\n\t\treasonCode: moved.value.reasonCode,\n\t});\n}\n\nconst IDENTITY_FIELDS = [\n\t\"operationId\",\n\t\"attemptId\",\n\t\"laneId\",\n\t\"laneEpoch\",\n\t\"processIncarnation\",\n\t\"semantics\",\n\t\"capabilityDigest\",\n\t\"intentDigest\",\n\t\"idempotencyKey\",\n] as const;\n\n/** Replay path: verify a persisted record against the chain and the transition table, then apply it. */\nexport function appendEffectRecord(\n\tstate: EffectJournalState,\n\trecord: EffectRecord,\n): EffectJournalResult<EffectJournalState> {\n\tconst id = record.effectId;\n\tif (record.schemaVersion !== EFFECT_RECORD_SCHEMA_VERSION) {\n\t\treturn fail(\"invalid_record\", `Unsupported effect record schema ${String(record.schemaVersion)}`, id);\n\t}\n\tif (record.sequence !== state.lastSequence + 1) {\n\t\treturn fail(\"sequence_violation\", `Record sequence ${record.sequence} is not ${state.lastSequence + 1}`, id);\n\t}\n\tif (record.previousRecordHash !== state.headHash) {\n\t\treturn fail(\n\t\t\t\"chain_break\",\n\t\t\t`Record ${record.sequence} chains to ${record.previousRecordHash}, head is ${state.headHash}`,\n\t\t\tid,\n\t\t);\n\t}\n\tconst { recordHash, ...body } = record;\n\tif (computeEffectRecordHash(body) !== recordHash) {\n\t\treturn fail(\"hash_mismatch\", `Record ${record.sequence} hash does not match its contents`, id);\n\t}\n\tconst latest = lookupEffect(state, id);\n\tif (latest === undefined) {\n\t\tconst problem = validatePrepare(record, record, record.timestamp);\n\t\tif (problem !== undefined) return fail(\"invalid_record\", problem, id);\n\t\tif (record.phase !== \"prepared\") return fail(\"invalid_record\", `First record for ${id} must be prepared`, id);\n\t} else {\n\t\tfor (const field of IDENTITY_FIELDS) {\n\t\t\tif (latest[field] !== record[field]) {\n\t\t\t\treturn fail(\"identity_mismatch\", `Record ${record.sequence} changes ${field} of effect ${id}`, id);\n\t\t\t}\n\t\t}\n\t\tif (!legalNextPhases(latest).includes(record.phase)) {\n\t\t\treturn fail(\"invalid_transition\", `Effect ${id} cannot move ${latest.phase} -> ${record.phase}`, id);\n\t\t}\n\t\tif (record.phase === \"abandoned\" && !nonEmpty(record.reasonCode)) {\n\t\t\treturn fail(\"invalid_record\", `Abandoned record for ${id} carries no reason code`, id);\n\t\t}\n\t}\n\tconst frozen = Object.freeze({ ...record });\n\treturn {\n\t\tok: true,\n\t\tvalue: Object.freeze({\n\t\t\theadHash: frozen.recordHash,\n\t\t\tlastSequence: frozen.sequence,\n\t\t\teffects: Object.freeze({ ...state.effects, [id]: frozen }),\n\t\t}),\n\t};\n}\n\n/** Fold a persisted record list into journal state; the first bad record stops the replay. */\nexport function replayEffectJournal(records: readonly EffectRecord[]): EffectJournalResult<EffectJournalState> {\n\tlet state = initialEffectJournalState();\n\tfor (const [index, record] of records.entries()) {\n\t\tconst next = appendEffectRecord(state, record);\n\t\tif (!next.ok) {\n\t\t\tconst error = new EffectJournalViolation(\n\t\t\t\tnext.error.code,\n\t\t\t\t`Journal record ${index}: ${next.error.message}`,\n\t\t\t\tnext.error.effectId,\n\t\t\t);\n\t\t\treturn { ok: false, error };\n\t\t}\n\t\tstate = next.value;\n\t}\n\treturn { ok: true, value: state };\n}\n"]}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hash-chained effect journal reducer.
|
|
3
|
+
*
|
|
4
|
+
* Two entry points, one invariant. `reduceEffectJournal` is the write path:
|
|
5
|
+
* it turns a command into the next record — sequence, previous hash, and
|
|
6
|
+
* record hash all derived, never supplied — and refuses illegal moves.
|
|
7
|
+
* `appendEffectRecord` is the read/replay path: it re-verifies a persisted
|
|
8
|
+
* record against the same rules plus the chain, so a journal that was
|
|
9
|
+
* tampered with, truncated in the middle, or produced by a reducer with a
|
|
10
|
+
* different transition table fails to replay instead of silently loading.
|
|
11
|
+
*
|
|
12
|
+
* The state is plain data: the head hash, the last sequence, and the latest
|
|
13
|
+
* record per effect. It is a pure fold over the record list, so recovery
|
|
14
|
+
* cost is linear in journal length and replaying twice yields equal states.
|
|
15
|
+
*/
|
|
16
|
+
import { canonicalDigest, domainDigest } from "../harness/canonical-digest.js";
|
|
17
|
+
import { legalNextPhases, reduceEffectPhase } from "./effect-transitions.js";
|
|
18
|
+
import { EFFECT_JOURNAL_GENESIS_HASH, EFFECT_RECORD_SCHEMA_VERSION, EffectJournalViolation, } from "./effect-types.js";
|
|
19
|
+
export const EFFECT_ID_DOMAIN = "omk.effect.v2";
|
|
20
|
+
export const EFFECT_RECORD_DOMAIN = "omk.effect.record.v2";
|
|
21
|
+
const SEMANTICS = ["pure", "idempotent", "inspectable", "compensatable", "opaque"];
|
|
22
|
+
/** Stable effect identity per plan §6.5. Two logically distinct actions never share an id. */
|
|
23
|
+
export function deriveEffectId(input) {
|
|
24
|
+
const attemptPart = input.resumeToken === undefined ? `index:${input.attemptLogicalIndex}` : `resume:${input.resumeToken}`;
|
|
25
|
+
return domainDigest(EFFECT_ID_DOMAIN, [input.operationId, attemptPart, input.toolCallId, input.intentDigest]);
|
|
26
|
+
}
|
|
27
|
+
export function initialEffectJournalState() {
|
|
28
|
+
return { headHash: EFFECT_JOURNAL_GENESIS_HASH, lastSequence: 0, effects: {} };
|
|
29
|
+
}
|
|
30
|
+
export function computeEffectRecordHash(record) {
|
|
31
|
+
return canonicalDigest({ domain: EFFECT_RECORD_DOMAIN, record });
|
|
32
|
+
}
|
|
33
|
+
export function lookupEffect(state, effectId) {
|
|
34
|
+
return Object.hasOwn(state.effects, effectId) ? state.effects[effectId] : undefined;
|
|
35
|
+
}
|
|
36
|
+
function fail(code, message, effectId) {
|
|
37
|
+
return { ok: false, error: new EffectJournalViolation(code, message, effectId) };
|
|
38
|
+
}
|
|
39
|
+
function nonEmpty(value) {
|
|
40
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
41
|
+
}
|
|
42
|
+
function validatePrepare(identity, intent, timestamp) {
|
|
43
|
+
for (const [name, value] of [
|
|
44
|
+
["effectId", identity.effectId],
|
|
45
|
+
["operationId", identity.operationId],
|
|
46
|
+
["attemptId", identity.attemptId],
|
|
47
|
+
["processIncarnation", identity.processIncarnation],
|
|
48
|
+
["capabilityDigest", intent.capabilityDigest],
|
|
49
|
+
["intentDigest", intent.intentDigest],
|
|
50
|
+
["timestamp", timestamp],
|
|
51
|
+
]) {
|
|
52
|
+
if (!nonEmpty(value))
|
|
53
|
+
return `${name} must be a non-empty string`;
|
|
54
|
+
}
|
|
55
|
+
if (!SEMANTICS.includes(intent.semantics))
|
|
56
|
+
return `unknown semantics ${String(intent.semantics)}`;
|
|
57
|
+
if (intent.semantics === "idempotent" && !nonEmpty(intent.idempotencyKey)) {
|
|
58
|
+
return "idempotent effects require an idempotencyKey";
|
|
59
|
+
}
|
|
60
|
+
if (intent.semantics === "compensatable" && intent.compensationDescriptor === undefined) {
|
|
61
|
+
return "compensatable effects require a compensationDescriptor";
|
|
62
|
+
}
|
|
63
|
+
if (intent.semantics === "inspectable" && intent.inspectDescriptor === undefined) {
|
|
64
|
+
return "inspectable effects require an inspectDescriptor";
|
|
65
|
+
}
|
|
66
|
+
if (identity.laneEpoch !== undefined && (!Number.isInteger(identity.laneEpoch) || identity.laneEpoch < 0)) {
|
|
67
|
+
return "laneEpoch must be a non-negative integer";
|
|
68
|
+
}
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
function seal(state, body) {
|
|
72
|
+
const unsealed = { ...body, sequence: state.lastSequence + 1, previousRecordHash: state.headHash };
|
|
73
|
+
const record = Object.freeze({ ...unsealed, recordHash: computeEffectRecordHash(unsealed) });
|
|
74
|
+
const next = Object.freeze({
|
|
75
|
+
headHash: record.recordHash,
|
|
76
|
+
lastSequence: record.sequence,
|
|
77
|
+
effects: Object.freeze({ ...state.effects, [record.effectId]: record }),
|
|
78
|
+
});
|
|
79
|
+
return { ok: true, value: { state: next, record } };
|
|
80
|
+
}
|
|
81
|
+
/** Write path: derive and chain the next record for `command`, or reject it. */
|
|
82
|
+
export function reduceEffectJournal(state, command) {
|
|
83
|
+
if (command.type === "prepare") {
|
|
84
|
+
const problem = validatePrepare(command.identity, command.intent, command.timestamp);
|
|
85
|
+
if (problem !== undefined)
|
|
86
|
+
return fail("invalid_record", problem, command.identity.effectId);
|
|
87
|
+
if (lookupEffect(state, command.identity.effectId) !== undefined) {
|
|
88
|
+
return fail("duplicate_effect", `Effect ${command.identity.effectId} is already journaled`, command.identity.effectId);
|
|
89
|
+
}
|
|
90
|
+
return seal(state, {
|
|
91
|
+
...command.identity,
|
|
92
|
+
...command.intent,
|
|
93
|
+
schemaVersion: EFFECT_RECORD_SCHEMA_VERSION,
|
|
94
|
+
phase: "prepared",
|
|
95
|
+
timestamp: command.timestamp,
|
|
96
|
+
reasonCode: "effect.prepared",
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
const latest = lookupEffect(state, command.effectId);
|
|
100
|
+
if (latest === undefined)
|
|
101
|
+
return fail("unknown_effect", `Effect ${command.effectId} is not journaled`, command.effectId);
|
|
102
|
+
if (!nonEmpty(command.timestamp))
|
|
103
|
+
return fail("invalid_record", "timestamp must be a non-empty string", command.effectId);
|
|
104
|
+
const moved = reduceEffectPhase(latest, command);
|
|
105
|
+
if (!moved.ok)
|
|
106
|
+
return moved;
|
|
107
|
+
const { recordHash: _hash, sequence: _sequence, previousRecordHash: _previous, ...carried } = latest;
|
|
108
|
+
return seal(state, {
|
|
109
|
+
...carried,
|
|
110
|
+
phase: moved.value.phase,
|
|
111
|
+
timestamp: command.timestamp,
|
|
112
|
+
reasonCode: moved.value.reasonCode,
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
const IDENTITY_FIELDS = [
|
|
116
|
+
"operationId",
|
|
117
|
+
"attemptId",
|
|
118
|
+
"laneId",
|
|
119
|
+
"laneEpoch",
|
|
120
|
+
"processIncarnation",
|
|
121
|
+
"semantics",
|
|
122
|
+
"capabilityDigest",
|
|
123
|
+
"intentDigest",
|
|
124
|
+
"idempotencyKey",
|
|
125
|
+
];
|
|
126
|
+
/** Replay path: verify a persisted record against the chain and the transition table, then apply it. */
|
|
127
|
+
export function appendEffectRecord(state, record) {
|
|
128
|
+
const id = record.effectId;
|
|
129
|
+
if (record.schemaVersion !== EFFECT_RECORD_SCHEMA_VERSION) {
|
|
130
|
+
return fail("invalid_record", `Unsupported effect record schema ${String(record.schemaVersion)}`, id);
|
|
131
|
+
}
|
|
132
|
+
if (record.sequence !== state.lastSequence + 1) {
|
|
133
|
+
return fail("sequence_violation", `Record sequence ${record.sequence} is not ${state.lastSequence + 1}`, id);
|
|
134
|
+
}
|
|
135
|
+
if (record.previousRecordHash !== state.headHash) {
|
|
136
|
+
return fail("chain_break", `Record ${record.sequence} chains to ${record.previousRecordHash}, head is ${state.headHash}`, id);
|
|
137
|
+
}
|
|
138
|
+
const { recordHash, ...body } = record;
|
|
139
|
+
if (computeEffectRecordHash(body) !== recordHash) {
|
|
140
|
+
return fail("hash_mismatch", `Record ${record.sequence} hash does not match its contents`, id);
|
|
141
|
+
}
|
|
142
|
+
const latest = lookupEffect(state, id);
|
|
143
|
+
if (latest === undefined) {
|
|
144
|
+
const problem = validatePrepare(record, record, record.timestamp);
|
|
145
|
+
if (problem !== undefined)
|
|
146
|
+
return fail("invalid_record", problem, id);
|
|
147
|
+
if (record.phase !== "prepared")
|
|
148
|
+
return fail("invalid_record", `First record for ${id} must be prepared`, id);
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
for (const field of IDENTITY_FIELDS) {
|
|
152
|
+
if (latest[field] !== record[field]) {
|
|
153
|
+
return fail("identity_mismatch", `Record ${record.sequence} changes ${field} of effect ${id}`, id);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
if (!legalNextPhases(latest).includes(record.phase)) {
|
|
157
|
+
return fail("invalid_transition", `Effect ${id} cannot move ${latest.phase} -> ${record.phase}`, id);
|
|
158
|
+
}
|
|
159
|
+
if (record.phase === "abandoned" && !nonEmpty(record.reasonCode)) {
|
|
160
|
+
return fail("invalid_record", `Abandoned record for ${id} carries no reason code`, id);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const frozen = Object.freeze({ ...record });
|
|
164
|
+
return {
|
|
165
|
+
ok: true,
|
|
166
|
+
value: Object.freeze({
|
|
167
|
+
headHash: frozen.recordHash,
|
|
168
|
+
lastSequence: frozen.sequence,
|
|
169
|
+
effects: Object.freeze({ ...state.effects, [id]: frozen }),
|
|
170
|
+
}),
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
/** Fold a persisted record list into journal state; the first bad record stops the replay. */
|
|
174
|
+
export function replayEffectJournal(records) {
|
|
175
|
+
let state = initialEffectJournalState();
|
|
176
|
+
for (const [index, record] of records.entries()) {
|
|
177
|
+
const next = appendEffectRecord(state, record);
|
|
178
|
+
if (!next.ok) {
|
|
179
|
+
const error = new EffectJournalViolation(next.error.code, `Journal record ${index}: ${next.error.message}`, next.error.effectId);
|
|
180
|
+
return { ok: false, error };
|
|
181
|
+
}
|
|
182
|
+
state = next.value;
|
|
183
|
+
}
|
|
184
|
+
return { ok: true, value: state };
|
|
185
|
+
}
|
|
186
|
+
//# sourceMappingURL=effect-journal.js.map
|