@ponythewhite/base-context-agent 1.0.21 → 1.1.1

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.
@@ -1 +1 @@
1
- {"version":3,"file":"agent-loop.d.ts","sourceRoot":"","sources":["../src/agent-loop.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAIN,WAAW,EAMX,MAAM,+BAA+B,CAAC;AAEvC,OAAO,KAAK,EACX,YAAY,EAEZ,UAAU,EACV,eAAe,EACf,YAAY,EAMZ,QAAQ,EAGR,MAAM,YAAY,CAAC;AAEpB,MAAM,MAAM,cAAc,GAAG,CAAC,KAAK,EAAE,UAAU,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;AAwJzE;;;GAGG;AACH,wBAAgB,SAAS,CACxB,OAAO,EAAE,YAAY,EAAE,EACvB,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,WAAW,CAAC,UAAU,EAAE,YAAY,EAAE,CAAC,CAkBzC;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAChC,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,WAAW,CAAC,UAAU,EAAE,YAAY,EAAE,CAAC,CAyBzC;AA8ED,wBAAsB,YAAY,CACjC,OAAO,EAAE,YAAY,EAAE,EACvB,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,IAAI,EAAE,cAAc,EACpB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,OAAO,CAAC,YAAY,EAAE,CAAC,CAkBzB;AAED,wBAAsB,oBAAoB,CACzC,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,IAAI,EAAE,cAAc,EACpB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,OAAO,CAAC,YAAY,EAAE,CAAC,CAiBzB","sourcesContent":["/**\n * Agent loop that works with AgentMessage throughout.\n * Transforms to Message[] only at the LLM call boundary.\n */\n\nimport {\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\ttype Context,\n\tEventStream,\n\tisLocalRequestPreparationError,\n\tmarkLocalRequestPreparationError,\n\tstreamSimple,\n\ttype ToolResultMessage,\n\tvalidateToolArguments,\n} from \"@ponythewhite/base-context-ai\";\nimport { AgentOutputLimitError, InvocationOutput } from \"./invocation-output.js\";\nimport type {\n\tAgentContext,\n\tAgentContextBuildResult,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentTool,\n\tAgentToolCall,\n\tAgentToolResult,\n\tBoundToolExecution,\n\tFinalizedToolExchange,\n\tStreamFn,\n\tToolExecutionMode,\n\tToolExecutionOutcome,\n} from \"./types.js\";\n\nexport type AgentEventSink = (event: AgentEvent) => Promise<void> | void;\n\nconst ABORT_ERROR_MESSAGE = \"Request was aborted\";\nconst EMPTY_USAGE: AssistantMessage[\"usage\"] = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nfunction createAbortError(): Error {\n\treturn new Error(ABORT_ERROR_MESSAGE);\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n\tif (signal?.aborted) {\n\t\tthrow createAbortError();\n\t}\n}\n\nfunction raceWithAbort<T>(operation: Promise<T>, signal: AbortSignal | undefined, onAbort?: () => void): Promise<T> {\n\tif (!signal) {\n\t\treturn operation;\n\t}\n\tif (signal.aborted) {\n\t\tonAbort?.();\n\t\tvoid operation.catch(() => undefined);\n\t\treturn Promise.reject(createAbortError());\n\t}\n\n\treturn new Promise<T>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst cleanup = () => {\n\t\t\tsignal.removeEventListener(\"abort\", abort);\n\t\t};\n\t\tconst abort = () => {\n\t\t\tif (settled) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tonAbort?.();\n\t\t\treject(createAbortError());\n\t\t};\n\t\tsignal.addEventListener(\"abort\", abort, { once: true });\n\t\toperation.then(\n\t\t\t(value) => {\n\t\t\t\tif (settled) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettled = true;\n\t\t\t\tcleanup();\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\tif (settled) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettled = true;\n\t\t\t\tcleanup();\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\nfunction maybePromiseWithAbort<T>(\n\toperation: T | Promise<T>,\n\tsignal: AbortSignal | undefined,\n\tonAbort?: () => void,\n): Promise<T> {\n\treturn raceWithAbort(Promise.resolve(operation), signal, onAbort);\n}\n\nfunction isAbortError(error: unknown): boolean {\n\treturn error instanceof Error && (error.message === ABORT_ERROR_MESSAGE || error.name === \"AbortError\");\n}\n\ntype PostTurnResult<T> = { status: \"completed\"; value: T } | { status: \"aborted\" };\n\nasync function settlePostTurn<T>(operation: Promise<T>, signal: AbortSignal | undefined): Promise<PostTurnResult<T>> {\n\ttry {\n\t\treturn { status: \"completed\", value: await operation };\n\t} catch (error) {\n\t\tif (signal?.aborted && isAbortError(error)) {\n\t\t\treturn { status: \"aborted\" };\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nfunction cloneAssistantContent(content: AssistantMessage[\"content\"]): AssistantMessage[\"content\"] {\n\treturn content.map((part) => {\n\t\tif (part.type === \"toolCall\") {\n\t\t\treturn { ...part, arguments: { ...part.arguments } };\n\t\t}\n\t\treturn { ...part };\n\t});\n}\n\nfunction cloneUsage(usage: AssistantMessage[\"usage\"]): AssistantMessage[\"usage\"] {\n\treturn { ...usage, cost: { ...usage.cost } };\n}\n\nfunction createAbortedAssistantMessage(\n\tconfig: AgentLoopConfig,\n\tpartialMessage: AssistantMessage | null,\n): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: partialMessage ? cloneAssistantContent(partialMessage.content) : [{ type: \"text\", text: \"\" }],\n\t\tapi: partialMessage?.api ?? config.model.api,\n\t\tprovider: partialMessage?.provider ?? config.model.provider,\n\t\tmodel: partialMessage?.model ?? config.model.id,\n\t\tusage: cloneUsage(partialMessage?.usage ?? EMPTY_USAGE),\n\t\tstopReason: \"aborted\",\n\t\terrorMessage: ABORT_ERROR_MESSAGE,\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction getTerminalMessage(event: Extract<AssistantMessageEvent, { type: \"done\" | \"error\" }>): AssistantMessage {\n\treturn event.type === \"done\" ? event.message : event.error;\n}\n\nfunction endAgentStreamOnError(\n\tstream: EventStream<AgentEvent, AgentMessage[]>,\n\tpromise: Promise<AgentMessage[]>,\n): void {\n\tvoid promise.then(\n\t\t(messages) => {\n\t\t\tstream.end(messages);\n\t\t},\n\t\t(error) => {\n\t\t\tif (error instanceof AgentOutputLimitError) stream.fail(error);\n\t\t\telse stream.end([]);\n\t\t},\n\t);\n}\n\nasync function pollMessagesUnlessAborted(\n\tpoll: (() => AgentMessage[] | Promise<AgentMessage[]>) | undefined,\n\tsignal: AbortSignal | undefined,\n): Promise<AgentMessage[]> {\n\tif (!poll || signal?.aborted) {\n\t\treturn [];\n\t}\n\treturn (await maybePromiseWithAbort(poll(), signal)) || [];\n}\n\n/**\n * Start an agent loop with a new prompt message.\n * The prompt is added to the context and events are emitted for it.\n */\nexport function agentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tconst stream = createAgentStream();\n\n\tendAgentStreamOnError(\n\t\tstream,\n\t\trunAgentLoop(\n\t\t\tprompts,\n\t\t\tcontext,\n\t\t\tconfig,\n\t\t\tasync (event) => {\n\t\t\t\tstream.push(event);\n\t\t\t},\n\t\t\tsignal,\n\t\t\tstreamFn,\n\t\t),\n\t);\n\n\treturn stream;\n}\n\n/**\n * Continue an agent loop from the current context without adding a new message.\n * Used for retries - context already has user message or tool results.\n *\n * **Important:** The last message in context must convert to a `user` or `toolResult` message\n * via `convertToLlm`. If it doesn't, the LLM provider will reject the request.\n * This cannot be validated here since `convertToLlm` is only called once per turn.\n */\nexport function agentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\tif (context.messages[context.messages.length - 1].role === \"assistant\") {\n\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t}\n\n\tconst stream = createAgentStream();\n\n\tendAgentStreamOnError(\n\t\tstream,\n\t\trunAgentLoopContinue(\n\t\t\tcontext,\n\t\t\tconfig,\n\t\t\tasync (event) => {\n\t\t\t\tstream.push(event);\n\t\t\t},\n\t\t\tsignal,\n\t\t\tstreamFn,\n\t\t),\n\t);\n\n\treturn stream;\n}\n\nasync function withInvocationOutput(\n\tmessages: AgentMessage[],\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\trun: (emit: AgentEventSink, output: InvocationOutput | undefined) => Promise<void>,\n): Promise<AgentMessage[]> {\n\tconst output = config.outputPolicy ? new InvocationOutput(config.outputPolicy, messages) : undefined;\n\tlet releaseUpdates = output ? output.policy.bindUpdates?.(output.refresh.bind(output)) : undefined;\n\tconst stopUpdates = () => {\n\t\tconst release = releaseUpdates;\n\t\treleaseUpdates = undefined;\n\t\trelease?.();\n\t};\n\tlet updateSettlement: Promise<void> | undefined;\n\tconst settleUpdates = () => {\n\t\tif (!updateSettlement) {\n\t\t\ttry {\n\t\t\t\tupdateSettlement = output?.policy.settleUpdates?.() ?? Promise.resolve();\n\t\t\t} catch (error) {\n\t\t\t\tupdateSettlement = Promise.reject(error);\n\t\t\t}\n\t\t}\n\t\treturn updateSettlement;\n\t};\n\tconst ownedEmit: AgentEventSink = output\n\t\t? async (event) => {\n\t\t\t\tif (event.type === \"agent_end\") {\n\t\t\t\t\tawait settleUpdates();\n\t\t\t\t\toutput.throwIfRefused();\n\t\t\t\t\tconst finalizedMessages = output.copy();\n\t\t\t\t\tstopUpdates();\n\t\t\t\t\tawait emit({ type: \"agent_end\", messages: finalizedMessages });\n\t\t\t\t} else {\n\t\t\t\t\tawait emit(event);\n\t\t\t\t\t// The native sink joins this message's replacement/persistence job. Keep its original subject.\n\t\t\t\t\tif (event.type === \"message_end\") output.capture(event.message);\n\t\t\t\t}\n\t\t\t}\n\t\t: emit;\n\ttry {\n\t\tawait run(ownedEmit, output);\n\t\treturn messages;\n\t} catch (error) {\n\t\tif (!output) throw error;\n\t\tlet failure = error;\n\t\ttry {\n\t\t\tawait settleUpdates();\n\t\t} catch (settlementError) {\n\t\t\tif (settlementError !== failure)\n\t\t\t\tfailure = new AggregateError(\n\t\t\t\t\t[failure, settlementError],\n\t\t\t\t\t\"Invocation and accepted update settlement failed\",\n\t\t\t\t\t{ cause: failure },\n\t\t\t\t);\n\t\t}\n\t\tif (!output.refusal) throw failure;\n\t\tlet cause: unknown = failure instanceof AgentOutputLimitError ? failure.cause : failure;\n\t\tstopUpdates();\n\t\ttry {\n\t\t\tawait emit({ type: \"agent_end\", refusal: { ...output.refusal } });\n\t\t} catch (notificationError) {\n\t\t\tcause =\n\t\t\t\tcause === undefined\n\t\t\t\t\t? notificationError\n\t\t\t\t\t: new AggregateError([cause, notificationError], \"Output refusal and terminal notification failed\");\n\t\t}\n\t\tthrow new AgentOutputLimitError({ ...output.refusal }, cause === undefined ? undefined : { cause });\n\t} finally {\n\t\ttry {\n\t\t\tstopUpdates();\n\t\t} finally {\n\t\t\toutput?.dispose();\n\t\t}\n\t}\n}\n\nexport async function runAgentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): Promise<AgentMessage[]> {\n\tconst newMessages: AgentMessage[] = config.outputPolicy ? [] : [...prompts];\n\treturn withInvocationOutput(newMessages, config, emit, async (ownedEmit, output) => {\n\t\tif (output) {\n\t\t\toutput.checkRoom(prompts.length);\n\t\t\tprompts = [...prompts];\n\t\t}\n\t\t// Keep only the working wrapper across awaits, not the initial snapshot.\n\t\tcontext = { ...context, messages: [...context.messages, ...prompts] };\n\t\tawait ownedEmit({ type: \"agent_start\" });\n\t\tawait ownedEmit({ type: \"turn_start\" });\n\t\tfor (const prompt of prompts) {\n\t\t\tawait ownedEmit({ type: \"message_start\", message: prompt });\n\t\t\tawait ownedEmit({ type: \"message_end\", message: prompt });\n\t\t\toutput?.throwIfRefused();\n\t\t}\n\t\tawait runLoop(context, newMessages, config, signal, ownedEmit, streamFn, output);\n\t});\n}\n\nexport async function runAgentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): Promise<AgentMessage[]> {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\tif (context.messages[context.messages.length - 1].role === \"assistant\") {\n\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t}\n\n\tconst newMessages: AgentMessage[] = [];\n\treturn withInvocationOutput(newMessages, config, emit, async (ownedEmit, output) => {\n\t\tcontext = { ...context };\n\t\tawait ownedEmit({ type: \"agent_start\" });\n\t\toutput?.throwIfRefused();\n\t\tawait ownedEmit({ type: \"turn_start\" });\n\t\tawait runLoop(context, newMessages, config, signal, ownedEmit, streamFn, output);\n\t});\n}\n\nfunction createAgentStream(): EventStream<AgentEvent, AgentMessage[]> {\n\treturn new EventStream<AgentEvent, AgentMessage[]>(\n\t\t(event: AgentEvent) => event.type === \"agent_end\" && !event.refusal,\n\t\t(event: AgentEvent) => (event.type === \"agent_end\" && !event.refusal ? event.messages : []),\n\t);\n}\n\nasync function runLoop(\n\tcurrentContext: AgentContext,\n\tnewMessages: AgentMessage[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n\toutput?: InvocationOutput,\n): Promise<void> {\n\tlet firstTurn = true;\n\tlet lastTurn: Parameters<NonNullable<AgentLoopConfig[\"getContinuationMessages\"]>>[0] | undefined;\n\tlet pendingMessages: AgentMessage[] = await pollMessagesUnlessAborted(config.getSteeringMessages, signal);\n\n\tconst shouldStopBeforeTurn = (): boolean => !firstTurn && (config.shouldStopBeforeTurn?.() ?? false);\n\n\twhile (true) {\n\t\tthrowIfAborted(signal);\n\t\tlet hasMoreToolCalls = true;\n\n\t\twhile (hasMoreToolCalls || pendingMessages.length > 0) {\n\t\t\tthrowIfAborted(signal);\n\t\t\tif (!firstTurn) {\n\t\t\t\tawait emit({ type: \"turn_start\" });\n\t\t\t} else {\n\t\t\t\tfirstTurn = false;\n\t\t\t}\n\n\t\t\tif (pendingMessages.length > 0) {\n\t\t\t\toutput?.checkRoom(pendingMessages.length);\n\t\t\t\tif (output) pendingMessages = [...pendingMessages];\n\t\t\t\tfor (const message of pendingMessages) {\n\t\t\t\t\tawait emit({ type: \"message_start\", message });\n\t\t\t\t\tawait emit({ type: \"message_end\", message });\n\t\t\t\t\tcurrentContext.messages.push(message);\n\t\t\t\t\tif (!output) newMessages.push(message);\n\t\t\t\t\toutput?.throwIfRefused();\n\t\t\t\t}\n\t\t\t\tpendingMessages = [];\n\t\t\t}\n\n\t\t\toutput?.checkRoom(1);\n\t\t\tconst message = await streamAssistantResponse(currentContext, config, signal, emit, streamFn);\n\t\t\tif (!output) newMessages.push(message);\n\t\t\toutput?.throwIfRefused();\n\n\t\t\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\t\t\tawait emit({\n\t\t\t\t\ttype: \"turn_end\",\n\t\t\t\t\tmessage,\n\t\t\t\t\ttoolResults: [],\n\t\t\t\t\ttoolExecution: config.toolExecution ?? \"parallel\",\n\t\t\t\t\texchanges: [],\n\t\t\t\t});\n\t\t\t\toutput?.refresh(message);\n\t\t\t\tif (\n\t\t\t\t\tmessage.stopReason === \"error\" &&\n\t\t\t\t\tconfig.recoverProviderFailure &&\n\t\t\t\t\t(await maybePromiseWithAbort(config.recoverProviderFailure(message, signal), signal))\n\t\t\t\t) {\n\t\t\t\t\t// Retain and charge the failed output; only omit it from the next request.\n\t\t\t\t\tcurrentContext.messages = currentContext.messages.filter((candidate) => candidate !== message);\n\t\t\t\t\thasMoreToolCalls = true;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst toolCalls = message.content.filter((c) => c.type === \"toolCall\");\n\n\t\t\tconst toolResults: ToolResultMessage[] = [];\n\t\t\tconst exchanges: FinalizedToolExchange[] = [];\n\t\t\tlet toolExecution = config.toolExecution ?? \"parallel\";\n\t\t\thasMoreToolCalls = false;\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\toutput?.checkRoom(toolCalls.length);\n\t\t\t\tconst executedToolBatch = await executeToolCalls(currentContext, message, config, signal, emit, output);\n\t\t\t\ttoolResults.push(...executedToolBatch.messages);\n\t\t\t\texchanges.push(...executedToolBatch.exchanges);\n\t\t\t\ttoolExecution = executedToolBatch.toolExecution;\n\t\t\t\thasMoreToolCalls = !executedToolBatch.terminate;\n\n\t\t\t\tfor (const result of toolResults) {\n\t\t\t\t\tcurrentContext.messages.push(result);\n\t\t\t\t\tif (!output) newMessages.push(result);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\toutput?.throwIfRefused();\n\t\t\tawait emit({ type: \"turn_end\", message, toolResults, toolExecution, exchanges });\n\t\t\toutput?.refresh(message);\n\t\t\tfor (const result of toolResults) output?.refresh(result);\n\t\t\toutput?.throwIfRefused();\n\t\t\tif (signal?.aborted) {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlastTurn = {\n\t\t\t\tmessage,\n\t\t\t\ttoolResults,\n\t\t\t\tcontext: currentContext,\n\t\t\t\tnewMessages,\n\t\t\t};\n\n\t\t\tconst turnContext = { ...lastTurn, newMessages: output?.copy() ?? newMessages };\n\t\t\tconst shouldStopResult = await settlePostTurn(\n\t\t\t\tmaybePromiseWithAbort(\n\t\t\t\t\tconfig.getTurnOutcome\n\t\t\t\t\t\t? config.getTurnOutcome({ ...turnContext, hasMoreToolCalls }, signal)\n\t\t\t\t\t\t: Promise.resolve(config.shouldStopAfterTurn?.(turnContext) ?? false).then((stop) => ({\n\t\t\t\t\t\t\t\tkind: stop ? (\"finish\" as const) : (\"proceed\" as const),\n\t\t\t\t\t\t\t})),\n\t\t\t\t\tsignal,\n\t\t\t\t),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\toutput?.refresh(message);\n\t\t\tfor (const result of toolResults) output?.refresh(result);\n\t\t\toutput?.throwIfRefused();\n\t\t\tif (shouldStopResult.status === \"aborted\") {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (shouldStopResult.value.kind !== \"proceed\" || shouldStopBeforeTurn()) {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst steeringMessagesResult = await settlePostTurn(\n\t\t\t\tpollMessagesUnlessAborted(config.getSteeringMessages, signal),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (steeringMessagesResult.status === \"aborted\") {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpendingMessages = steeringMessagesResult.value;\n\t\t\t// Steering drained by this poll owns the turn boundary; stop only when it was empty.\n\t\t\tif (pendingMessages.length === 0 && shouldStopBeforeTurn()) {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (shouldStopBeforeTurn()) break;\n\t\tconst followUpMessagesResult = await settlePostTurn(\n\t\t\tpollMessagesUnlessAborted(config.getFollowUpMessages, signal),\n\t\t\tsignal,\n\t\t);\n\t\tif (followUpMessagesResult.status === \"aborted\") {\n\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\treturn;\n\t\t}\n\t\tconst followUpMessages = followUpMessagesResult.value;\n\t\tif (followUpMessages.length > 0) {\n\t\t\tpendingMessages = followUpMessages;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (shouldStopBeforeTurn()) break;\n\t\tif (lastTurn && config.getContinuationOutcome) {\n\t\t\tconst outcome = await settlePostTurn(\n\t\t\t\tmaybePromiseWithAbort(\n\t\t\t\t\tconfig.getContinuationOutcome(output ? { ...lastTurn, newMessages: output.copy() } : lastTurn, signal),\n\t\t\t\t\tsignal,\n\t\t\t\t),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (outcome.status === \"completed\" && outcome.value.kind === \"continue\") {\n\t\t\t\tpendingMessages = outcome.value.messages;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tconst continuationMessagesResult = lastTurn\n\t\t\t? await settlePostTurn(\n\t\t\t\t\tmaybePromiseWithAbort(\n\t\t\t\t\t\tconfig.getContinuationMessages?.(\n\t\t\t\t\t\t\toutput ? { ...lastTurn, newMessages: output.copy() } : lastTurn,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t) ?? [],\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t),\n\t\t\t\t\tsignal,\n\t\t\t\t)\n\t\t\t: ({ status: \"completed\", value: [] } satisfies PostTurnResult<AgentMessage[]>);\n\t\tif (continuationMessagesResult.status === \"aborted\") {\n\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\treturn;\n\t\t}\n\t\tconst continuationMessages = continuationMessagesResult.value || [];\n\t\tif (continuationMessages.length > 0) {\n\t\t\tpendingMessages = continuationMessages;\n\t\t\tcontinue;\n\t\t}\n\n\t\tbreak;\n\t}\n\n\tawait emit({ type: \"agent_end\", messages: newMessages });\n}\n\nasync function streamAssistantResponse(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n\tallowRecovery = true,\n\tallowReprepare = true,\n): Promise<AssistantMessage> {\n\tconst build: { projection: AgentContextBuildResult } = { projection: undefined };\n\tlet addedPartial = false;\n\tconst runResponse = async (): Promise<AssistantMessage> => {\n\t\tlet partialMessage: AssistantMessage | null = null;\n\t\tconst finishAbortedMessage = async () => {\n\t\t\tconst finalMessage = createAbortedAssistantMessage(config, partialMessage);\n\t\t\tif (addedPartial) {\n\t\t\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t\t\t} else {\n\t\t\t\tcontext.messages.push(finalMessage);\n\t\t\t\tawait emit({ type: \"message_start\", message: { ...finalMessage } });\n\t\t\t}\n\t\t\tawait emit({ type: \"message_end\", message: finalMessage });\n\t\t\treturn finalMessage;\n\t\t};\n\n\t\ttry {\n\t\t\tthrowIfAborted(signal);\n\t\t\t// Do not race source persistence against cancellation; drain it before leaving this build.\n\t\t\tconst projection = await config.beforeContextBuild?.();\n\t\t\tbuild.projection = projection;\n\t\t\tif (projection && projection.adoptMessages === true) {\n\t\t\t\tcontext.messages = projection.messages.slice();\n\t\t\t\tawait config.onContextAdopted?.(context.messages);\n\t\t\t}\n\t\t\tthrowIfAborted(signal);\n\t\t\tlet messages = projection ? projection.messages.slice() : context.messages;\n\t\t\tif (config.transformContext) {\n\t\t\t\tmessages = await maybePromiseWithAbort(config.transformContext(messages, signal), signal);\n\t\t\t}\n\n\t\t\tconst llmMessages = await maybePromiseWithAbort(config.convertToLlm(messages), signal);\n\n\t\t\tconst streamFunction = streamFn || streamSimple;\n\n\t\t\tconst resolvedApiKey =\n\t\t\t\t(config.getApiKey\n\t\t\t\t\t? await maybePromiseWithAbort(config.getApiKey(config.model.provider), signal)\n\t\t\t\t\t: undefined) || config.apiKey;\n\n\t\t\tconst llmContext: Context = {\n\t\t\t\tsystemPrompt: config.getSystemPrompt?.() ?? context.systemPrompt,\n\t\t\t\tmessages: llmMessages,\n\t\t\t\ttools: context.tools,\n\t\t\t};\n\n\t\t\tconst {\n\t\t\t\tbeforeContextBuild: _beforeContextBuild,\n\t\t\t\tonContextAdopted: _onContextAdopted,\n\t\t\t\trecoverRequestPreparation: _recoverRequestPreparation,\n\t\t\t\trecoverProviderFailure: _recoverProviderFailure,\n\t\t\t\toutputPolicy: _outputPolicy,\n\t\t\t\townedStreamFn,\n\t\t\t\t...streamOptions\n\t\t\t} = config;\n\t\t\tconst options = { ...streamOptions, apiKey: resolvedApiKey, signal };\n\t\t\tconst response = await maybePromiseWithAbort(\n\t\t\t\townedStreamFn\n\t\t\t\t\t? ownedStreamFn(config.model, llmContext, options, projection ? projection.streamContext : undefined)\n\t\t\t\t\t: streamFunction(config.model, llmContext, options),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tconst iterator = response[Symbol.asyncIterator]();\n\t\t\tconst closeIterator = () => {\n\t\t\t\tvoid Promise.resolve(iterator.return?.()).catch(() => undefined);\n\t\t\t};\n\t\t\twhile (true) {\n\t\t\t\tconst next = await raceWithAbort<IteratorResult<AssistantMessageEvent>>(\n\t\t\t\t\titerator.next(),\n\t\t\t\t\tsignal,\n\t\t\t\t\tcloseIterator,\n\t\t\t\t);\n\t\t\t\tif (next.done) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tconst event = next.value;\n\t\t\t\tswitch (event.type) {\n\t\t\t\t\tcase \"start\":\n\t\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\t\tcontext.messages.push(partialMessage);\n\t\t\t\t\t\taddedPartial = true;\n\t\t\t\t\t\tawait emit({ type: \"message_start\", message: { ...partialMessage } });\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"text_start\":\n\t\t\t\t\tcase \"text_delta\":\n\t\t\t\t\tcase \"text_end\":\n\t\t\t\t\tcase \"thinking_start\":\n\t\t\t\t\tcase \"thinking_delta\":\n\t\t\t\t\tcase \"thinking_end\":\n\t\t\t\t\tcase \"toolcall_start\":\n\t\t\t\t\tcase \"toolcall_delta\":\n\t\t\t\t\tcase \"toolcall_end\":\n\t\t\t\t\t\tif (partialMessage) {\n\t\t\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\t\t\tcontext.messages[context.messages.length - 1] = partialMessage;\n\t\t\t\t\t\t\tawait emit({\n\t\t\t\t\t\t\t\ttype: \"message_update\",\n\t\t\t\t\t\t\t\tassistantMessageEvent: event,\n\t\t\t\t\t\t\t\tmessage: { ...partialMessage },\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"done\":\n\t\t\t\t\tcase \"error\": {\n\t\t\t\t\t\tlet finalMessage = getTerminalMessage(event);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tfinalMessage = await maybePromiseWithAbort(response.result(), signal);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tif (!signal?.aborted || !isAbortError(error)) {\n\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (addedPartial) {\n\t\t\t\t\t\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcontext.messages.push(finalMessage);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!addedPartial) {\n\t\t\t\t\t\t\tawait emit({ type: \"message_start\", message: { ...finalMessage } });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tawait emit({ type: \"message_end\", message: finalMessage });\n\t\t\t\t\t\treturn finalMessage;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst finalMessage = await maybePromiseWithAbort(response.result(), signal);\n\t\t\tif (addedPartial) {\n\t\t\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t\t\t} else {\n\t\t\t\tcontext.messages.push(finalMessage);\n\t\t\t\tawait emit({ type: \"message_start\", message: { ...finalMessage } });\n\t\t\t}\n\t\t\tawait emit({ type: \"message_end\", message: finalMessage });\n\t\t\treturn finalMessage;\n\t\t} catch (error) {\n\t\t\tif (signal?.aborted && isAbortError(error)) {\n\t\t\t\treturn await finishAbortedMessage();\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t};\n\n\tlet outcome: { message: AssistantMessage } | { error: unknown };\n\ttry {\n\t\toutcome = { message: await runResponse() };\n\t} catch (error) {\n\t\toutcome = { error };\n\t}\n\ttry {\n\t\tif (build.projection) await build.projection.release?.();\n\t} catch (error) {\n\t\tif (\"error\" in outcome) {\n\t\t\tthrow new AggregateError(\n\t\t\t\t[outcome.error, error],\n\t\t\t\t`Agent inference and context cleanup failed: ${String(outcome.error)}`,\n\t\t\t);\n\t\t}\n\t\tthrow error;\n\t}\n\tif (\"error\" in outcome) {\n\t\tif (\n\t\t\tallowRecovery &&\n\t\t\t!addedPartial &&\n\t\t\tisLocalRequestPreparationError(outcome.error) &&\n\t\t\tconfig.recoverRequestPreparation\n\t\t) {\n\t\t\tlet recovered: boolean | \"reprepare\";\n\t\t\ttry {\n\t\t\t\trecovered = await config.recoverRequestPreparation(outcome.error, signal);\n\t\t\t} catch (error) {\n\t\t\t\t// Preserve the real owner error, including a post-ACK compaction failure.\n\t\t\t\tmarkLocalRequestPreparationError(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (recovered === \"reprepare\" && allowReprepare) {\n\t\t\t\t// A bounded deterministic change (for example, rebasing a TaskFrame) must\n\t\t\t\t// not consume the one recovery available if the new request still cannot fit.\n\t\t\t\treturn streamAssistantResponse(context, config, signal, emit, streamFn, true, false);\n\t\t\t}\n\t\t\tif (recovered === true) {\n\t\t\t\t// Keep this invocation's output collector, completed tools and emitted messages.\n\t\t\t\treturn streamAssistantResponse(context, config, signal, emit, streamFn, false, false);\n\t\t\t}\n\t\t}\n\t\tthrow outcome.error;\n\t}\n\treturn outcome.message;\n}\n\nasync function executeToolCalls(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\toutput?: InvocationOutput,\n): Promise<ExecutedToolCallBatch> {\n\tconst toolCalls = assistantMessage.content\n\t\t.filter((c) => c.type === \"toolCall\")\n\t\t.map((toolCall, sourceOrder) => ({\n\t\t\ttoolCall,\n\t\t\tsourceOrder,\n\t\t\texecutionId: crypto.randomUUID(),\n\t\t\tassistantMessage,\n\t\t\toriginalInput: structuredClone(toolCall.arguments),\n\t\t}));\n\tconst hasSequentialToolCall = toolCalls.some(\n\t\t({ toolCall }) => currentContext.tools?.find((t) => t.name === toolCall.name)?.executionMode === \"sequential\",\n\t);\n\tif (config.toolExecution === \"sequential\" || hasSequentialToolCall) {\n\t\treturn executeToolCallsSequential(currentContext, assistantMessage, toolCalls, config, signal, emit, output);\n\t}\n\treturn executeToolCallsParallel(currentContext, assistantMessage, toolCalls, config, signal, emit);\n}\n\ntype ToolCallSource = {\n\towner?: BoundToolExecution;\n\texecutionId: string;\n\tassistantMessage: AssistantMessage;\n\ttoolCall: AgentToolCall;\n\tsourceOrder: number;\n\toriginalInput: unknown;\n};\n\ntype ExecutedToolCallBatch = {\n\tmessages: ToolResultMessage[];\n\texchanges: FinalizedToolExchange[];\n\ttoolExecution: ToolExecutionMode;\n\tterminate: boolean;\n};\n\nasync function executeToolCallsSequential(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: ToolCallSource[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\toutput?: InvocationOutput,\n): Promise<ExecutedToolCallBatch> {\n\tconst finalizedCalls: FinalizedToolCallOutcome[] = [];\n\tconst messages: ToolResultMessage[] = [];\n\tconst exchanges: FinalizedToolExchange[] = [];\n\n\tfor (const source of toolCalls) {\n\t\tconst { toolCall } = source;\n\t\tif (signal?.aborted) {\n\t\t\tbreak;\n\t\t}\n\n\t\tawait emit({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\targs: toolCall.arguments,\n\t\t});\n\n\t\tconst preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);\n\t\tlet finalized: FinalizedToolCallOutcome;\n\t\tif (preparation.kind === \"immediate\") {\n\t\t\tfinalized = {\n\t\t\t\ttoolCall,\n\t\t\t\tresult: preparation.result,\n\t\t\t\tisError: preparation.isError,\n\t\t\t\texecutionOutcome: \"not_started\",\n\t\t\t};\n\t\t} else {\n\t\t\tconst executed = await executePreparedToolCall(preparation, source, \"sequential\", config, signal, emit);\n\t\t\tfinalized = await finalizeExecutedToolCall(\n\t\t\t\tcurrentContext,\n\t\t\t\tassistantMessage,\n\t\t\t\tpreparation,\n\t\t\t\texecuted,\n\t\t\t\tconfig,\n\t\t\t\tsignal,\n\t\t\t);\n\t\t}\n\n\t\tconst published = await publishToolExchange(finalized, source, \"sequential\", config, signal, emit);\n\t\tawait emitToolResultMessage(published.exchange.result, emit);\n\t\tfinalizedCalls.push(finalized);\n\t\tmessages.push(published.exchange.result);\n\t\texchanges.push(published.exchange);\n\n\t\tif (signal?.aborted || output?.refusal) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn {\n\t\tmessages,\n\t\texchanges,\n\t\ttoolExecution: \"sequential\",\n\t\tterminate: shouldTerminateToolBatch(finalizedCalls),\n\t};\n}\n\nasync function executeToolCallsParallel(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: ToolCallSource[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallBatch> {\n\tconst finalizedCalls: FinalizedToolCallEntry[] = [];\n\n\tfor (const source of toolCalls) {\n\t\tconst { toolCall } = source;\n\t\tawait emit({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\targs: toolCall.arguments,\n\t\t});\n\n\t\tconst preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);\n\t\tif (preparation.kind === \"immediate\") {\n\t\t\tconst finalized = {\n\t\t\t\ttoolCall,\n\t\t\t\tresult: preparation.result,\n\t\t\t\tisError: preparation.isError,\n\t\t\t\texecutionOutcome: \"not_started\",\n\t\t\t} satisfies FinalizedToolCallOutcome;\n\t\t\tfinalizedCalls.push(await publishToolExchange(finalized, source, \"parallel\", config, signal, emit));\n\t\t\tcontinue;\n\t\t}\n\n\t\tfinalizedCalls.push(async () => {\n\t\t\tconst executed = await executePreparedToolCall(preparation, source, \"parallel\", config, signal, emit);\n\t\t\tconst finalized = await finalizeExecutedToolCall(\n\t\t\t\tcurrentContext,\n\t\t\t\tassistantMessage,\n\t\t\t\tpreparation,\n\t\t\t\texecuted,\n\t\t\t\tconfig,\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\treturn publishToolExchange(finalized, source, \"parallel\", config, signal, emit);\n\t\t});\n\t}\n\n\t// An owner/publication failure must not abandon other invocations already started.\n\tconst settledCalls = await Promise.allSettled(\n\t\tfinalizedCalls.map((entry) => (typeof entry === \"function\" ? entry() : Promise.resolve(entry))),\n\t);\n\tconst orderedFinalizedCalls = settledCalls.flatMap((settled) =>\n\t\tsettled.status === \"fulfilled\" ? [settled.value] : [],\n\t);\n\tconst failure = settledCalls.find((settled) => settled.status === \"rejected\");\n\tconst messages: ToolResultMessage[] = [];\n\tfor (const finalized of orderedFinalizedCalls) {\n\t\tconst toolResultMessage = finalized.exchange.result;\n\t\tawait emitToolResultMessage(toolResultMessage, emit);\n\t\tmessages.push(toolResultMessage);\n\t}\n\n\tif (failure?.status === \"rejected\") throw failure.reason;\n\treturn {\n\t\tmessages,\n\t\texchanges: orderedFinalizedCalls.map((finalized) => finalized.exchange),\n\t\ttoolExecution: \"parallel\",\n\t\tterminate: shouldTerminateToolBatch(orderedFinalizedCalls),\n\t};\n}\n\ntype PreparedToolCall = {\n\tkind: \"prepared\";\n\ttoolCall: AgentToolCall;\n\ttool: AgentTool<any>;\n\targs: unknown;\n};\n\ntype ImmediateToolCallOutcome = {\n\tkind: \"immediate\";\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n};\n\ntype ExecutedToolCallOutcome = {\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n\texecutedInput?: unknown;\n\texecutionOutcome: ToolExecutionOutcome;\n};\n\ntype FinalizedToolCallOutcome = ExecutedToolCallOutcome & {\n\ttoolCall: AgentToolCall;\n};\n\ntype PublishedToolCallOutcome = FinalizedToolCallOutcome & { exchange: FinalizedToolExchange };\n\ntype FinalizedToolCallEntry = PublishedToolCallOutcome | (() => Promise<PublishedToolCallOutcome>);\n\nfunction shouldTerminateToolBatch(finalizedCalls: FinalizedToolCallOutcome[]): boolean {\n\treturn finalizedCalls.length > 0 && finalizedCalls.every((finalized) => finalized.result.terminate === true);\n}\n\nfunction prepareToolCallArguments(tool: AgentTool<any>, toolCall: AgentToolCall): AgentToolCall {\n\tif (!tool.prepareArguments) {\n\t\treturn toolCall;\n\t}\n\tconst preparedArguments = tool.prepareArguments(toolCall.arguments);\n\tif (preparedArguments === toolCall.arguments) {\n\t\treturn toolCall;\n\t}\n\treturn {\n\t\t...toolCall,\n\t\targuments: preparedArguments as Record<string, any>,\n\t};\n}\n\nasync function prepareToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCall: AgentToolCall,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<PreparedToolCall | ImmediateToolCallOutcome> {\n\tconst tool = currentContext.tools?.find((t) => t.name === toolCall.name);\n\tif (!tool) {\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(`Tool ${toolCall.name} not found`),\n\t\t\tisError: true,\n\t\t};\n\t}\n\n\ttry {\n\t\tconst preparedToolCall = prepareToolCallArguments(tool, toolCall);\n\t\tconst validatedArgs = validateToolArguments(tool, preparedToolCall);\n\t\tif (config.beforeToolCall) {\n\t\t\tconst beforeResult = await maybePromiseWithAbort(\n\t\t\t\tconfig.beforeToolCall(\n\t\t\t\t\t{\n\t\t\t\t\t\tassistantMessage,\n\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\targs: validatedArgs,\n\t\t\t\t\t\tcontext: currentContext,\n\t\t\t\t\t},\n\t\t\t\t\tsignal,\n\t\t\t\t),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (beforeResult?.block) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"immediate\",\n\t\t\t\t\tresult: createErrorToolResult(beforeResult.reason || \"Tool execution was blocked\"),\n\t\t\t\t\tisError: true,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tkind: \"prepared\",\n\t\t\ttoolCall,\n\t\t\ttool,\n\t\t\targs: validatedArgs,\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(error instanceof Error ? error.message : String(error)),\n\t\t\tisError: true,\n\t\t};\n\t}\n}\n\nasync function executePreparedToolCall(\n\tprepared: PreparedToolCall,\n\tsource: ToolCallSource,\n\ttoolExecution: ToolExecutionMode,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallOutcome> {\n\tconst invocationArgs = structuredClone(prepared.args);\n\tconst executedInput = structuredClone(invocationArgs);\n\tconst execute = prepared.tool.execute;\n\tif (!signal?.aborted) {\n\t\t// Admission failures must not become synthetic tool results or fall through to effects.\n\t\tconst owner = await config.onToolInvocationStarting?.(\n\t\t\t{\n\t\t\t\texecutionId: source.executionId,\n\t\t\t\tsourceOrder: source.sourceOrder,\n\t\t\t\ttoolCallId: prepared.toolCall.id,\n\t\t\t\ttoolName: prepared.toolCall.name,\n\t\t\t\toriginalInput: source.originalInput,\n\t\t\t\texecutedInput,\n\t\t\t\ttoolExecution,\n\t\t\t},\n\t\t\tsignal,\n\t\t\tprepared.tool,\n\t\t\texecute,\n\t\t\tsource.assistantMessage,\n\t\t);\n\t\tif (owner) source.owner = owner;\n\t}\n\tlet acceptingUpdates = true;\n\tlet pendingUpdates = 0;\n\tlet finishUpdates!: () => void;\n\tlet failUpdates!: (error: unknown) => void;\n\tconst updateEvents = new Promise<void>((resolve, reject) => {\n\t\tfinishUpdates = resolve;\n\t\tfailUpdates = reject;\n\t});\n\t// Observe early failures now; the normal execution path still awaits and reports them.\n\tvoid updateEvents.catch(() => undefined);\n\tconst settleUpdate = () => {\n\t\tpendingUpdates--;\n\t\tif (!acceptingUpdates && pendingUpdates === 0) finishUpdates();\n\t};\n\tconst stopUpdates = () => {\n\t\tacceptingUpdates = false;\n\t\tif (pendingUpdates === 0) finishUpdates();\n\t};\n\tlet executionStarted = false;\n\n\ttry {\n\t\tthrowIfAborted(signal);\n\t\texecutionStarted = true;\n\t\tconst run = () =>\n\t\t\texecute.call(prepared.tool, prepared.toolCall.id, invocationArgs as never, signal, (partialResult) => {\n\t\t\t\tif (!acceptingUpdates || signal?.aborted) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst update = Promise.resolve(\n\t\t\t\t\temit({\n\t\t\t\t\t\ttype: \"tool_execution_update\",\n\t\t\t\t\t\ttoolCallId: prepared.toolCall.id,\n\t\t\t\t\t\ttoolName: prepared.toolCall.name,\n\t\t\t\t\t\targs: prepared.toolCall.arguments,\n\t\t\t\t\t\tpartialResult,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\t// Do not retain every stdout callback or feed an unbounded array to Promise.all.\n\t\t\t\tpendingUpdates++;\n\t\t\t\tvoid update.then(settleUpdate, (error) => {\n\t\t\t\t\tfailUpdates(error);\n\t\t\t\t\tsettleUpdate();\n\t\t\t\t});\n\t\t\t});\n\t\tconst result = await raceWithAbort(source.owner ? source.owner.run(run) : run(), signal);\n\t\tstopUpdates();\n\t\ttry {\n\t\t\tawait raceWithAbort(updateEvents, signal);\n\t\t} catch (error) {\n\t\t\tif (!signal?.aborted || !isAbortError(error)) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\treturn { result, isError: false, executedInput, executionOutcome: \"completed\" };\n\t} catch (error) {\n\t\tstopUpdates();\n\t\tawait raceWithAbort(updateEvents, signal).catch(() => undefined);\n\t\treturn {\n\t\t\tresult: createErrorToolResult(\n\t\t\t\tsignal?.aborted ? \"Tool execution aborted\" : error instanceof Error ? error.message : String(error),\n\t\t\t),\n\t\t\tisError: true,\n\t\t\t...(executionStarted ? { executedInput } : {}),\n\t\t\texecutionOutcome: !executionStarted ? \"not_started\" : signal?.aborted ? \"outcome_unknown\" : \"failed\",\n\t\t};\n\t}\n}\n\nasync function finalizeExecutedToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tprepared: PreparedToolCall,\n\texecuted: ExecutedToolCallOutcome,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<FinalizedToolCallOutcome> {\n\tlet result = executed.result;\n\tlet isError = executed.isError;\n\n\tif (config.afterToolCall) {\n\t\ttry {\n\t\t\tconst afterResult = await maybePromiseWithAbort(\n\t\t\t\tconfig.afterToolCall(\n\t\t\t\t\t{\n\t\t\t\t\t\tassistantMessage,\n\t\t\t\t\t\ttoolCall: prepared.toolCall,\n\t\t\t\t\t\targs: prepared.args,\n\t\t\t\t\t\tresult,\n\t\t\t\t\t\tisError,\n\t\t\t\t\t\tcontext: currentContext,\n\t\t\t\t\t},\n\t\t\t\t\tsignal,\n\t\t\t\t),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (afterResult) {\n\t\t\t\tresult = {\n\t\t\t\t\tcontent: afterResult.content ?? result.content,\n\t\t\t\t\tdetails: afterResult.details ?? result.details,\n\t\t\t\t\tterminate: afterResult.terminate ?? result.terminate,\n\t\t\t\t};\n\t\t\t\tisError = afterResult.isError ?? isError;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tresult = createErrorToolResult(error instanceof Error ? error.message : String(error));\n\t\t\tisError = true;\n\t\t}\n\t}\n\n\treturn {\n\t\t...executed,\n\t\ttoolCall: prepared.toolCall,\n\t\tresult,\n\t\tisError,\n\t};\n}\n\nfunction createErrorToolResult(message: string): AgentToolResult<any> {\n\treturn {\n\t\tcontent: [{ type: \"text\", text: message }],\n\t\tdetails: {},\n\t};\n}\n\nasync function publishToolExchange(\n\tfinalized: FinalizedToolCallOutcome,\n\tsource: ToolCallSource,\n\ttoolExecution: ToolExecutionMode,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<PublishedToolCallOutcome> {\n\tconst exchange: FinalizedToolExchange = {\n\t\texecutionId: source.executionId,\n\t\tsourceOrder: source.sourceOrder,\n\t\ttoolCallId: finalized.toolCall.id,\n\t\ttoolName: finalized.toolCall.name,\n\t\toriginalInput: source.originalInput,\n\t\t...(finalized.executionOutcome === \"not_started\" ? {} : { executedInput: finalized.executedInput }),\n\t\ttoolExecution,\n\t\texecutionOutcome: finalized.executionOutcome,\n\t\tcancellationRequested: signal?.aborted ?? false,\n\t\tresult: createToolResultMessage(finalized),\n\t};\n\tawait config.onToolExchangeFinalized?.(exchange, signal, source.owner);\n\tawait emit({\n\t\ttype: \"tool_execution_end\",\n\t\ttoolCallId: finalized.toolCall.id,\n\t\ttoolName: finalized.toolCall.name,\n\t\tresult: finalized.result,\n\t\tisError: finalized.isError,\n\t\texchange,\n\t});\n\treturn { ...finalized, exchange };\n}\n\nfunction createToolResultMessage(finalized: FinalizedToolCallOutcome): ToolResultMessage {\n\treturn {\n\t\trole: \"toolResult\",\n\t\ttoolCallId: finalized.toolCall.id,\n\t\ttoolName: finalized.toolCall.name,\n\t\tcontent: finalized.result.content,\n\t\tdetails: finalized.result.details,\n\t\tisError: finalized.isError,\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nasync function emitToolResultMessage(toolResultMessage: ToolResultMessage, emit: AgentEventSink): Promise<void> {\n\tawait emit({ type: \"message_start\", message: toolResultMessage });\n\tawait emit({ type: \"message_end\", message: toolResultMessage });\n}\n"]}
1
+ {"version":3,"file":"agent-loop.d.ts","sourceRoot":"","sources":["../src/agent-loop.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAIN,WAAW,EAMX,MAAM,+BAA+B,CAAC;AAEvC,OAAO,KAAK,EACX,YAAY,EAEZ,UAAU,EACV,eAAe,EACf,YAAY,EAMZ,QAAQ,EAGR,MAAM,YAAY,CAAC;AAEpB,MAAM,MAAM,cAAc,GAAG,CAAC,KAAK,EAAE,UAAU,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;AAwJzE;;;GAGG;AACH,wBAAgB,SAAS,CACxB,OAAO,EAAE,YAAY,EAAE,EACvB,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,WAAW,CAAC,UAAU,EAAE,YAAY,EAAE,CAAC,CAkBzC;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAChC,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,WAAW,CAAC,UAAU,EAAE,YAAY,EAAE,CAAC,CAyBzC;AA8ED,wBAAsB,YAAY,CACjC,OAAO,EAAE,YAAY,EAAE,EACvB,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,IAAI,EAAE,cAAc,EACpB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,OAAO,CAAC,YAAY,EAAE,CAAC,CAkBzB;AAED,wBAAsB,oBAAoB,CACzC,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,IAAI,EAAE,cAAc,EACpB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,OAAO,CAAC,YAAY,EAAE,CAAC,CAiBzB","sourcesContent":["/**\n * Agent loop that works with AgentMessage throughout.\n * Transforms to Message[] only at the LLM call boundary.\n */\n\nimport {\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\ttype Context,\n\tEventStream,\n\tisLocalRequestPreparationError,\n\tmarkLocalRequestPreparationError,\n\tstreamSimple,\n\ttype ToolResultMessage,\n\tvalidateToolArguments,\n} from \"@ponythewhite/base-context-ai\";\nimport { AgentOutputLimitError, InvocationOutput } from \"./invocation-output.js\";\nimport type {\n\tAgentContext,\n\tAgentContextBuildResult,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentTool,\n\tAgentToolCall,\n\tAgentToolResult,\n\tBoundToolExecution,\n\tFinalizedToolExchange,\n\tStreamFn,\n\tToolExecutionMode,\n\tToolExecutionOutcome,\n} from \"./types.js\";\n\nexport type AgentEventSink = (event: AgentEvent) => Promise<void> | void;\n\nconst ABORT_ERROR_MESSAGE = \"Request was aborted\";\nconst EMPTY_USAGE: AssistantMessage[\"usage\"] = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nfunction createAbortError(): Error {\n\treturn new Error(ABORT_ERROR_MESSAGE);\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n\tif (signal?.aborted) {\n\t\tthrow createAbortError();\n\t}\n}\n\nfunction raceWithAbort<T>(operation: Promise<T>, signal: AbortSignal | undefined, onAbort?: () => void): Promise<T> {\n\tif (!signal) {\n\t\treturn operation;\n\t}\n\tif (signal.aborted) {\n\t\tonAbort?.();\n\t\tvoid operation.catch(() => undefined);\n\t\treturn Promise.reject(createAbortError());\n\t}\n\n\treturn new Promise<T>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst cleanup = () => {\n\t\t\tsignal.removeEventListener(\"abort\", abort);\n\t\t};\n\t\tconst abort = () => {\n\t\t\tif (settled) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tonAbort?.();\n\t\t\treject(createAbortError());\n\t\t};\n\t\tsignal.addEventListener(\"abort\", abort, { once: true });\n\t\toperation.then(\n\t\t\t(value) => {\n\t\t\t\tif (settled) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettled = true;\n\t\t\t\tcleanup();\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\tif (settled) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettled = true;\n\t\t\t\tcleanup();\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\nfunction maybePromiseWithAbort<T>(\n\toperation: T | Promise<T>,\n\tsignal: AbortSignal | undefined,\n\tonAbort?: () => void,\n): Promise<T> {\n\treturn raceWithAbort(Promise.resolve(operation), signal, onAbort);\n}\n\nfunction isAbortError(error: unknown): boolean {\n\treturn error instanceof Error && (error.message === ABORT_ERROR_MESSAGE || error.name === \"AbortError\");\n}\n\ntype PostTurnResult<T> = { status: \"completed\"; value: T } | { status: \"aborted\" };\n\nasync function settlePostTurn<T>(operation: Promise<T>, signal: AbortSignal | undefined): Promise<PostTurnResult<T>> {\n\ttry {\n\t\treturn { status: \"completed\", value: await operation };\n\t} catch (error) {\n\t\tif (signal?.aborted && isAbortError(error)) {\n\t\t\treturn { status: \"aborted\" };\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nfunction cloneAssistantContent(content: AssistantMessage[\"content\"]): AssistantMessage[\"content\"] {\n\treturn content.map((part) => {\n\t\tif (part.type === \"toolCall\") {\n\t\t\treturn { ...part, arguments: { ...part.arguments } };\n\t\t}\n\t\treturn { ...part };\n\t});\n}\n\nfunction cloneUsage(usage: AssistantMessage[\"usage\"]): AssistantMessage[\"usage\"] {\n\treturn { ...usage, cost: { ...usage.cost } };\n}\n\nfunction createAbortedAssistantMessage(\n\tconfig: AgentLoopConfig,\n\tpartialMessage: AssistantMessage | null,\n): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: partialMessage ? cloneAssistantContent(partialMessage.content) : [{ type: \"text\", text: \"\" }],\n\t\tapi: partialMessage?.api ?? config.model.api,\n\t\tprovider: partialMessage?.provider ?? config.model.provider,\n\t\tmodel: partialMessage?.model ?? config.model.id,\n\t\tusage: cloneUsage(partialMessage?.usage ?? EMPTY_USAGE),\n\t\tstopReason: \"aborted\",\n\t\terrorMessage: ABORT_ERROR_MESSAGE,\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction getTerminalMessage(event: Extract<AssistantMessageEvent, { type: \"done\" | \"error\" }>): AssistantMessage {\n\treturn event.type === \"done\" ? event.message : event.error;\n}\n\nfunction endAgentStreamOnError(\n\tstream: EventStream<AgentEvent, AgentMessage[]>,\n\tpromise: Promise<AgentMessage[]>,\n): void {\n\tvoid promise.then(\n\t\t(messages) => {\n\t\t\tstream.end(messages);\n\t\t},\n\t\t(error) => {\n\t\t\tif (error instanceof AgentOutputLimitError) stream.fail(error);\n\t\t\telse stream.end([]);\n\t\t},\n\t);\n}\n\nasync function pollMessagesUnlessAborted(\n\tpoll: (() => AgentMessage[] | Promise<AgentMessage[]>) | undefined,\n\tsignal: AbortSignal | undefined,\n): Promise<AgentMessage[]> {\n\tif (!poll || signal?.aborted) {\n\t\treturn [];\n\t}\n\treturn (await maybePromiseWithAbort(poll(), signal)) || [];\n}\n\n/**\n * Start an agent loop with a new prompt message.\n * The prompt is added to the context and events are emitted for it.\n */\nexport function agentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tconst stream = createAgentStream();\n\n\tendAgentStreamOnError(\n\t\tstream,\n\t\trunAgentLoop(\n\t\t\tprompts,\n\t\t\tcontext,\n\t\t\tconfig,\n\t\t\tasync (event) => {\n\t\t\t\tstream.push(event);\n\t\t\t},\n\t\t\tsignal,\n\t\t\tstreamFn,\n\t\t),\n\t);\n\n\treturn stream;\n}\n\n/**\n * Continue an agent loop from the current context without adding a new message.\n * Used for retries - context already has user message or tool results.\n *\n * **Important:** The last message in context must convert to a `user` or `toolResult` message\n * via `convertToLlm`. If it doesn't, the LLM provider will reject the request.\n * This cannot be validated here since `convertToLlm` is only called once per turn.\n */\nexport function agentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\tif (context.messages[context.messages.length - 1].role === \"assistant\") {\n\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t}\n\n\tconst stream = createAgentStream();\n\n\tendAgentStreamOnError(\n\t\tstream,\n\t\trunAgentLoopContinue(\n\t\t\tcontext,\n\t\t\tconfig,\n\t\t\tasync (event) => {\n\t\t\t\tstream.push(event);\n\t\t\t},\n\t\t\tsignal,\n\t\t\tstreamFn,\n\t\t),\n\t);\n\n\treturn stream;\n}\n\nasync function withInvocationOutput(\n\tmessages: AgentMessage[],\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\trun: (emit: AgentEventSink, output: InvocationOutput | undefined) => Promise<void>,\n): Promise<AgentMessage[]> {\n\tconst output = config.outputPolicy ? new InvocationOutput(config.outputPolicy, messages) : undefined;\n\tlet releaseUpdates = output ? output.policy.bindUpdates?.(output.refresh.bind(output)) : undefined;\n\tconst stopUpdates = () => {\n\t\tconst release = releaseUpdates;\n\t\treleaseUpdates = undefined;\n\t\trelease?.();\n\t};\n\tlet updateSettlement: Promise<void> | undefined;\n\tconst settleUpdates = () => {\n\t\tif (!updateSettlement) {\n\t\t\ttry {\n\t\t\t\tupdateSettlement = output?.policy.settleUpdates?.() ?? Promise.resolve();\n\t\t\t} catch (error) {\n\t\t\t\tupdateSettlement = Promise.reject(error);\n\t\t\t}\n\t\t}\n\t\treturn updateSettlement;\n\t};\n\tconst ownedEmit: AgentEventSink = output\n\t\t? async (event) => {\n\t\t\t\tif (event.type === \"agent_end\") {\n\t\t\t\t\tawait settleUpdates();\n\t\t\t\t\toutput.throwIfRefused();\n\t\t\t\t\tconst finalizedMessages = output.copy();\n\t\t\t\t\tstopUpdates();\n\t\t\t\t\tawait emit({ type: \"agent_end\", messages: finalizedMessages });\n\t\t\t\t} else {\n\t\t\t\t\tawait emit(event);\n\t\t\t\t\t// The native sink joins this message's replacement/persistence job. Keep its original subject.\n\t\t\t\t\tif (event.type === \"message_end\") output.capture(event.message);\n\t\t\t\t}\n\t\t\t}\n\t\t: emit;\n\ttry {\n\t\tawait run(ownedEmit, output);\n\t\treturn messages;\n\t} catch (error) {\n\t\tif (!output) throw error;\n\t\tlet failure = error;\n\t\ttry {\n\t\t\tawait settleUpdates();\n\t\t} catch (settlementError) {\n\t\t\tif (settlementError !== failure)\n\t\t\t\tfailure = new AggregateError(\n\t\t\t\t\t[failure, settlementError],\n\t\t\t\t\t\"Invocation and accepted update settlement failed\",\n\t\t\t\t\t{ cause: failure },\n\t\t\t\t);\n\t\t}\n\t\tif (!output.refusal) throw failure;\n\t\tlet cause: unknown = failure instanceof AgentOutputLimitError ? failure.cause : failure;\n\t\tstopUpdates();\n\t\ttry {\n\t\t\tawait emit({ type: \"agent_end\", refusal: { ...output.refusal } });\n\t\t} catch (notificationError) {\n\t\t\tcause =\n\t\t\t\tcause === undefined\n\t\t\t\t\t? notificationError\n\t\t\t\t\t: new AggregateError([cause, notificationError], \"Output refusal and terminal notification failed\");\n\t\t}\n\t\tthrow new AgentOutputLimitError({ ...output.refusal }, cause === undefined ? undefined : { cause });\n\t} finally {\n\t\ttry {\n\t\t\tstopUpdates();\n\t\t} finally {\n\t\t\toutput?.dispose();\n\t\t}\n\t}\n}\n\nexport async function runAgentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): Promise<AgentMessage[]> {\n\tconst newMessages: AgentMessage[] = config.outputPolicy ? [] : [...prompts];\n\treturn withInvocationOutput(newMessages, config, emit, async (ownedEmit, output) => {\n\t\tif (output) {\n\t\t\toutput.checkRoom(prompts.length);\n\t\t\tprompts = [...prompts];\n\t\t}\n\t\t// Keep only the working wrapper across awaits, not the initial snapshot.\n\t\tcontext = { ...context, messages: [...context.messages, ...prompts] };\n\t\tawait ownedEmit({ type: \"agent_start\" });\n\t\tawait ownedEmit({ type: \"turn_start\" });\n\t\tfor (const prompt of prompts) {\n\t\t\tawait ownedEmit({ type: \"message_start\", message: prompt });\n\t\t\tawait ownedEmit({ type: \"message_end\", message: prompt });\n\t\t\toutput?.throwIfRefused();\n\t\t}\n\t\tawait runLoop(context, newMessages, config, signal, ownedEmit, streamFn, output);\n\t});\n}\n\nexport async function runAgentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): Promise<AgentMessage[]> {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\tif (context.messages[context.messages.length - 1].role === \"assistant\") {\n\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t}\n\n\tconst newMessages: AgentMessage[] = [];\n\treturn withInvocationOutput(newMessages, config, emit, async (ownedEmit, output) => {\n\t\tcontext = { ...context };\n\t\tawait ownedEmit({ type: \"agent_start\" });\n\t\toutput?.throwIfRefused();\n\t\tawait ownedEmit({ type: \"turn_start\" });\n\t\tawait runLoop(context, newMessages, config, signal, ownedEmit, streamFn, output);\n\t});\n}\n\nfunction createAgentStream(): EventStream<AgentEvent, AgentMessage[]> {\n\treturn new EventStream<AgentEvent, AgentMessage[]>(\n\t\t(event: AgentEvent) => event.type === \"agent_end\" && !event.refusal,\n\t\t(event: AgentEvent) => (event.type === \"agent_end\" && !event.refusal ? event.messages : []),\n\t);\n}\n\nasync function runLoop(\n\tcurrentContext: AgentContext,\n\tnewMessages: AgentMessage[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n\toutput?: InvocationOutput,\n): Promise<void> {\n\tlet firstTurn = true;\n\tlet lastTurn: Parameters<NonNullable<AgentLoopConfig[\"getContinuationMessages\"]>>[0] | undefined;\n\tlet pendingMessages: AgentMessage[] = await pollMessagesUnlessAborted(config.getSteeringMessages, signal);\n\n\tconst shouldStopBeforeTurn = (): boolean => !firstTurn && (config.shouldStopBeforeTurn?.() ?? false);\n\n\twhile (true) {\n\t\tthrowIfAborted(signal);\n\t\tlet hasMoreToolCalls = true;\n\n\t\twhile (hasMoreToolCalls || pendingMessages.length > 0) {\n\t\t\tthrowIfAborted(signal);\n\t\t\tif (!firstTurn) {\n\t\t\t\tawait emit({ type: \"turn_start\" });\n\t\t\t} else {\n\t\t\t\tfirstTurn = false;\n\t\t\t}\n\n\t\t\tif (pendingMessages.length > 0) {\n\t\t\t\toutput?.checkRoom(pendingMessages.length);\n\t\t\t\tif (output) pendingMessages = [...pendingMessages];\n\t\t\t\tfor (const message of pendingMessages) {\n\t\t\t\t\tawait emit({ type: \"message_start\", message });\n\t\t\t\t\tawait emit({ type: \"message_end\", message });\n\t\t\t\t\tcurrentContext.messages.push(message);\n\t\t\t\t\tif (!output) newMessages.push(message);\n\t\t\t\t\toutput?.throwIfRefused();\n\t\t\t\t}\n\t\t\t\tpendingMessages = [];\n\t\t\t}\n\n\t\t\toutput?.checkRoom(1);\n\t\t\tconst message = await streamAssistantResponse(currentContext, config, signal, emit, streamFn);\n\t\t\tif (!output) newMessages.push(message);\n\t\t\toutput?.throwIfRefused();\n\n\t\t\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\t\t\tawait emit({\n\t\t\t\t\ttype: \"turn_end\",\n\t\t\t\t\tmessage,\n\t\t\t\t\ttoolResults: [],\n\t\t\t\t\ttoolExecution: config.toolExecution ?? \"parallel\",\n\t\t\t\t\texchanges: [],\n\t\t\t\t});\n\t\t\t\toutput?.refresh(message);\n\t\t\t\tif (\n\t\t\t\t\tmessage.stopReason === \"error\" &&\n\t\t\t\t\tconfig.recoverProviderFailure &&\n\t\t\t\t\t(await maybePromiseWithAbort(config.recoverProviderFailure(message, signal), signal))\n\t\t\t\t) {\n\t\t\t\t\t// Retain and charge the failed output; only omit it from the next request.\n\t\t\t\t\tcurrentContext.messages = currentContext.messages.filter((candidate) => candidate !== message);\n\t\t\t\t\thasMoreToolCalls = true;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst toolCalls = message.content.filter((c) => c.type === \"toolCall\");\n\n\t\t\tconst toolResults: ToolResultMessage[] = [];\n\t\t\tconst exchanges: FinalizedToolExchange[] = [];\n\t\t\tlet toolExecution = config.toolExecution ?? \"parallel\";\n\t\t\thasMoreToolCalls = false;\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\toutput?.checkRoom(toolCalls.length);\n\t\t\t\tconst executedToolBatch = await executeToolCalls(currentContext, message, config, signal, emit, output);\n\t\t\t\ttoolResults.push(...executedToolBatch.messages);\n\t\t\t\texchanges.push(...executedToolBatch.exchanges);\n\t\t\t\ttoolExecution = executedToolBatch.toolExecution;\n\t\t\t\thasMoreToolCalls = !executedToolBatch.terminate;\n\n\t\t\t\tfor (const result of toolResults) {\n\t\t\t\t\tcurrentContext.messages.push(result);\n\t\t\t\t\tif (!output) newMessages.push(result);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\toutput?.throwIfRefused();\n\t\t\tawait emit({ type: \"turn_end\", message, toolResults, toolExecution, exchanges });\n\t\t\toutput?.refresh(message);\n\t\t\tfor (const result of toolResults) output?.refresh(result);\n\t\t\toutput?.throwIfRefused();\n\t\t\tif (signal?.aborted) {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlastTurn = {\n\t\t\t\tmessage,\n\t\t\t\ttoolResults,\n\t\t\t\tcontext: currentContext,\n\t\t\t\tnewMessages,\n\t\t\t};\n\n\t\t\tconst turnContext = { ...lastTurn, newMessages: output?.copy() ?? newMessages };\n\t\t\tconst shouldStopResult = await settlePostTurn(\n\t\t\t\tmaybePromiseWithAbort(\n\t\t\t\t\tconfig.getTurnOutcome\n\t\t\t\t\t\t? config.getTurnOutcome({ ...turnContext, hasMoreToolCalls }, signal)\n\t\t\t\t\t\t: Promise.resolve(config.shouldStopAfterTurn?.(turnContext) ?? false).then((stop) => ({\n\t\t\t\t\t\t\t\tkind: stop ? (\"finish\" as const) : (\"proceed\" as const),\n\t\t\t\t\t\t\t})),\n\t\t\t\t\tsignal,\n\t\t\t\t),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\toutput?.refresh(message);\n\t\t\tfor (const result of toolResults) output?.refresh(result);\n\t\t\toutput?.throwIfRefused();\n\t\t\tif (shouldStopResult.status === \"aborted\") {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (shouldStopResult.value.kind !== \"proceed\" || shouldStopBeforeTurn()) {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst steeringMessagesResult = await settlePostTurn(\n\t\t\t\tpollMessagesUnlessAborted(config.getSteeringMessages, signal),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (steeringMessagesResult.status === \"aborted\") {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpendingMessages = steeringMessagesResult.value;\n\t\t\t// Steering drained by this poll owns the turn boundary; stop only when it was empty.\n\t\t\tif (pendingMessages.length === 0 && shouldStopBeforeTurn()) {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (shouldStopBeforeTurn()) break;\n\t\tconst followUpMessagesResult = await settlePostTurn(\n\t\t\tpollMessagesUnlessAborted(config.getFollowUpMessages, signal),\n\t\t\tsignal,\n\t\t);\n\t\tif (followUpMessagesResult.status === \"aborted\") {\n\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\treturn;\n\t\t}\n\t\tconst followUpMessages = followUpMessagesResult.value;\n\t\tif (followUpMessages.length > 0) {\n\t\t\tpendingMessages = followUpMessages;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (shouldStopBeforeTurn()) break;\n\t\tif (lastTurn && config.getContinuationOutcome) {\n\t\t\tconst outcome = await settlePostTurn(\n\t\t\t\tmaybePromiseWithAbort(\n\t\t\t\t\tconfig.getContinuationOutcome(output ? { ...lastTurn, newMessages: output.copy() } : lastTurn, signal),\n\t\t\t\t\tsignal,\n\t\t\t\t),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (outcome.status === \"completed\" && outcome.value.kind === \"continue\") {\n\t\t\t\tpendingMessages = outcome.value.messages;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tconst continuationMessagesResult = lastTurn\n\t\t\t? await settlePostTurn(\n\t\t\t\t\tmaybePromiseWithAbort(\n\t\t\t\t\t\tconfig.getContinuationMessages?.(\n\t\t\t\t\t\t\toutput ? { ...lastTurn, newMessages: output.copy() } : lastTurn,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t) ?? [],\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t),\n\t\t\t\t\tsignal,\n\t\t\t\t)\n\t\t\t: ({ status: \"completed\", value: [] } satisfies PostTurnResult<AgentMessage[]>);\n\t\tif (continuationMessagesResult.status === \"aborted\") {\n\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\treturn;\n\t\t}\n\t\tconst continuationMessages = continuationMessagesResult.value || [];\n\t\tif (continuationMessages.length > 0) {\n\t\t\tpendingMessages = continuationMessages;\n\t\t\tcontinue;\n\t\t}\n\n\t\tbreak;\n\t}\n\n\tawait emit({ type: \"agent_end\", messages: newMessages });\n}\n\nasync function streamAssistantResponse(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n\tallowRecovery = true,\n\tallowReprepare = true,\n): Promise<AssistantMessage> {\n\tconst build: { projection: AgentContextBuildResult } = { projection: undefined };\n\tlet addedPartial = false;\n\tconst runResponse = async (): Promise<AssistantMessage> => {\n\t\tlet partialMessage: AssistantMessage | null = null;\n\t\tconst finishAbortedMessage = async () => {\n\t\t\tconst finalMessage = createAbortedAssistantMessage(config, partialMessage);\n\t\t\tif (addedPartial) {\n\t\t\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t\t\t} else {\n\t\t\t\tcontext.messages.push(finalMessage);\n\t\t\t\tawait emit({ type: \"message_start\", message: { ...finalMessage } });\n\t\t\t}\n\t\t\tawait emit({ type: \"message_end\", message: finalMessage });\n\t\t\treturn finalMessage;\n\t\t};\n\n\t\ttry {\n\t\t\tthrowIfAborted(signal);\n\t\t\t// Do not race source persistence against cancellation; drain it before leaving this build.\n\t\t\tconst projection = await config.beforeContextBuild?.();\n\t\t\tbuild.projection = projection;\n\t\t\tif (projection && projection.adoptMessages === true) {\n\t\t\t\tcontext.messages = projection.messages.slice();\n\t\t\t\tawait config.onContextAdopted?.(context.messages);\n\t\t\t}\n\t\t\tthrowIfAborted(signal);\n\t\t\tlet messages = projection ? projection.messages.slice() : context.messages;\n\t\t\tif (config.transformContext) {\n\t\t\t\tmessages = await maybePromiseWithAbort(config.transformContext(messages, signal), signal);\n\t\t\t}\n\n\t\t\tconst llmMessages = await maybePromiseWithAbort(config.convertToLlm(messages), signal);\n\n\t\t\tconst streamFunction = streamFn || streamSimple;\n\n\t\t\tconst resolvedApiKey =\n\t\t\t\t(config.getApiKey\n\t\t\t\t\t? await maybePromiseWithAbort(config.getApiKey(config.model.provider), signal)\n\t\t\t\t\t: undefined) || config.apiKey;\n\n\t\t\tconst llmContext: Context = {\n\t\t\t\tsystemPrompt: config.getSystemPrompt?.() ?? context.systemPrompt,\n\t\t\t\tmessages: llmMessages,\n\t\t\t\ttools: context.tools,\n\t\t\t};\n\n\t\t\tconst {\n\t\t\t\tbeforeContextBuild: _beforeContextBuild,\n\t\t\t\tonContextAdopted: _onContextAdopted,\n\t\t\t\trecoverRequestPreparation: _recoverRequestPreparation,\n\t\t\t\trecoverProviderFailure: _recoverProviderFailure,\n\t\t\t\toutputPolicy: _outputPolicy,\n\t\t\t\townedStreamFn,\n\t\t\t\t...streamOptions\n\t\t\t} = config;\n\t\t\tconst options = { ...streamOptions, apiKey: resolvedApiKey, signal };\n\t\t\tconst response = await maybePromiseWithAbort(\n\t\t\t\townedStreamFn\n\t\t\t\t\t? ownedStreamFn(config.model, llmContext, options, projection ? projection.streamContext : undefined)\n\t\t\t\t\t: streamFunction(config.model, llmContext, options),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tconst iterator = response[Symbol.asyncIterator]();\n\t\t\tconst closeIterator = () => {\n\t\t\t\tvoid Promise.resolve(iterator.return?.()).catch(() => undefined);\n\t\t\t};\n\t\t\twhile (true) {\n\t\t\t\tconst next = await raceWithAbort<IteratorResult<AssistantMessageEvent>>(\n\t\t\t\t\titerator.next(),\n\t\t\t\t\tsignal,\n\t\t\t\t\tcloseIterator,\n\t\t\t\t);\n\t\t\t\tif (next.done) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tconst event = next.value;\n\t\t\t\tswitch (event.type) {\n\t\t\t\t\tcase \"start\":\n\t\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\t\tcontext.messages.push(partialMessage);\n\t\t\t\t\t\taddedPartial = true;\n\t\t\t\t\t\tawait emit({ type: \"message_start\", message: { ...partialMessage } });\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"text_start\":\n\t\t\t\t\tcase \"text_delta\":\n\t\t\t\t\tcase \"text_end\":\n\t\t\t\t\tcase \"thinking_start\":\n\t\t\t\t\tcase \"thinking_delta\":\n\t\t\t\t\tcase \"thinking_end\":\n\t\t\t\t\tcase \"toolcall_start\":\n\t\t\t\t\tcase \"toolcall_delta\":\n\t\t\t\t\tcase \"toolcall_end\":\n\t\t\t\t\t\tif (partialMessage) {\n\t\t\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\t\t\tcontext.messages[context.messages.length - 1] = partialMessage;\n\t\t\t\t\t\t\tawait emit({\n\t\t\t\t\t\t\t\ttype: \"message_update\",\n\t\t\t\t\t\t\t\tassistantMessageEvent: event,\n\t\t\t\t\t\t\t\tmessage: { ...partialMessage },\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"done\":\n\t\t\t\t\tcase \"error\": {\n\t\t\t\t\t\tlet finalMessage = getTerminalMessage(event);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tfinalMessage = await maybePromiseWithAbort(response.result(), signal);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tif (!signal?.aborted || !isAbortError(error)) {\n\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (addedPartial) {\n\t\t\t\t\t\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcontext.messages.push(finalMessage);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!addedPartial) {\n\t\t\t\t\t\t\tawait emit({ type: \"message_start\", message: { ...finalMessage } });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tawait emit({ type: \"message_end\", message: finalMessage });\n\t\t\t\t\t\treturn finalMessage;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst finalMessage = await maybePromiseWithAbort(response.result(), signal);\n\t\t\tif (addedPartial) {\n\t\t\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t\t\t} else {\n\t\t\t\tcontext.messages.push(finalMessage);\n\t\t\t\tawait emit({ type: \"message_start\", message: { ...finalMessage } });\n\t\t\t}\n\t\t\tawait emit({ type: \"message_end\", message: finalMessage });\n\t\t\treturn finalMessage;\n\t\t} catch (error) {\n\t\t\tif (signal?.aborted && isAbortError(error)) {\n\t\t\t\treturn await finishAbortedMessage();\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t};\n\n\tlet outcome: { message: AssistantMessage } | { error: unknown };\n\ttry {\n\t\toutcome = { message: await runResponse() };\n\t} catch (error) {\n\t\toutcome = { error };\n\t}\n\ttry {\n\t\tif (build.projection) await build.projection.release?.();\n\t} catch (error) {\n\t\tif (\"error\" in outcome) {\n\t\t\tthrow new AggregateError(\n\t\t\t\t[outcome.error, error],\n\t\t\t\t`Agent inference and context cleanup failed: ${String(outcome.error)}`,\n\t\t\t);\n\t\t}\n\t\tthrow error;\n\t}\n\tif (\"error\" in outcome) {\n\t\tif (\n\t\t\tallowRecovery &&\n\t\t\t!addedPartial &&\n\t\t\tisLocalRequestPreparationError(outcome.error) &&\n\t\t\tconfig.recoverRequestPreparation\n\t\t) {\n\t\t\tlet recovered: boolean | \"reprepare\";\n\t\t\ttry {\n\t\t\t\trecovered = await config.recoverRequestPreparation(outcome.error, signal);\n\t\t\t} catch (error) {\n\t\t\t\t// Preserve the real owner error, including a post-ACK compaction failure.\n\t\t\t\tmarkLocalRequestPreparationError(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (recovered === \"reprepare\" && allowReprepare) {\n\t\t\t\t// A bounded deterministic change (for example, rebasing a TaskFrame) must\n\t\t\t\t// not consume the one recovery available if the new request still cannot fit.\n\t\t\t\treturn streamAssistantResponse(context, config, signal, emit, streamFn, true, false);\n\t\t\t}\n\t\t\tif (recovered === true) {\n\t\t\t\t// Keep this invocation's output collector, completed tools and emitted messages.\n\t\t\t\treturn streamAssistantResponse(context, config, signal, emit, streamFn, false, false);\n\t\t\t}\n\t\t}\n\t\tthrow outcome.error;\n\t}\n\treturn outcome.message;\n}\n\nasync function executeToolCalls(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\toutput?: InvocationOutput,\n): Promise<ExecutedToolCallBatch> {\n\tconst toolCalls = assistantMessage.content\n\t\t.filter((c) => c.type === \"toolCall\")\n\t\t.map((toolCall, sourceOrder) => ({\n\t\t\ttoolCall,\n\t\t\tsourceOrder,\n\t\t\texecutionId: crypto.randomUUID(),\n\t\t\tassistantMessage,\n\t\t\toriginalInput: structuredClone(toolCall.arguments),\n\t\t}));\n\tconst hasSequentialToolCall = toolCalls.some(\n\t\t({ toolCall }) => currentContext.tools?.find((t) => t.name === toolCall.name)?.executionMode === \"sequential\",\n\t);\n\tif (config.toolExecution === \"sequential\" || hasSequentialToolCall) {\n\t\treturn executeToolCallsSequential(currentContext, assistantMessage, toolCalls, config, signal, emit, output);\n\t}\n\treturn executeToolCallsParallel(currentContext, assistantMessage, toolCalls, config, signal, emit);\n}\n\ntype ToolCallSource = {\n\towner?: BoundToolExecution;\n\texecutionId: string;\n\tassistantMessage: AssistantMessage;\n\ttoolCall: AgentToolCall;\n\tsourceOrder: number;\n\toriginalInput: unknown;\n};\n\ntype ExecutedToolCallBatch = {\n\tmessages: ToolResultMessage[];\n\texchanges: FinalizedToolExchange[];\n\ttoolExecution: ToolExecutionMode;\n\tterminate: boolean;\n};\n\nasync function executeToolCallsSequential(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: ToolCallSource[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\toutput?: InvocationOutput,\n): Promise<ExecutedToolCallBatch> {\n\tconst finalizedCalls: FinalizedToolCallOutcome[] = [];\n\tconst messages: ToolResultMessage[] = [];\n\tconst exchanges: FinalizedToolExchange[] = [];\n\n\tfor (const source of toolCalls) {\n\t\tconst { toolCall } = source;\n\t\tif (signal?.aborted) {\n\t\t\tbreak;\n\t\t}\n\n\t\tawait emit({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\targs: toolCall.arguments,\n\t\t});\n\n\t\tconst preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);\n\t\tlet finalized: FinalizedToolCallOutcome;\n\t\tif (preparation.kind === \"immediate\") {\n\t\t\tfinalized = {\n\t\t\t\ttoolCall,\n\t\t\t\tresult: preparation.result,\n\t\t\t\tisError: preparation.isError,\n\t\t\t\texecutionOutcome: \"not_started\",\n\t\t\t};\n\t\t} else {\n\t\t\tconst executed = await executePreparedToolCall(preparation, source, \"sequential\", config, signal, emit);\n\t\t\tfinalized = await finalizeExecutedToolCall(\n\t\t\t\tcurrentContext,\n\t\t\t\tassistantMessage,\n\t\t\t\tpreparation,\n\t\t\t\texecuted,\n\t\t\t\tconfig,\n\t\t\t\tsignal,\n\t\t\t);\n\t\t}\n\n\t\tconst published = await publishToolExchange(finalized, source, \"sequential\", config, signal, emit);\n\t\tawait emitToolResultMessage(published.exchange.result, emit);\n\t\tfinalizedCalls.push(finalized);\n\t\tmessages.push(published.exchange.result);\n\t\texchanges.push(published.exchange);\n\n\t\tif (signal?.aborted || output?.refusal) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn {\n\t\tmessages,\n\t\texchanges,\n\t\ttoolExecution: \"sequential\",\n\t\tterminate: shouldTerminateToolBatch(finalizedCalls),\n\t};\n}\n\nasync function executeToolCallsParallel(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: ToolCallSource[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallBatch> {\n\tconst finalizedCalls: FinalizedToolCallEntry[] = [];\n\n\tfor (const source of toolCalls) {\n\t\tconst { toolCall } = source;\n\t\tawait emit({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\targs: toolCall.arguments,\n\t\t});\n\n\t\tconst preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);\n\t\tif (preparation.kind === \"immediate\") {\n\t\t\tconst finalized = {\n\t\t\t\ttoolCall,\n\t\t\t\tresult: preparation.result,\n\t\t\t\tisError: preparation.isError,\n\t\t\t\texecutionOutcome: \"not_started\",\n\t\t\t} satisfies FinalizedToolCallOutcome;\n\t\t\tfinalizedCalls.push(await publishToolExchange(finalized, source, \"parallel\", config, signal, emit));\n\t\t\tcontinue;\n\t\t}\n\n\t\tfinalizedCalls.push(async () => {\n\t\t\tconst executed = await executePreparedToolCall(preparation, source, \"parallel\", config, signal, emit);\n\t\t\tconst finalized = await finalizeExecutedToolCall(\n\t\t\t\tcurrentContext,\n\t\t\t\tassistantMessage,\n\t\t\t\tpreparation,\n\t\t\t\texecuted,\n\t\t\t\tconfig,\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\treturn publishToolExchange(finalized, source, \"parallel\", config, signal, emit);\n\t\t});\n\t}\n\n\t// An owner/publication failure must not abandon other invocations already started.\n\tconst settledCalls = await Promise.allSettled(\n\t\tfinalizedCalls.map((entry) => (typeof entry === \"function\" ? entry() : Promise.resolve(entry))),\n\t);\n\tconst orderedFinalizedCalls = settledCalls.flatMap((settled) =>\n\t\tsettled.status === \"fulfilled\" ? [settled.value] : [],\n\t);\n\tconst failure = settledCalls.find((settled) => settled.status === \"rejected\");\n\tconst messages: ToolResultMessage[] = [];\n\tfor (const finalized of orderedFinalizedCalls) {\n\t\tconst toolResultMessage = finalized.exchange.result;\n\t\tawait emitToolResultMessage(toolResultMessage, emit);\n\t\tmessages.push(toolResultMessage);\n\t}\n\n\tif (failure?.status === \"rejected\") throw failure.reason;\n\treturn {\n\t\tmessages,\n\t\texchanges: orderedFinalizedCalls.map((finalized) => finalized.exchange),\n\t\ttoolExecution: \"parallel\",\n\t\tterminate: shouldTerminateToolBatch(orderedFinalizedCalls),\n\t};\n}\n\ntype PreparedToolCall = {\n\tkind: \"prepared\";\n\ttoolCall: AgentToolCall;\n\ttool: AgentTool<any>;\n\targs: unknown;\n};\n\ntype ImmediateToolCallOutcome = {\n\tkind: \"immediate\";\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n};\n\ntype ExecutedToolCallOutcome = {\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n\texecutedInput?: unknown;\n\texecutionOutcome: ToolExecutionOutcome;\n};\n\ntype FinalizedToolCallOutcome = ExecutedToolCallOutcome & {\n\ttoolCall: AgentToolCall;\n};\n\ntype PublishedToolCallOutcome = FinalizedToolCallOutcome & { exchange: FinalizedToolExchange };\n\ntype FinalizedToolCallEntry = PublishedToolCallOutcome | (() => Promise<PublishedToolCallOutcome>);\n\nfunction shouldTerminateToolBatch(finalizedCalls: FinalizedToolCallOutcome[]): boolean {\n\treturn finalizedCalls.length > 0 && finalizedCalls.every((finalized) => finalized.result.terminate === true);\n}\n\nfunction prepareToolCallArguments(tool: AgentTool<any>, toolCall: AgentToolCall): AgentToolCall {\n\tif (!tool.prepareArguments) {\n\t\treturn toolCall;\n\t}\n\tconst preparedArguments = tool.prepareArguments(toolCall.arguments);\n\tif (preparedArguments === toolCall.arguments) {\n\t\treturn toolCall;\n\t}\n\treturn {\n\t\t...toolCall,\n\t\targuments: preparedArguments as Record<string, any>,\n\t};\n}\n\nasync function prepareToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCall: AgentToolCall,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<PreparedToolCall | ImmediateToolCallOutcome> {\n\tconst tool = currentContext.tools?.find((t) => t.name === toolCall.name);\n\tif (!tool) {\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(`Tool ${toolCall.name} not found`),\n\t\t\tisError: true,\n\t\t};\n\t}\n\n\ttry {\n\t\tconst preparedToolCall = prepareToolCallArguments(tool, toolCall);\n\t\tconst validatedArgs = validateToolArguments(tool, preparedToolCall);\n\t\tif (config.beforeToolCall) {\n\t\t\tconst beforeResult = await maybePromiseWithAbort(\n\t\t\t\tconfig.beforeToolCall(\n\t\t\t\t\t{\n\t\t\t\t\t\tassistantMessage,\n\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\targs: validatedArgs,\n\t\t\t\t\t\tcontext: currentContext,\n\t\t\t\t\t},\n\t\t\t\t\tsignal,\n\t\t\t\t),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (beforeResult?.block) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"immediate\",\n\t\t\t\t\tresult: createErrorToolResult(beforeResult.reason || \"Tool execution was blocked\"),\n\t\t\t\t\tisError: true,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tkind: \"prepared\",\n\t\t\ttoolCall,\n\t\t\ttool,\n\t\t\targs: validatedArgs,\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(error instanceof Error ? error.message : String(error)),\n\t\t\tisError: true,\n\t\t};\n\t}\n}\n\nasync function executePreparedToolCall(\n\tprepared: PreparedToolCall,\n\tsource: ToolCallSource,\n\ttoolExecution: ToolExecutionMode,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallOutcome> {\n\tconst invocationArgs = structuredClone(prepared.args);\n\tconst executedInput = structuredClone(invocationArgs);\n\tconst execute = prepared.tool.execute;\n\tif (!signal?.aborted) {\n\t\t// Admission failures must not become synthetic tool results or fall through to effects.\n\t\tconst owner = await config.onToolInvocationStarting?.(\n\t\t\t{\n\t\t\t\texecutionId: source.executionId,\n\t\t\t\tsourceOrder: source.sourceOrder,\n\t\t\t\ttoolCallId: prepared.toolCall.id,\n\t\t\t\ttoolName: prepared.toolCall.name,\n\t\t\t\toriginalInput: source.originalInput,\n\t\t\t\texecutedInput,\n\t\t\t\ttoolExecution,\n\t\t\t},\n\t\t\tsignal,\n\t\t\tprepared.tool,\n\t\t\texecute,\n\t\t\tsource.assistantMessage,\n\t\t);\n\t\tif (owner) source.owner = owner;\n\t}\n\tlet acceptingUpdates = true;\n\tlet pendingUpdates = 0;\n\tlet finishUpdates!: () => void;\n\tlet failUpdates!: (error: unknown) => void;\n\tconst updateEvents = new Promise<void>((resolve, reject) => {\n\t\tfinishUpdates = resolve;\n\t\tfailUpdates = reject;\n\t});\n\t// Observe early failures now; the normal execution path still awaits and reports them.\n\tvoid updateEvents.catch(() => undefined);\n\tconst settleUpdate = () => {\n\t\tpendingUpdates--;\n\t\tif (!acceptingUpdates && pendingUpdates === 0) finishUpdates();\n\t};\n\tconst stopUpdates = () => {\n\t\tacceptingUpdates = false;\n\t\tif (pendingUpdates === 0) finishUpdates();\n\t};\n\tlet executionStarted = false;\n\n\ttry {\n\t\tthrowIfAborted(signal);\n\t\texecutionStarted = true;\n\t\tconst run = () =>\n\t\t\texecute.call(prepared.tool, prepared.toolCall.id, invocationArgs as never, signal, (partialResult) => {\n\t\t\t\tif (!acceptingUpdates || signal?.aborted) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst update = Promise.resolve(\n\t\t\t\t\temit({\n\t\t\t\t\t\ttype: \"tool_execution_update\",\n\t\t\t\t\t\ttoolCallId: prepared.toolCall.id,\n\t\t\t\t\t\ttoolName: prepared.toolCall.name,\n\t\t\t\t\t\targs: prepared.toolCall.arguments,\n\t\t\t\t\t\tpartialResult,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\t// Do not retain every stdout callback or feed an unbounded array to Promise.all.\n\t\t\t\tpendingUpdates++;\n\t\t\t\tvoid update.then(settleUpdate, (error) => {\n\t\t\t\t\tfailUpdates(error);\n\t\t\t\t\tsettleUpdate();\n\t\t\t\t});\n\t\t\t});\n\t\tconst result = await raceWithAbort(source.owner ? source.owner.run(run) : run(), signal);\n\t\tstopUpdates();\n\t\ttry {\n\t\t\tawait raceWithAbort(updateEvents, signal);\n\t\t} catch (error) {\n\t\t\tif (!signal?.aborted || !isAbortError(error)) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\treturn { result, isError: result.isError ?? false, executedInput, executionOutcome: \"completed\" };\n\t} catch (error) {\n\t\tstopUpdates();\n\t\tawait raceWithAbort(updateEvents, signal).catch(() => undefined);\n\t\treturn {\n\t\t\tresult: createErrorToolResult(\n\t\t\t\tsignal?.aborted ? \"Tool execution aborted\" : error instanceof Error ? error.message : String(error),\n\t\t\t),\n\t\t\tisError: true,\n\t\t\t...(executionStarted ? { executedInput } : {}),\n\t\t\texecutionOutcome: !executionStarted ? \"not_started\" : signal?.aborted ? \"outcome_unknown\" : \"failed\",\n\t\t};\n\t}\n}\n\nasync function finalizeExecutedToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tprepared: PreparedToolCall,\n\texecuted: ExecutedToolCallOutcome,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<FinalizedToolCallOutcome> {\n\tlet result = executed.result;\n\tlet isError = executed.isError;\n\n\tif (config.afterToolCall) {\n\t\ttry {\n\t\t\tconst afterResult = await maybePromiseWithAbort(\n\t\t\t\tconfig.afterToolCall(\n\t\t\t\t\t{\n\t\t\t\t\t\tassistantMessage,\n\t\t\t\t\t\ttoolCall: prepared.toolCall,\n\t\t\t\t\t\targs: prepared.args,\n\t\t\t\t\t\tresult,\n\t\t\t\t\t\tisError,\n\t\t\t\t\t\tcontext: currentContext,\n\t\t\t\t\t},\n\t\t\t\t\tsignal,\n\t\t\t\t),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (afterResult) {\n\t\t\t\tresult = {\n\t\t\t\t\tcontent: afterResult.content ?? result.content,\n\t\t\t\t\tdetails: afterResult.details ?? result.details,\n\t\t\t\t\tterminate: afterResult.terminate ?? result.terminate,\n\t\t\t\t};\n\t\t\t\tisError = afterResult.isError ?? isError;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tresult = createErrorToolResult(error instanceof Error ? error.message : String(error));\n\t\t\tisError = true;\n\t\t}\n\t}\n\n\treturn {\n\t\t...executed,\n\t\ttoolCall: prepared.toolCall,\n\t\tresult,\n\t\tisError,\n\t};\n}\n\nfunction createErrorToolResult(message: string): AgentToolResult<any> {\n\treturn {\n\t\tcontent: [{ type: \"text\", text: message }],\n\t\tdetails: {},\n\t};\n}\n\nasync function publishToolExchange(\n\tfinalized: FinalizedToolCallOutcome,\n\tsource: ToolCallSource,\n\ttoolExecution: ToolExecutionMode,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<PublishedToolCallOutcome> {\n\tconst exchange: FinalizedToolExchange = {\n\t\texecutionId: source.executionId,\n\t\tsourceOrder: source.sourceOrder,\n\t\ttoolCallId: finalized.toolCall.id,\n\t\ttoolName: finalized.toolCall.name,\n\t\toriginalInput: source.originalInput,\n\t\t...(finalized.executionOutcome === \"not_started\" ? {} : { executedInput: finalized.executedInput }),\n\t\ttoolExecution,\n\t\texecutionOutcome: finalized.executionOutcome,\n\t\tcancellationRequested: signal?.aborted ?? false,\n\t\tresult: createToolResultMessage(finalized),\n\t};\n\tawait config.onToolExchangeFinalized?.(exchange, signal, source.owner);\n\tawait emit({\n\t\ttype: \"tool_execution_end\",\n\t\ttoolCallId: finalized.toolCall.id,\n\t\ttoolName: finalized.toolCall.name,\n\t\tresult: finalized.result,\n\t\tisError: finalized.isError,\n\t\texchange,\n\t});\n\treturn { ...finalized, exchange };\n}\n\nfunction createToolResultMessage(finalized: FinalizedToolCallOutcome): ToolResultMessage {\n\treturn {\n\t\trole: \"toolResult\",\n\t\ttoolCallId: finalized.toolCall.id,\n\t\ttoolName: finalized.toolCall.name,\n\t\tcontent: finalized.result.content,\n\t\tdetails: finalized.result.details,\n\t\tisError: finalized.isError,\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nasync function emitToolResultMessage(toolResultMessage: ToolResultMessage, emit: AgentEventSink): Promise<void> {\n\tawait emit({ type: \"message_start\", message: toolResultMessage });\n\tawait emit({ type: \"message_end\", message: toolResultMessage });\n}\n"]}
@@ -830,7 +830,7 @@ async function executePreparedToolCall(prepared, source, toolExecution, config,
830
830
  throw error;
831
831
  }
832
832
  }
833
- return { result, isError: false, executedInput, executionOutcome: "completed" };
833
+ return { result, isError: result.isError ?? false, executedInput, executionOutcome: "completed" };
834
834
  }
835
835
  catch (error) {
836
836
  stopUpdates();
@@ -1 +1 @@
1
- {"version":3,"file":"agent-loop.js","sourceRoot":"","sources":["../src/agent-loop.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAIN,WAAW,EACX,8BAA8B,EAC9B,gCAAgC,E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AAC,uBAAuB,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC;IACvE,MAAM,IAAI,CAAC;QACV,IAAI,EAAE,oBAAoB;QAC1B,UAAU,EAAE,SAAS,CAAC,QAAQ,CAAC,EAAE;QACjC,QAAQ,EAAE,SAAS,CAAC,QAAQ,CAAC,IAAI;QACjC,MAAM,EAAE,SAAS,CAAC,MAAM;QACxB,OAAO,EAAE,SAAS,CAAC,OAAO;QAC1B,QAAQ;KACR,CAAC,CAAC;IACH,OAAO,EAAE,GAAG,SAAS,EAAE,QAAQ,EAAE,CAAC;AAAA,CAClC;AAED,SAAS,uBAAuB,CAAC,SAAmC,EAAqB;IACxF,OAAO;QACN,IAAI,EAAE,YAAY;QAClB,UAAU,EAAE,SAAS,CAAC,QAAQ,CAAC,EAAE;QACjC,QAAQ,EAAE,SAAS,CAAC,QAAQ,CAAC,IAAI;QACjC,OAAO,EAAE,SAAS,CAAC,MAAM,CAAC,OAAO;QACjC,OAAO,EAAE,SAAS,CAAC,MAAM,CAAC,OAAO;QACjC,OAAO,EAAE,SAAS,CAAC,OAAO;QAC1B,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;KACrB,CAAC;AAAA,CACF;AAED,KAAK,UAAU,qBAAqB,CAAC,iBAAoC,EAAE,IAAoB,EAAiB;IAC/G,MAAM,IAAI,CAAC,EAAE,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC;IAClE,MAAM,IAAI,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC;AAAA,CAChE","sourcesContent":["/**\n * Agent loop that works with AgentMessage throughout.\n * Transforms to Message[] only at the LLM call boundary.\n */\n\nimport {\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\ttype Context,\n\tEventStream,\n\tisLocalRequestPreparationError,\n\tmarkLocalRequestPreparationError,\n\tstreamSimple,\n\ttype ToolResultMessage,\n\tvalidateToolArguments,\n} from \"@ponythewhite/base-context-ai\";\nimport { AgentOutputLimitError, InvocationOutput } from \"./invocation-output.js\";\nimport type {\n\tAgentContext,\n\tAgentContextBuildResult,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentTool,\n\tAgentToolCall,\n\tAgentToolResult,\n\tBoundToolExecution,\n\tFinalizedToolExchange,\n\tStreamFn,\n\tToolExecutionMode,\n\tToolExecutionOutcome,\n} from \"./types.js\";\n\nexport type AgentEventSink = (event: AgentEvent) => Promise<void> | void;\n\nconst ABORT_ERROR_MESSAGE = \"Request was aborted\";\nconst EMPTY_USAGE: AssistantMessage[\"usage\"] = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nfunction createAbortError(): Error {\n\treturn new Error(ABORT_ERROR_MESSAGE);\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n\tif (signal?.aborted) {\n\t\tthrow createAbortError();\n\t}\n}\n\nfunction raceWithAbort<T>(operation: Promise<T>, signal: AbortSignal | undefined, onAbort?: () => void): Promise<T> {\n\tif (!signal) {\n\t\treturn operation;\n\t}\n\tif (signal.aborted) {\n\t\tonAbort?.();\n\t\tvoid operation.catch(() => undefined);\n\t\treturn Promise.reject(createAbortError());\n\t}\n\n\treturn new Promise<T>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst cleanup = () => {\n\t\t\tsignal.removeEventListener(\"abort\", abort);\n\t\t};\n\t\tconst abort = () => {\n\t\t\tif (settled) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tonAbort?.();\n\t\t\treject(createAbortError());\n\t\t};\n\t\tsignal.addEventListener(\"abort\", abort, { once: true });\n\t\toperation.then(\n\t\t\t(value) => {\n\t\t\t\tif (settled) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettled = true;\n\t\t\t\tcleanup();\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\tif (settled) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettled = true;\n\t\t\t\tcleanup();\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\nfunction maybePromiseWithAbort<T>(\n\toperation: T | Promise<T>,\n\tsignal: AbortSignal | undefined,\n\tonAbort?: () => void,\n): Promise<T> {\n\treturn raceWithAbort(Promise.resolve(operation), signal, onAbort);\n}\n\nfunction isAbortError(error: unknown): boolean {\n\treturn error instanceof Error && (error.message === ABORT_ERROR_MESSAGE || error.name === \"AbortError\");\n}\n\ntype PostTurnResult<T> = { status: \"completed\"; value: T } | { status: \"aborted\" };\n\nasync function settlePostTurn<T>(operation: Promise<T>, signal: AbortSignal | undefined): Promise<PostTurnResult<T>> {\n\ttry {\n\t\treturn { status: \"completed\", value: await operation };\n\t} catch (error) {\n\t\tif (signal?.aborted && isAbortError(error)) {\n\t\t\treturn { status: \"aborted\" };\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nfunction cloneAssistantContent(content: AssistantMessage[\"content\"]): AssistantMessage[\"content\"] {\n\treturn content.map((part) => {\n\t\tif (part.type === \"toolCall\") {\n\t\t\treturn { ...part, arguments: { ...part.arguments } };\n\t\t}\n\t\treturn { ...part };\n\t});\n}\n\nfunction cloneUsage(usage: AssistantMessage[\"usage\"]): AssistantMessage[\"usage\"] {\n\treturn { ...usage, cost: { ...usage.cost } };\n}\n\nfunction createAbortedAssistantMessage(\n\tconfig: AgentLoopConfig,\n\tpartialMessage: AssistantMessage | null,\n): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: partialMessage ? cloneAssistantContent(partialMessage.content) : [{ type: \"text\", text: \"\" }],\n\t\tapi: partialMessage?.api ?? config.model.api,\n\t\tprovider: partialMessage?.provider ?? config.model.provider,\n\t\tmodel: partialMessage?.model ?? config.model.id,\n\t\tusage: cloneUsage(partialMessage?.usage ?? EMPTY_USAGE),\n\t\tstopReason: \"aborted\",\n\t\terrorMessage: ABORT_ERROR_MESSAGE,\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction getTerminalMessage(event: Extract<AssistantMessageEvent, { type: \"done\" | \"error\" }>): AssistantMessage {\n\treturn event.type === \"done\" ? event.message : event.error;\n}\n\nfunction endAgentStreamOnError(\n\tstream: EventStream<AgentEvent, AgentMessage[]>,\n\tpromise: Promise<AgentMessage[]>,\n): void {\n\tvoid promise.then(\n\t\t(messages) => {\n\t\t\tstream.end(messages);\n\t\t},\n\t\t(error) => {\n\t\t\tif (error instanceof AgentOutputLimitError) stream.fail(error);\n\t\t\telse stream.end([]);\n\t\t},\n\t);\n}\n\nasync function pollMessagesUnlessAborted(\n\tpoll: (() => AgentMessage[] | Promise<AgentMessage[]>) | undefined,\n\tsignal: AbortSignal | undefined,\n): Promise<AgentMessage[]> {\n\tif (!poll || signal?.aborted) {\n\t\treturn [];\n\t}\n\treturn (await maybePromiseWithAbort(poll(), signal)) || [];\n}\n\n/**\n * Start an agent loop with a new prompt message.\n * The prompt is added to the context and events are emitted for it.\n */\nexport function agentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tconst stream = createAgentStream();\n\n\tendAgentStreamOnError(\n\t\tstream,\n\t\trunAgentLoop(\n\t\t\tprompts,\n\t\t\tcontext,\n\t\t\tconfig,\n\t\t\tasync (event) => {\n\t\t\t\tstream.push(event);\n\t\t\t},\n\t\t\tsignal,\n\t\t\tstreamFn,\n\t\t),\n\t);\n\n\treturn stream;\n}\n\n/**\n * Continue an agent loop from the current context without adding a new message.\n * Used for retries - context already has user message or tool results.\n *\n * **Important:** The last message in context must convert to a `user` or `toolResult` message\n * via `convertToLlm`. If it doesn't, the LLM provider will reject the request.\n * This cannot be validated here since `convertToLlm` is only called once per turn.\n */\nexport function agentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\tif (context.messages[context.messages.length - 1].role === \"assistant\") {\n\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t}\n\n\tconst stream = createAgentStream();\n\n\tendAgentStreamOnError(\n\t\tstream,\n\t\trunAgentLoopContinue(\n\t\t\tcontext,\n\t\t\tconfig,\n\t\t\tasync (event) => {\n\t\t\t\tstream.push(event);\n\t\t\t},\n\t\t\tsignal,\n\t\t\tstreamFn,\n\t\t),\n\t);\n\n\treturn stream;\n}\n\nasync function withInvocationOutput(\n\tmessages: AgentMessage[],\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\trun: (emit: AgentEventSink, output: InvocationOutput | undefined) => Promise<void>,\n): Promise<AgentMessage[]> {\n\tconst output = config.outputPolicy ? new InvocationOutput(config.outputPolicy, messages) : undefined;\n\tlet releaseUpdates = output ? output.policy.bindUpdates?.(output.refresh.bind(output)) : undefined;\n\tconst stopUpdates = () => {\n\t\tconst release = releaseUpdates;\n\t\treleaseUpdates = undefined;\n\t\trelease?.();\n\t};\n\tlet updateSettlement: Promise<void> | undefined;\n\tconst settleUpdates = () => {\n\t\tif (!updateSettlement) {\n\t\t\ttry {\n\t\t\t\tupdateSettlement = output?.policy.settleUpdates?.() ?? Promise.resolve();\n\t\t\t} catch (error) {\n\t\t\t\tupdateSettlement = Promise.reject(error);\n\t\t\t}\n\t\t}\n\t\treturn updateSettlement;\n\t};\n\tconst ownedEmit: AgentEventSink = output\n\t\t? async (event) => {\n\t\t\t\tif (event.type === \"agent_end\") {\n\t\t\t\t\tawait settleUpdates();\n\t\t\t\t\toutput.throwIfRefused();\n\t\t\t\t\tconst finalizedMessages = output.copy();\n\t\t\t\t\tstopUpdates();\n\t\t\t\t\tawait emit({ type: \"agent_end\", messages: finalizedMessages });\n\t\t\t\t} else {\n\t\t\t\t\tawait emit(event);\n\t\t\t\t\t// The native sink joins this message's replacement/persistence job. Keep its original subject.\n\t\t\t\t\tif (event.type === \"message_end\") output.capture(event.message);\n\t\t\t\t}\n\t\t\t}\n\t\t: emit;\n\ttry {\n\t\tawait run(ownedEmit, output);\n\t\treturn messages;\n\t} catch (error) {\n\t\tif (!output) throw error;\n\t\tlet failure = error;\n\t\ttry {\n\t\t\tawait settleUpdates();\n\t\t} catch (settlementError) {\n\t\t\tif (settlementError !== failure)\n\t\t\t\tfailure = new AggregateError(\n\t\t\t\t\t[failure, settlementError],\n\t\t\t\t\t\"Invocation and accepted update settlement failed\",\n\t\t\t\t\t{ cause: failure },\n\t\t\t\t);\n\t\t}\n\t\tif (!output.refusal) throw failure;\n\t\tlet cause: unknown = failure instanceof AgentOutputLimitError ? failure.cause : failure;\n\t\tstopUpdates();\n\t\ttry {\n\t\t\tawait emit({ type: \"agent_end\", refusal: { ...output.refusal } });\n\t\t} catch (notificationError) {\n\t\t\tcause =\n\t\t\t\tcause === undefined\n\t\t\t\t\t? notificationError\n\t\t\t\t\t: new AggregateError([cause, notificationError], \"Output refusal and terminal notification failed\");\n\t\t}\n\t\tthrow new AgentOutputLimitError({ ...output.refusal }, cause === undefined ? undefined : { cause });\n\t} finally {\n\t\ttry {\n\t\t\tstopUpdates();\n\t\t} finally {\n\t\t\toutput?.dispose();\n\t\t}\n\t}\n}\n\nexport async function runAgentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): Promise<AgentMessage[]> {\n\tconst newMessages: AgentMessage[] = config.outputPolicy ? [] : [...prompts];\n\treturn withInvocationOutput(newMessages, config, emit, async (ownedEmit, output) => {\n\t\tif (output) {\n\t\t\toutput.checkRoom(prompts.length);\n\t\t\tprompts = [...prompts];\n\t\t}\n\t\t// Keep only the working wrapper across awaits, not the initial snapshot.\n\t\tcontext = { ...context, messages: [...context.messages, ...prompts] };\n\t\tawait ownedEmit({ type: \"agent_start\" });\n\t\tawait ownedEmit({ type: \"turn_start\" });\n\t\tfor (const prompt of prompts) {\n\t\t\tawait ownedEmit({ type: \"message_start\", message: prompt });\n\t\t\tawait ownedEmit({ type: \"message_end\", message: prompt });\n\t\t\toutput?.throwIfRefused();\n\t\t}\n\t\tawait runLoop(context, newMessages, config, signal, ownedEmit, streamFn, output);\n\t});\n}\n\nexport async function runAgentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): Promise<AgentMessage[]> {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\tif (context.messages[context.messages.length - 1].role === \"assistant\") {\n\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t}\n\n\tconst newMessages: AgentMessage[] = [];\n\treturn withInvocationOutput(newMessages, config, emit, async (ownedEmit, output) => {\n\t\tcontext = { ...context };\n\t\tawait ownedEmit({ type: \"agent_start\" });\n\t\toutput?.throwIfRefused();\n\t\tawait ownedEmit({ type: \"turn_start\" });\n\t\tawait runLoop(context, newMessages, config, signal, ownedEmit, streamFn, output);\n\t});\n}\n\nfunction createAgentStream(): EventStream<AgentEvent, AgentMessage[]> {\n\treturn new EventStream<AgentEvent, AgentMessage[]>(\n\t\t(event: AgentEvent) => event.type === \"agent_end\" && !event.refusal,\n\t\t(event: AgentEvent) => (event.type === \"agent_end\" && !event.refusal ? event.messages : []),\n\t);\n}\n\nasync function runLoop(\n\tcurrentContext: AgentContext,\n\tnewMessages: AgentMessage[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n\toutput?: InvocationOutput,\n): Promise<void> {\n\tlet firstTurn = true;\n\tlet lastTurn: Parameters<NonNullable<AgentLoopConfig[\"getContinuationMessages\"]>>[0] | undefined;\n\tlet pendingMessages: AgentMessage[] = await pollMessagesUnlessAborted(config.getSteeringMessages, signal);\n\n\tconst shouldStopBeforeTurn = (): boolean => !firstTurn && (config.shouldStopBeforeTurn?.() ?? false);\n\n\twhile (true) {\n\t\tthrowIfAborted(signal);\n\t\tlet hasMoreToolCalls = true;\n\n\t\twhile (hasMoreToolCalls || pendingMessages.length > 0) {\n\t\t\tthrowIfAborted(signal);\n\t\t\tif (!firstTurn) {\n\t\t\t\tawait emit({ type: \"turn_start\" });\n\t\t\t} else {\n\t\t\t\tfirstTurn = false;\n\t\t\t}\n\n\t\t\tif (pendingMessages.length > 0) {\n\t\t\t\toutput?.checkRoom(pendingMessages.length);\n\t\t\t\tif (output) pendingMessages = [...pendingMessages];\n\t\t\t\tfor (const message of pendingMessages) {\n\t\t\t\t\tawait emit({ type: \"message_start\", message });\n\t\t\t\t\tawait emit({ type: \"message_end\", message });\n\t\t\t\t\tcurrentContext.messages.push(message);\n\t\t\t\t\tif (!output) newMessages.push(message);\n\t\t\t\t\toutput?.throwIfRefused();\n\t\t\t\t}\n\t\t\t\tpendingMessages = [];\n\t\t\t}\n\n\t\t\toutput?.checkRoom(1);\n\t\t\tconst message = await streamAssistantResponse(currentContext, config, signal, emit, streamFn);\n\t\t\tif (!output) newMessages.push(message);\n\t\t\toutput?.throwIfRefused();\n\n\t\t\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\t\t\tawait emit({\n\t\t\t\t\ttype: \"turn_end\",\n\t\t\t\t\tmessage,\n\t\t\t\t\ttoolResults: [],\n\t\t\t\t\ttoolExecution: config.toolExecution ?? \"parallel\",\n\t\t\t\t\texchanges: [],\n\t\t\t\t});\n\t\t\t\toutput?.refresh(message);\n\t\t\t\tif (\n\t\t\t\t\tmessage.stopReason === \"error\" &&\n\t\t\t\t\tconfig.recoverProviderFailure &&\n\t\t\t\t\t(await maybePromiseWithAbort(config.recoverProviderFailure(message, signal), signal))\n\t\t\t\t) {\n\t\t\t\t\t// Retain and charge the failed output; only omit it from the next request.\n\t\t\t\t\tcurrentContext.messages = currentContext.messages.filter((candidate) => candidate !== message);\n\t\t\t\t\thasMoreToolCalls = true;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst toolCalls = message.content.filter((c) => c.type === \"toolCall\");\n\n\t\t\tconst toolResults: ToolResultMessage[] = [];\n\t\t\tconst exchanges: FinalizedToolExchange[] = [];\n\t\t\tlet toolExecution = config.toolExecution ?? \"parallel\";\n\t\t\thasMoreToolCalls = false;\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\toutput?.checkRoom(toolCalls.length);\n\t\t\t\tconst executedToolBatch = await executeToolCalls(currentContext, message, config, signal, emit, output);\n\t\t\t\ttoolResults.push(...executedToolBatch.messages);\n\t\t\t\texchanges.push(...executedToolBatch.exchanges);\n\t\t\t\ttoolExecution = executedToolBatch.toolExecution;\n\t\t\t\thasMoreToolCalls = !executedToolBatch.terminate;\n\n\t\t\t\tfor (const result of toolResults) {\n\t\t\t\t\tcurrentContext.messages.push(result);\n\t\t\t\t\tif (!output) newMessages.push(result);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\toutput?.throwIfRefused();\n\t\t\tawait emit({ type: \"turn_end\", message, toolResults, toolExecution, exchanges });\n\t\t\toutput?.refresh(message);\n\t\t\tfor (const result of toolResults) output?.refresh(result);\n\t\t\toutput?.throwIfRefused();\n\t\t\tif (signal?.aborted) {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlastTurn = {\n\t\t\t\tmessage,\n\t\t\t\ttoolResults,\n\t\t\t\tcontext: currentContext,\n\t\t\t\tnewMessages,\n\t\t\t};\n\n\t\t\tconst turnContext = { ...lastTurn, newMessages: output?.copy() ?? newMessages };\n\t\t\tconst shouldStopResult = await settlePostTurn(\n\t\t\t\tmaybePromiseWithAbort(\n\t\t\t\t\tconfig.getTurnOutcome\n\t\t\t\t\t\t? config.getTurnOutcome({ ...turnContext, hasMoreToolCalls }, signal)\n\t\t\t\t\t\t: Promise.resolve(config.shouldStopAfterTurn?.(turnContext) ?? false).then((stop) => ({\n\t\t\t\t\t\t\t\tkind: stop ? (\"finish\" as const) : (\"proceed\" as const),\n\t\t\t\t\t\t\t})),\n\t\t\t\t\tsignal,\n\t\t\t\t),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\toutput?.refresh(message);\n\t\t\tfor (const result of toolResults) output?.refresh(result);\n\t\t\toutput?.throwIfRefused();\n\t\t\tif (shouldStopResult.status === \"aborted\") {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (shouldStopResult.value.kind !== \"proceed\" || shouldStopBeforeTurn()) {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst steeringMessagesResult = await settlePostTurn(\n\t\t\t\tpollMessagesUnlessAborted(config.getSteeringMessages, signal),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (steeringMessagesResult.status === \"aborted\") {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpendingMessages = steeringMessagesResult.value;\n\t\t\t// Steering drained by this poll owns the turn boundary; stop only when it was empty.\n\t\t\tif (pendingMessages.length === 0 && shouldStopBeforeTurn()) {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (shouldStopBeforeTurn()) break;\n\t\tconst followUpMessagesResult = await settlePostTurn(\n\t\t\tpollMessagesUnlessAborted(config.getFollowUpMessages, signal),\n\t\t\tsignal,\n\t\t);\n\t\tif (followUpMessagesResult.status === \"aborted\") {\n\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\treturn;\n\t\t}\n\t\tconst followUpMessages = followUpMessagesResult.value;\n\t\tif (followUpMessages.length > 0) {\n\t\t\tpendingMessages = followUpMessages;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (shouldStopBeforeTurn()) break;\n\t\tif (lastTurn && config.getContinuationOutcome) {\n\t\t\tconst outcome = await settlePostTurn(\n\t\t\t\tmaybePromiseWithAbort(\n\t\t\t\t\tconfig.getContinuationOutcome(output ? { ...lastTurn, newMessages: output.copy() } : lastTurn, signal),\n\t\t\t\t\tsignal,\n\t\t\t\t),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (outcome.status === \"completed\" && outcome.value.kind === \"continue\") {\n\t\t\t\tpendingMessages = outcome.value.messages;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tconst continuationMessagesResult = lastTurn\n\t\t\t? await settlePostTurn(\n\t\t\t\t\tmaybePromiseWithAbort(\n\t\t\t\t\t\tconfig.getContinuationMessages?.(\n\t\t\t\t\t\t\toutput ? { ...lastTurn, newMessages: output.copy() } : lastTurn,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t) ?? [],\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t),\n\t\t\t\t\tsignal,\n\t\t\t\t)\n\t\t\t: ({ status: \"completed\", value: [] } satisfies PostTurnResult<AgentMessage[]>);\n\t\tif (continuationMessagesResult.status === \"aborted\") {\n\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\treturn;\n\t\t}\n\t\tconst continuationMessages = continuationMessagesResult.value || [];\n\t\tif (continuationMessages.length > 0) {\n\t\t\tpendingMessages = continuationMessages;\n\t\t\tcontinue;\n\t\t}\n\n\t\tbreak;\n\t}\n\n\tawait emit({ type: \"agent_end\", messages: newMessages });\n}\n\nasync function streamAssistantResponse(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n\tallowRecovery = true,\n\tallowReprepare = true,\n): Promise<AssistantMessage> {\n\tconst build: { projection: AgentContextBuildResult } = { projection: undefined };\n\tlet addedPartial = false;\n\tconst runResponse = async (): Promise<AssistantMessage> => {\n\t\tlet partialMessage: AssistantMessage | null = null;\n\t\tconst finishAbortedMessage = async () => {\n\t\t\tconst finalMessage = createAbortedAssistantMessage(config, partialMessage);\n\t\t\tif (addedPartial) {\n\t\t\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t\t\t} else {\n\t\t\t\tcontext.messages.push(finalMessage);\n\t\t\t\tawait emit({ type: \"message_start\", message: { ...finalMessage } });\n\t\t\t}\n\t\t\tawait emit({ type: \"message_end\", message: finalMessage });\n\t\t\treturn finalMessage;\n\t\t};\n\n\t\ttry {\n\t\t\tthrowIfAborted(signal);\n\t\t\t// Do not race source persistence against cancellation; drain it before leaving this build.\n\t\t\tconst projection = await config.beforeContextBuild?.();\n\t\t\tbuild.projection = projection;\n\t\t\tif (projection && projection.adoptMessages === true) {\n\t\t\t\tcontext.messages = projection.messages.slice();\n\t\t\t\tawait config.onContextAdopted?.(context.messages);\n\t\t\t}\n\t\t\tthrowIfAborted(signal);\n\t\t\tlet messages = projection ? projection.messages.slice() : context.messages;\n\t\t\tif (config.transformContext) {\n\t\t\t\tmessages = await maybePromiseWithAbort(config.transformContext(messages, signal), signal);\n\t\t\t}\n\n\t\t\tconst llmMessages = await maybePromiseWithAbort(config.convertToLlm(messages), signal);\n\n\t\t\tconst streamFunction = streamFn || streamSimple;\n\n\t\t\tconst resolvedApiKey =\n\t\t\t\t(config.getApiKey\n\t\t\t\t\t? await maybePromiseWithAbort(config.getApiKey(config.model.provider), signal)\n\t\t\t\t\t: undefined) || config.apiKey;\n\n\t\t\tconst llmContext: Context = {\n\t\t\t\tsystemPrompt: config.getSystemPrompt?.() ?? context.systemPrompt,\n\t\t\t\tmessages: llmMessages,\n\t\t\t\ttools: context.tools,\n\t\t\t};\n\n\t\t\tconst {\n\t\t\t\tbeforeContextBuild: _beforeContextBuild,\n\t\t\t\tonContextAdopted: _onContextAdopted,\n\t\t\t\trecoverRequestPreparation: _recoverRequestPreparation,\n\t\t\t\trecoverProviderFailure: _recoverProviderFailure,\n\t\t\t\toutputPolicy: _outputPolicy,\n\t\t\t\townedStreamFn,\n\t\t\t\t...streamOptions\n\t\t\t} = config;\n\t\t\tconst options = { ...streamOptions, apiKey: resolvedApiKey, signal };\n\t\t\tconst response = await maybePromiseWithAbort(\n\t\t\t\townedStreamFn\n\t\t\t\t\t? ownedStreamFn(config.model, llmContext, options, projection ? projection.streamContext : undefined)\n\t\t\t\t\t: streamFunction(config.model, llmContext, options),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tconst iterator = response[Symbol.asyncIterator]();\n\t\t\tconst closeIterator = () => {\n\t\t\t\tvoid Promise.resolve(iterator.return?.()).catch(() => undefined);\n\t\t\t};\n\t\t\twhile (true) {\n\t\t\t\tconst next = await raceWithAbort<IteratorResult<AssistantMessageEvent>>(\n\t\t\t\t\titerator.next(),\n\t\t\t\t\tsignal,\n\t\t\t\t\tcloseIterator,\n\t\t\t\t);\n\t\t\t\tif (next.done) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tconst event = next.value;\n\t\t\t\tswitch (event.type) {\n\t\t\t\t\tcase \"start\":\n\t\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\t\tcontext.messages.push(partialMessage);\n\t\t\t\t\t\taddedPartial = true;\n\t\t\t\t\t\tawait emit({ type: \"message_start\", message: { ...partialMessage } });\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"text_start\":\n\t\t\t\t\tcase \"text_delta\":\n\t\t\t\t\tcase \"text_end\":\n\t\t\t\t\tcase \"thinking_start\":\n\t\t\t\t\tcase \"thinking_delta\":\n\t\t\t\t\tcase \"thinking_end\":\n\t\t\t\t\tcase \"toolcall_start\":\n\t\t\t\t\tcase \"toolcall_delta\":\n\t\t\t\t\tcase \"toolcall_end\":\n\t\t\t\t\t\tif (partialMessage) {\n\t\t\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\t\t\tcontext.messages[context.messages.length - 1] = partialMessage;\n\t\t\t\t\t\t\tawait emit({\n\t\t\t\t\t\t\t\ttype: \"message_update\",\n\t\t\t\t\t\t\t\tassistantMessageEvent: event,\n\t\t\t\t\t\t\t\tmessage: { ...partialMessage },\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"done\":\n\t\t\t\t\tcase \"error\": {\n\t\t\t\t\t\tlet finalMessage = getTerminalMessage(event);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tfinalMessage = await maybePromiseWithAbort(response.result(), signal);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tif (!signal?.aborted || !isAbortError(error)) {\n\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (addedPartial) {\n\t\t\t\t\t\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcontext.messages.push(finalMessage);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!addedPartial) {\n\t\t\t\t\t\t\tawait emit({ type: \"message_start\", message: { ...finalMessage } });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tawait emit({ type: \"message_end\", message: finalMessage });\n\t\t\t\t\t\treturn finalMessage;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst finalMessage = await maybePromiseWithAbort(response.result(), signal);\n\t\t\tif (addedPartial) {\n\t\t\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t\t\t} else {\n\t\t\t\tcontext.messages.push(finalMessage);\n\t\t\t\tawait emit({ type: \"message_start\", message: { ...finalMessage } });\n\t\t\t}\n\t\t\tawait emit({ type: \"message_end\", message: finalMessage });\n\t\t\treturn finalMessage;\n\t\t} catch (error) {\n\t\t\tif (signal?.aborted && isAbortError(error)) {\n\t\t\t\treturn await finishAbortedMessage();\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t};\n\n\tlet outcome: { message: AssistantMessage } | { error: unknown };\n\ttry {\n\t\toutcome = { message: await runResponse() };\n\t} catch (error) {\n\t\toutcome = { error };\n\t}\n\ttry {\n\t\tif (build.projection) await build.projection.release?.();\n\t} catch (error) {\n\t\tif (\"error\" in outcome) {\n\t\t\tthrow new AggregateError(\n\t\t\t\t[outcome.error, error],\n\t\t\t\t`Agent inference and context cleanup failed: ${String(outcome.error)}`,\n\t\t\t);\n\t\t}\n\t\tthrow error;\n\t}\n\tif (\"error\" in outcome) {\n\t\tif (\n\t\t\tallowRecovery &&\n\t\t\t!addedPartial &&\n\t\t\tisLocalRequestPreparationError(outcome.error) &&\n\t\t\tconfig.recoverRequestPreparation\n\t\t) {\n\t\t\tlet recovered: boolean | \"reprepare\";\n\t\t\ttry {\n\t\t\t\trecovered = await config.recoverRequestPreparation(outcome.error, signal);\n\t\t\t} catch (error) {\n\t\t\t\t// Preserve the real owner error, including a post-ACK compaction failure.\n\t\t\t\tmarkLocalRequestPreparationError(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (recovered === \"reprepare\" && allowReprepare) {\n\t\t\t\t// A bounded deterministic change (for example, rebasing a TaskFrame) must\n\t\t\t\t// not consume the one recovery available if the new request still cannot fit.\n\t\t\t\treturn streamAssistantResponse(context, config, signal, emit, streamFn, true, false);\n\t\t\t}\n\t\t\tif (recovered === true) {\n\t\t\t\t// Keep this invocation's output collector, completed tools and emitted messages.\n\t\t\t\treturn streamAssistantResponse(context, config, signal, emit, streamFn, false, false);\n\t\t\t}\n\t\t}\n\t\tthrow outcome.error;\n\t}\n\treturn outcome.message;\n}\n\nasync function executeToolCalls(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\toutput?: InvocationOutput,\n): Promise<ExecutedToolCallBatch> {\n\tconst toolCalls = assistantMessage.content\n\t\t.filter((c) => c.type === \"toolCall\")\n\t\t.map((toolCall, sourceOrder) => ({\n\t\t\ttoolCall,\n\t\t\tsourceOrder,\n\t\t\texecutionId: crypto.randomUUID(),\n\t\t\tassistantMessage,\n\t\t\toriginalInput: structuredClone(toolCall.arguments),\n\t\t}));\n\tconst hasSequentialToolCall = toolCalls.some(\n\t\t({ toolCall }) => currentContext.tools?.find((t) => t.name === toolCall.name)?.executionMode === \"sequential\",\n\t);\n\tif (config.toolExecution === \"sequential\" || hasSequentialToolCall) {\n\t\treturn executeToolCallsSequential(currentContext, assistantMessage, toolCalls, config, signal, emit, output);\n\t}\n\treturn executeToolCallsParallel(currentContext, assistantMessage, toolCalls, config, signal, emit);\n}\n\ntype ToolCallSource = {\n\towner?: BoundToolExecution;\n\texecutionId: string;\n\tassistantMessage: AssistantMessage;\n\ttoolCall: AgentToolCall;\n\tsourceOrder: number;\n\toriginalInput: unknown;\n};\n\ntype ExecutedToolCallBatch = {\n\tmessages: ToolResultMessage[];\n\texchanges: FinalizedToolExchange[];\n\ttoolExecution: ToolExecutionMode;\n\tterminate: boolean;\n};\n\nasync function executeToolCallsSequential(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: ToolCallSource[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\toutput?: InvocationOutput,\n): Promise<ExecutedToolCallBatch> {\n\tconst finalizedCalls: FinalizedToolCallOutcome[] = [];\n\tconst messages: ToolResultMessage[] = [];\n\tconst exchanges: FinalizedToolExchange[] = [];\n\n\tfor (const source of toolCalls) {\n\t\tconst { toolCall } = source;\n\t\tif (signal?.aborted) {\n\t\t\tbreak;\n\t\t}\n\n\t\tawait emit({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\targs: toolCall.arguments,\n\t\t});\n\n\t\tconst preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);\n\t\tlet finalized: FinalizedToolCallOutcome;\n\t\tif (preparation.kind === \"immediate\") {\n\t\t\tfinalized = {\n\t\t\t\ttoolCall,\n\t\t\t\tresult: preparation.result,\n\t\t\t\tisError: preparation.isError,\n\t\t\t\texecutionOutcome: \"not_started\",\n\t\t\t};\n\t\t} else {\n\t\t\tconst executed = await executePreparedToolCall(preparation, source, \"sequential\", config, signal, emit);\n\t\t\tfinalized = await finalizeExecutedToolCall(\n\t\t\t\tcurrentContext,\n\t\t\t\tassistantMessage,\n\t\t\t\tpreparation,\n\t\t\t\texecuted,\n\t\t\t\tconfig,\n\t\t\t\tsignal,\n\t\t\t);\n\t\t}\n\n\t\tconst published = await publishToolExchange(finalized, source, \"sequential\", config, signal, emit);\n\t\tawait emitToolResultMessage(published.exchange.result, emit);\n\t\tfinalizedCalls.push(finalized);\n\t\tmessages.push(published.exchange.result);\n\t\texchanges.push(published.exchange);\n\n\t\tif (signal?.aborted || output?.refusal) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn {\n\t\tmessages,\n\t\texchanges,\n\t\ttoolExecution: \"sequential\",\n\t\tterminate: shouldTerminateToolBatch(finalizedCalls),\n\t};\n}\n\nasync function executeToolCallsParallel(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: ToolCallSource[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallBatch> {\n\tconst finalizedCalls: FinalizedToolCallEntry[] = [];\n\n\tfor (const source of toolCalls) {\n\t\tconst { toolCall } = source;\n\t\tawait emit({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\targs: toolCall.arguments,\n\t\t});\n\n\t\tconst preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);\n\t\tif (preparation.kind === \"immediate\") {\n\t\t\tconst finalized = {\n\t\t\t\ttoolCall,\n\t\t\t\tresult: preparation.result,\n\t\t\t\tisError: preparation.isError,\n\t\t\t\texecutionOutcome: \"not_started\",\n\t\t\t} satisfies FinalizedToolCallOutcome;\n\t\t\tfinalizedCalls.push(await publishToolExchange(finalized, source, \"parallel\", config, signal, emit));\n\t\t\tcontinue;\n\t\t}\n\n\t\tfinalizedCalls.push(async () => {\n\t\t\tconst executed = await executePreparedToolCall(preparation, source, \"parallel\", config, signal, emit);\n\t\t\tconst finalized = await finalizeExecutedToolCall(\n\t\t\t\tcurrentContext,\n\t\t\t\tassistantMessage,\n\t\t\t\tpreparation,\n\t\t\t\texecuted,\n\t\t\t\tconfig,\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\treturn publishToolExchange(finalized, source, \"parallel\", config, signal, emit);\n\t\t});\n\t}\n\n\t// An owner/publication failure must not abandon other invocations already started.\n\tconst settledCalls = await Promise.allSettled(\n\t\tfinalizedCalls.map((entry) => (typeof entry === \"function\" ? entry() : Promise.resolve(entry))),\n\t);\n\tconst orderedFinalizedCalls = settledCalls.flatMap((settled) =>\n\t\tsettled.status === \"fulfilled\" ? [settled.value] : [],\n\t);\n\tconst failure = settledCalls.find((settled) => settled.status === \"rejected\");\n\tconst messages: ToolResultMessage[] = [];\n\tfor (const finalized of orderedFinalizedCalls) {\n\t\tconst toolResultMessage = finalized.exchange.result;\n\t\tawait emitToolResultMessage(toolResultMessage, emit);\n\t\tmessages.push(toolResultMessage);\n\t}\n\n\tif (failure?.status === \"rejected\") throw failure.reason;\n\treturn {\n\t\tmessages,\n\t\texchanges: orderedFinalizedCalls.map((finalized) => finalized.exchange),\n\t\ttoolExecution: \"parallel\",\n\t\tterminate: shouldTerminateToolBatch(orderedFinalizedCalls),\n\t};\n}\n\ntype PreparedToolCall = {\n\tkind: \"prepared\";\n\ttoolCall: AgentToolCall;\n\ttool: AgentTool<any>;\n\targs: unknown;\n};\n\ntype ImmediateToolCallOutcome = {\n\tkind: \"immediate\";\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n};\n\ntype ExecutedToolCallOutcome = {\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n\texecutedInput?: unknown;\n\texecutionOutcome: ToolExecutionOutcome;\n};\n\ntype FinalizedToolCallOutcome = ExecutedToolCallOutcome & {\n\ttoolCall: AgentToolCall;\n};\n\ntype PublishedToolCallOutcome = FinalizedToolCallOutcome & { exchange: FinalizedToolExchange };\n\ntype FinalizedToolCallEntry = PublishedToolCallOutcome | (() => Promise<PublishedToolCallOutcome>);\n\nfunction shouldTerminateToolBatch(finalizedCalls: FinalizedToolCallOutcome[]): boolean {\n\treturn finalizedCalls.length > 0 && finalizedCalls.every((finalized) => finalized.result.terminate === true);\n}\n\nfunction prepareToolCallArguments(tool: AgentTool<any>, toolCall: AgentToolCall): AgentToolCall {\n\tif (!tool.prepareArguments) {\n\t\treturn toolCall;\n\t}\n\tconst preparedArguments = tool.prepareArguments(toolCall.arguments);\n\tif (preparedArguments === toolCall.arguments) {\n\t\treturn toolCall;\n\t}\n\treturn {\n\t\t...toolCall,\n\t\targuments: preparedArguments as Record<string, any>,\n\t};\n}\n\nasync function prepareToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCall: AgentToolCall,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<PreparedToolCall | ImmediateToolCallOutcome> {\n\tconst tool = currentContext.tools?.find((t) => t.name === toolCall.name);\n\tif (!tool) {\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(`Tool ${toolCall.name} not found`),\n\t\t\tisError: true,\n\t\t};\n\t}\n\n\ttry {\n\t\tconst preparedToolCall = prepareToolCallArguments(tool, toolCall);\n\t\tconst validatedArgs = validateToolArguments(tool, preparedToolCall);\n\t\tif (config.beforeToolCall) {\n\t\t\tconst beforeResult = await maybePromiseWithAbort(\n\t\t\t\tconfig.beforeToolCall(\n\t\t\t\t\t{\n\t\t\t\t\t\tassistantMessage,\n\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\targs: validatedArgs,\n\t\t\t\t\t\tcontext: currentContext,\n\t\t\t\t\t},\n\t\t\t\t\tsignal,\n\t\t\t\t),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (beforeResult?.block) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"immediate\",\n\t\t\t\t\tresult: createErrorToolResult(beforeResult.reason || \"Tool execution was blocked\"),\n\t\t\t\t\tisError: true,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tkind: \"prepared\",\n\t\t\ttoolCall,\n\t\t\ttool,\n\t\t\targs: validatedArgs,\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(error instanceof Error ? error.message : String(error)),\n\t\t\tisError: true,\n\t\t};\n\t}\n}\n\nasync function executePreparedToolCall(\n\tprepared: PreparedToolCall,\n\tsource: ToolCallSource,\n\ttoolExecution: ToolExecutionMode,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallOutcome> {\n\tconst invocationArgs = structuredClone(prepared.args);\n\tconst executedInput = structuredClone(invocationArgs);\n\tconst execute = prepared.tool.execute;\n\tif (!signal?.aborted) {\n\t\t// Admission failures must not become synthetic tool results or fall through to effects.\n\t\tconst owner = await config.onToolInvocationStarting?.(\n\t\t\t{\n\t\t\t\texecutionId: source.executionId,\n\t\t\t\tsourceOrder: source.sourceOrder,\n\t\t\t\ttoolCallId: prepared.toolCall.id,\n\t\t\t\ttoolName: prepared.toolCall.name,\n\t\t\t\toriginalInput: source.originalInput,\n\t\t\t\texecutedInput,\n\t\t\t\ttoolExecution,\n\t\t\t},\n\t\t\tsignal,\n\t\t\tprepared.tool,\n\t\t\texecute,\n\t\t\tsource.assistantMessage,\n\t\t);\n\t\tif (owner) source.owner = owner;\n\t}\n\tlet acceptingUpdates = true;\n\tlet pendingUpdates = 0;\n\tlet finishUpdates!: () => void;\n\tlet failUpdates!: (error: unknown) => void;\n\tconst updateEvents = new Promise<void>((resolve, reject) => {\n\t\tfinishUpdates = resolve;\n\t\tfailUpdates = reject;\n\t});\n\t// Observe early failures now; the normal execution path still awaits and reports them.\n\tvoid updateEvents.catch(() => undefined);\n\tconst settleUpdate = () => {\n\t\tpendingUpdates--;\n\t\tif (!acceptingUpdates && pendingUpdates === 0) finishUpdates();\n\t};\n\tconst stopUpdates = () => {\n\t\tacceptingUpdates = false;\n\t\tif (pendingUpdates === 0) finishUpdates();\n\t};\n\tlet executionStarted = false;\n\n\ttry {\n\t\tthrowIfAborted(signal);\n\t\texecutionStarted = true;\n\t\tconst run = () =>\n\t\t\texecute.call(prepared.tool, prepared.toolCall.id, invocationArgs as never, signal, (partialResult) => {\n\t\t\t\tif (!acceptingUpdates || signal?.aborted) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst update = Promise.resolve(\n\t\t\t\t\temit({\n\t\t\t\t\t\ttype: \"tool_execution_update\",\n\t\t\t\t\t\ttoolCallId: prepared.toolCall.id,\n\t\t\t\t\t\ttoolName: prepared.toolCall.name,\n\t\t\t\t\t\targs: prepared.toolCall.arguments,\n\t\t\t\t\t\tpartialResult,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\t// Do not retain every stdout callback or feed an unbounded array to Promise.all.\n\t\t\t\tpendingUpdates++;\n\t\t\t\tvoid update.then(settleUpdate, (error) => {\n\t\t\t\t\tfailUpdates(error);\n\t\t\t\t\tsettleUpdate();\n\t\t\t\t});\n\t\t\t});\n\t\tconst result = await raceWithAbort(source.owner ? source.owner.run(run) : run(), signal);\n\t\tstopUpdates();\n\t\ttry {\n\t\t\tawait raceWithAbort(updateEvents, signal);\n\t\t} catch (error) {\n\t\t\tif (!signal?.aborted || !isAbortError(error)) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\treturn { result, isError: false, executedInput, executionOutcome: \"completed\" };\n\t} catch (error) {\n\t\tstopUpdates();\n\t\tawait raceWithAbort(updateEvents, signal).catch(() => undefined);\n\t\treturn {\n\t\t\tresult: createErrorToolResult(\n\t\t\t\tsignal?.aborted ? \"Tool execution aborted\" : error instanceof Error ? error.message : String(error),\n\t\t\t),\n\t\t\tisError: true,\n\t\t\t...(executionStarted ? { executedInput } : {}),\n\t\t\texecutionOutcome: !executionStarted ? \"not_started\" : signal?.aborted ? \"outcome_unknown\" : \"failed\",\n\t\t};\n\t}\n}\n\nasync function finalizeExecutedToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tprepared: PreparedToolCall,\n\texecuted: ExecutedToolCallOutcome,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<FinalizedToolCallOutcome> {\n\tlet result = executed.result;\n\tlet isError = executed.isError;\n\n\tif (config.afterToolCall) {\n\t\ttry {\n\t\t\tconst afterResult = await maybePromiseWithAbort(\n\t\t\t\tconfig.afterToolCall(\n\t\t\t\t\t{\n\t\t\t\t\t\tassistantMessage,\n\t\t\t\t\t\ttoolCall: prepared.toolCall,\n\t\t\t\t\t\targs: prepared.args,\n\t\t\t\t\t\tresult,\n\t\t\t\t\t\tisError,\n\t\t\t\t\t\tcontext: currentContext,\n\t\t\t\t\t},\n\t\t\t\t\tsignal,\n\t\t\t\t),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (afterResult) {\n\t\t\t\tresult = {\n\t\t\t\t\tcontent: afterResult.content ?? result.content,\n\t\t\t\t\tdetails: afterResult.details ?? result.details,\n\t\t\t\t\tterminate: afterResult.terminate ?? result.terminate,\n\t\t\t\t};\n\t\t\t\tisError = afterResult.isError ?? isError;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tresult = createErrorToolResult(error instanceof Error ? error.message : String(error));\n\t\t\tisError = true;\n\t\t}\n\t}\n\n\treturn {\n\t\t...executed,\n\t\ttoolCall: prepared.toolCall,\n\t\tresult,\n\t\tisError,\n\t};\n}\n\nfunction createErrorToolResult(message: string): AgentToolResult<any> {\n\treturn {\n\t\tcontent: [{ type: \"text\", text: message }],\n\t\tdetails: {},\n\t};\n}\n\nasync function publishToolExchange(\n\tfinalized: FinalizedToolCallOutcome,\n\tsource: ToolCallSource,\n\ttoolExecution: ToolExecutionMode,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<PublishedToolCallOutcome> {\n\tconst exchange: FinalizedToolExchange = {\n\t\texecutionId: source.executionId,\n\t\tsourceOrder: source.sourceOrder,\n\t\ttoolCallId: finalized.toolCall.id,\n\t\ttoolName: finalized.toolCall.name,\n\t\toriginalInput: source.originalInput,\n\t\t...(finalized.executionOutcome === \"not_started\" ? {} : { executedInput: finalized.executedInput }),\n\t\ttoolExecution,\n\t\texecutionOutcome: finalized.executionOutcome,\n\t\tcancellationRequested: signal?.aborted ?? false,\n\t\tresult: createToolResultMessage(finalized),\n\t};\n\tawait config.onToolExchangeFinalized?.(exchange, signal, source.owner);\n\tawait emit({\n\t\ttype: \"tool_execution_end\",\n\t\ttoolCallId: finalized.toolCall.id,\n\t\ttoolName: finalized.toolCall.name,\n\t\tresult: finalized.result,\n\t\tisError: finalized.isError,\n\t\texchange,\n\t});\n\treturn { ...finalized, exchange };\n}\n\nfunction createToolResultMessage(finalized: FinalizedToolCallOutcome): ToolResultMessage {\n\treturn {\n\t\trole: \"toolResult\",\n\t\ttoolCallId: finalized.toolCall.id,\n\t\ttoolName: finalized.toolCall.name,\n\t\tcontent: finalized.result.content,\n\t\tdetails: finalized.result.details,\n\t\tisError: finalized.isError,\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nasync function emitToolResultMessage(toolResultMessage: ToolResultMessage, emit: AgentEventSink): Promise<void> {\n\tawait emit({ type: \"message_start\", message: toolResultMessage });\n\tawait emit({ type: \"message_end\", message: toolResultMessage });\n}\n"]}
1
+ {"version":3,"file":"agent-loop.js","sourceRoot":"","sources":["../src/agent-loop.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAIN,WAAW,EACX,8BAA8B,EAC9B,gCAAgC,EAChC,YAAY,EAEZ,qBAAqB,GACrB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAmBjF,MAAM,mBAAmB,GAAG,qBAAqB,CAAC;AAClD,MAAM,WAAW,GAA8B;IAC9C,KAAK,EAAE,CAAC;IACR,MAAM,EAAE,CAAC;IACT,SAAS,EAAE,CAAC;IACZ,UAAU,EAAE,CAAC;IACb,WAAW,EAAE,CAAC;IACd,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE;CACpE,CAAC;AAEF,SAAS,gBAAgB,GAAU;IAClC,OAAO,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;AAAA,CACtC;AAED,SAAS,cAAc,CAAC,MAA+B,EAAQ;IAC9D,IAAI,MAAM,EAAE,OAAO,EAAE,CAAC;QACrB,MAAM,gBAAgB,EAAE,CAAC;IAC1B,CAAC;AAAA,CACD;AAED,SAAS,aAAa,CAAI,SAAqB,EAAE,MAA+B,EAAE,OAAoB,EAAc;IACnH,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;QACpB,OAAO,EAAE,EAAE,CAAC;QACZ,KAAK,SAAS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AE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC;IAClE,MAAM,IAAI,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC;AAAA,CAChE","sourcesContent":["/**\n * Agent loop that works with AgentMessage throughout.\n * Transforms to Message[] only at the LLM call boundary.\n */\n\nimport {\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\ttype Context,\n\tEventStream,\n\tisLocalRequestPreparationError,\n\tmarkLocalRequestPreparationError,\n\tstreamSimple,\n\ttype ToolResultMessage,\n\tvalidateToolArguments,\n} from \"@ponythewhite/base-context-ai\";\nimport { AgentOutputLimitError, InvocationOutput } from \"./invocation-output.js\";\nimport type {\n\tAgentContext,\n\tAgentContextBuildResult,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentTool,\n\tAgentToolCall,\n\tAgentToolResult,\n\tBoundToolExecution,\n\tFinalizedToolExchange,\n\tStreamFn,\n\tToolExecutionMode,\n\tToolExecutionOutcome,\n} from \"./types.js\";\n\nexport type AgentEventSink = (event: AgentEvent) => Promise<void> | void;\n\nconst ABORT_ERROR_MESSAGE = \"Request was aborted\";\nconst EMPTY_USAGE: AssistantMessage[\"usage\"] = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nfunction createAbortError(): Error {\n\treturn new Error(ABORT_ERROR_MESSAGE);\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n\tif (signal?.aborted) {\n\t\tthrow createAbortError();\n\t}\n}\n\nfunction raceWithAbort<T>(operation: Promise<T>, signal: AbortSignal | undefined, onAbort?: () => void): Promise<T> {\n\tif (!signal) {\n\t\treturn operation;\n\t}\n\tif (signal.aborted) {\n\t\tonAbort?.();\n\t\tvoid operation.catch(() => undefined);\n\t\treturn Promise.reject(createAbortError());\n\t}\n\n\treturn new Promise<T>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst cleanup = () => {\n\t\t\tsignal.removeEventListener(\"abort\", abort);\n\t\t};\n\t\tconst abort = () => {\n\t\t\tif (settled) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tonAbort?.();\n\t\t\treject(createAbortError());\n\t\t};\n\t\tsignal.addEventListener(\"abort\", abort, { once: true });\n\t\toperation.then(\n\t\t\t(value) => {\n\t\t\t\tif (settled) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettled = true;\n\t\t\t\tcleanup();\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\tif (settled) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettled = true;\n\t\t\t\tcleanup();\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\nfunction maybePromiseWithAbort<T>(\n\toperation: T | Promise<T>,\n\tsignal: AbortSignal | undefined,\n\tonAbort?: () => void,\n): Promise<T> {\n\treturn raceWithAbort(Promise.resolve(operation), signal, onAbort);\n}\n\nfunction isAbortError(error: unknown): boolean {\n\treturn error instanceof Error && (error.message === ABORT_ERROR_MESSAGE || error.name === \"AbortError\");\n}\n\ntype PostTurnResult<T> = { status: \"completed\"; value: T } | { status: \"aborted\" };\n\nasync function settlePostTurn<T>(operation: Promise<T>, signal: AbortSignal | undefined): Promise<PostTurnResult<T>> {\n\ttry {\n\t\treturn { status: \"completed\", value: await operation };\n\t} catch (error) {\n\t\tif (signal?.aborted && isAbortError(error)) {\n\t\t\treturn { status: \"aborted\" };\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nfunction cloneAssistantContent(content: AssistantMessage[\"content\"]): AssistantMessage[\"content\"] {\n\treturn content.map((part) => {\n\t\tif (part.type === \"toolCall\") {\n\t\t\treturn { ...part, arguments: { ...part.arguments } };\n\t\t}\n\t\treturn { ...part };\n\t});\n}\n\nfunction cloneUsage(usage: AssistantMessage[\"usage\"]): AssistantMessage[\"usage\"] {\n\treturn { ...usage, cost: { ...usage.cost } };\n}\n\nfunction createAbortedAssistantMessage(\n\tconfig: AgentLoopConfig,\n\tpartialMessage: AssistantMessage | null,\n): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: partialMessage ? cloneAssistantContent(partialMessage.content) : [{ type: \"text\", text: \"\" }],\n\t\tapi: partialMessage?.api ?? config.model.api,\n\t\tprovider: partialMessage?.provider ?? config.model.provider,\n\t\tmodel: partialMessage?.model ?? config.model.id,\n\t\tusage: cloneUsage(partialMessage?.usage ?? EMPTY_USAGE),\n\t\tstopReason: \"aborted\",\n\t\terrorMessage: ABORT_ERROR_MESSAGE,\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction getTerminalMessage(event: Extract<AssistantMessageEvent, { type: \"done\" | \"error\" }>): AssistantMessage {\n\treturn event.type === \"done\" ? event.message : event.error;\n}\n\nfunction endAgentStreamOnError(\n\tstream: EventStream<AgentEvent, AgentMessage[]>,\n\tpromise: Promise<AgentMessage[]>,\n): void {\n\tvoid promise.then(\n\t\t(messages) => {\n\t\t\tstream.end(messages);\n\t\t},\n\t\t(error) => {\n\t\t\tif (error instanceof AgentOutputLimitError) stream.fail(error);\n\t\t\telse stream.end([]);\n\t\t},\n\t);\n}\n\nasync function pollMessagesUnlessAborted(\n\tpoll: (() => AgentMessage[] | Promise<AgentMessage[]>) | undefined,\n\tsignal: AbortSignal | undefined,\n): Promise<AgentMessage[]> {\n\tif (!poll || signal?.aborted) {\n\t\treturn [];\n\t}\n\treturn (await maybePromiseWithAbort(poll(), signal)) || [];\n}\n\n/**\n * Start an agent loop with a new prompt message.\n * The prompt is added to the context and events are emitted for it.\n */\nexport function agentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tconst stream = createAgentStream();\n\n\tendAgentStreamOnError(\n\t\tstream,\n\t\trunAgentLoop(\n\t\t\tprompts,\n\t\t\tcontext,\n\t\t\tconfig,\n\t\t\tasync (event) => {\n\t\t\t\tstream.push(event);\n\t\t\t},\n\t\t\tsignal,\n\t\t\tstreamFn,\n\t\t),\n\t);\n\n\treturn stream;\n}\n\n/**\n * Continue an agent loop from the current context without adding a new message.\n * Used for retries - context already has user message or tool results.\n *\n * **Important:** The last message in context must convert to a `user` or `toolResult` message\n * via `convertToLlm`. If it doesn't, the LLM provider will reject the request.\n * This cannot be validated here since `convertToLlm` is only called once per turn.\n */\nexport function agentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\tif (context.messages[context.messages.length - 1].role === \"assistant\") {\n\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t}\n\n\tconst stream = createAgentStream();\n\n\tendAgentStreamOnError(\n\t\tstream,\n\t\trunAgentLoopContinue(\n\t\t\tcontext,\n\t\t\tconfig,\n\t\t\tasync (event) => {\n\t\t\t\tstream.push(event);\n\t\t\t},\n\t\t\tsignal,\n\t\t\tstreamFn,\n\t\t),\n\t);\n\n\treturn stream;\n}\n\nasync function withInvocationOutput(\n\tmessages: AgentMessage[],\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\trun: (emit: AgentEventSink, output: InvocationOutput | undefined) => Promise<void>,\n): Promise<AgentMessage[]> {\n\tconst output = config.outputPolicy ? new InvocationOutput(config.outputPolicy, messages) : undefined;\n\tlet releaseUpdates = output ? output.policy.bindUpdates?.(output.refresh.bind(output)) : undefined;\n\tconst stopUpdates = () => {\n\t\tconst release = releaseUpdates;\n\t\treleaseUpdates = undefined;\n\t\trelease?.();\n\t};\n\tlet updateSettlement: Promise<void> | undefined;\n\tconst settleUpdates = () => {\n\t\tif (!updateSettlement) {\n\t\t\ttry {\n\t\t\t\tupdateSettlement = output?.policy.settleUpdates?.() ?? Promise.resolve();\n\t\t\t} catch (error) {\n\t\t\t\tupdateSettlement = Promise.reject(error);\n\t\t\t}\n\t\t}\n\t\treturn updateSettlement;\n\t};\n\tconst ownedEmit: AgentEventSink = output\n\t\t? async (event) => {\n\t\t\t\tif (event.type === \"agent_end\") {\n\t\t\t\t\tawait settleUpdates();\n\t\t\t\t\toutput.throwIfRefused();\n\t\t\t\t\tconst finalizedMessages = output.copy();\n\t\t\t\t\tstopUpdates();\n\t\t\t\t\tawait emit({ type: \"agent_end\", messages: finalizedMessages });\n\t\t\t\t} else {\n\t\t\t\t\tawait emit(event);\n\t\t\t\t\t// The native sink joins this message's replacement/persistence job. Keep its original subject.\n\t\t\t\t\tif (event.type === \"message_end\") output.capture(event.message);\n\t\t\t\t}\n\t\t\t}\n\t\t: emit;\n\ttry {\n\t\tawait run(ownedEmit, output);\n\t\treturn messages;\n\t} catch (error) {\n\t\tif (!output) throw error;\n\t\tlet failure = error;\n\t\ttry {\n\t\t\tawait settleUpdates();\n\t\t} catch (settlementError) {\n\t\t\tif (settlementError !== failure)\n\t\t\t\tfailure = new AggregateError(\n\t\t\t\t\t[failure, settlementError],\n\t\t\t\t\t\"Invocation and accepted update settlement failed\",\n\t\t\t\t\t{ cause: failure },\n\t\t\t\t);\n\t\t}\n\t\tif (!output.refusal) throw failure;\n\t\tlet cause: unknown = failure instanceof AgentOutputLimitError ? failure.cause : failure;\n\t\tstopUpdates();\n\t\ttry {\n\t\t\tawait emit({ type: \"agent_end\", refusal: { ...output.refusal } });\n\t\t} catch (notificationError) {\n\t\t\tcause =\n\t\t\t\tcause === undefined\n\t\t\t\t\t? notificationError\n\t\t\t\t\t: new AggregateError([cause, notificationError], \"Output refusal and terminal notification failed\");\n\t\t}\n\t\tthrow new AgentOutputLimitError({ ...output.refusal }, cause === undefined ? undefined : { cause });\n\t} finally {\n\t\ttry {\n\t\t\tstopUpdates();\n\t\t} finally {\n\t\t\toutput?.dispose();\n\t\t}\n\t}\n}\n\nexport async function runAgentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): Promise<AgentMessage[]> {\n\tconst newMessages: AgentMessage[] = config.outputPolicy ? [] : [...prompts];\n\treturn withInvocationOutput(newMessages, config, emit, async (ownedEmit, output) => {\n\t\tif (output) {\n\t\t\toutput.checkRoom(prompts.length);\n\t\t\tprompts = [...prompts];\n\t\t}\n\t\t// Keep only the working wrapper across awaits, not the initial snapshot.\n\t\tcontext = { ...context, messages: [...context.messages, ...prompts] };\n\t\tawait ownedEmit({ type: \"agent_start\" });\n\t\tawait ownedEmit({ type: \"turn_start\" });\n\t\tfor (const prompt of prompts) {\n\t\t\tawait ownedEmit({ type: \"message_start\", message: prompt });\n\t\t\tawait ownedEmit({ type: \"message_end\", message: prompt });\n\t\t\toutput?.throwIfRefused();\n\t\t}\n\t\tawait runLoop(context, newMessages, config, signal, ownedEmit, streamFn, output);\n\t});\n}\n\nexport async function runAgentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): Promise<AgentMessage[]> {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\tif (context.messages[context.messages.length - 1].role === \"assistant\") {\n\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t}\n\n\tconst newMessages: AgentMessage[] = [];\n\treturn withInvocationOutput(newMessages, config, emit, async (ownedEmit, output) => {\n\t\tcontext = { ...context };\n\t\tawait ownedEmit({ type: \"agent_start\" });\n\t\toutput?.throwIfRefused();\n\t\tawait ownedEmit({ type: \"turn_start\" });\n\t\tawait runLoop(context, newMessages, config, signal, ownedEmit, streamFn, output);\n\t});\n}\n\nfunction createAgentStream(): EventStream<AgentEvent, AgentMessage[]> {\n\treturn new EventStream<AgentEvent, AgentMessage[]>(\n\t\t(event: AgentEvent) => event.type === \"agent_end\" && !event.refusal,\n\t\t(event: AgentEvent) => (event.type === \"agent_end\" && !event.refusal ? event.messages : []),\n\t);\n}\n\nasync function runLoop(\n\tcurrentContext: AgentContext,\n\tnewMessages: AgentMessage[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n\toutput?: InvocationOutput,\n): Promise<void> {\n\tlet firstTurn = true;\n\tlet lastTurn: Parameters<NonNullable<AgentLoopConfig[\"getContinuationMessages\"]>>[0] | undefined;\n\tlet pendingMessages: AgentMessage[] = await pollMessagesUnlessAborted(config.getSteeringMessages, signal);\n\n\tconst shouldStopBeforeTurn = (): boolean => !firstTurn && (config.shouldStopBeforeTurn?.() ?? false);\n\n\twhile (true) {\n\t\tthrowIfAborted(signal);\n\t\tlet hasMoreToolCalls = true;\n\n\t\twhile (hasMoreToolCalls || pendingMessages.length > 0) {\n\t\t\tthrowIfAborted(signal);\n\t\t\tif (!firstTurn) {\n\t\t\t\tawait emit({ type: \"turn_start\" });\n\t\t\t} else {\n\t\t\t\tfirstTurn = false;\n\t\t\t}\n\n\t\t\tif (pendingMessages.length > 0) {\n\t\t\t\toutput?.checkRoom(pendingMessages.length);\n\t\t\t\tif (output) pendingMessages = [...pendingMessages];\n\t\t\t\tfor (const message of pendingMessages) {\n\t\t\t\t\tawait emit({ type: \"message_start\", message });\n\t\t\t\t\tawait emit({ type: \"message_end\", message });\n\t\t\t\t\tcurrentContext.messages.push(message);\n\t\t\t\t\tif (!output) newMessages.push(message);\n\t\t\t\t\toutput?.throwIfRefused();\n\t\t\t\t}\n\t\t\t\tpendingMessages = [];\n\t\t\t}\n\n\t\t\toutput?.checkRoom(1);\n\t\t\tconst message = await streamAssistantResponse(currentContext, config, signal, emit, streamFn);\n\t\t\tif (!output) newMessages.push(message);\n\t\t\toutput?.throwIfRefused();\n\n\t\t\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\t\t\tawait emit({\n\t\t\t\t\ttype: \"turn_end\",\n\t\t\t\t\tmessage,\n\t\t\t\t\ttoolResults: [],\n\t\t\t\t\ttoolExecution: config.toolExecution ?? \"parallel\",\n\t\t\t\t\texchanges: [],\n\t\t\t\t});\n\t\t\t\toutput?.refresh(message);\n\t\t\t\tif (\n\t\t\t\t\tmessage.stopReason === \"error\" &&\n\t\t\t\t\tconfig.recoverProviderFailure &&\n\t\t\t\t\t(await maybePromiseWithAbort(config.recoverProviderFailure(message, signal), signal))\n\t\t\t\t) {\n\t\t\t\t\t// Retain and charge the failed output; only omit it from the next request.\n\t\t\t\t\tcurrentContext.messages = currentContext.messages.filter((candidate) => candidate !== message);\n\t\t\t\t\thasMoreToolCalls = true;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst toolCalls = message.content.filter((c) => c.type === \"toolCall\");\n\n\t\t\tconst toolResults: ToolResultMessage[] = [];\n\t\t\tconst exchanges: FinalizedToolExchange[] = [];\n\t\t\tlet toolExecution = config.toolExecution ?? \"parallel\";\n\t\t\thasMoreToolCalls = false;\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\toutput?.checkRoom(toolCalls.length);\n\t\t\t\tconst executedToolBatch = await executeToolCalls(currentContext, message, config, signal, emit, output);\n\t\t\t\ttoolResults.push(...executedToolBatch.messages);\n\t\t\t\texchanges.push(...executedToolBatch.exchanges);\n\t\t\t\ttoolExecution = executedToolBatch.toolExecution;\n\t\t\t\thasMoreToolCalls = !executedToolBatch.terminate;\n\n\t\t\t\tfor (const result of toolResults) {\n\t\t\t\t\tcurrentContext.messages.push(result);\n\t\t\t\t\tif (!output) newMessages.push(result);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\toutput?.throwIfRefused();\n\t\t\tawait emit({ type: \"turn_end\", message, toolResults, toolExecution, exchanges });\n\t\t\toutput?.refresh(message);\n\t\t\tfor (const result of toolResults) output?.refresh(result);\n\t\t\toutput?.throwIfRefused();\n\t\t\tif (signal?.aborted) {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlastTurn = {\n\t\t\t\tmessage,\n\t\t\t\ttoolResults,\n\t\t\t\tcontext: currentContext,\n\t\t\t\tnewMessages,\n\t\t\t};\n\n\t\t\tconst turnContext = { ...lastTurn, newMessages: output?.copy() ?? newMessages };\n\t\t\tconst shouldStopResult = await settlePostTurn(\n\t\t\t\tmaybePromiseWithAbort(\n\t\t\t\t\tconfig.getTurnOutcome\n\t\t\t\t\t\t? config.getTurnOutcome({ ...turnContext, hasMoreToolCalls }, signal)\n\t\t\t\t\t\t: Promise.resolve(config.shouldStopAfterTurn?.(turnContext) ?? false).then((stop) => ({\n\t\t\t\t\t\t\t\tkind: stop ? (\"finish\" as const) : (\"proceed\" as const),\n\t\t\t\t\t\t\t})),\n\t\t\t\t\tsignal,\n\t\t\t\t),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\toutput?.refresh(message);\n\t\t\tfor (const result of toolResults) output?.refresh(result);\n\t\t\toutput?.throwIfRefused();\n\t\t\tif (shouldStopResult.status === \"aborted\") {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (shouldStopResult.value.kind !== \"proceed\" || shouldStopBeforeTurn()) {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst steeringMessagesResult = await settlePostTurn(\n\t\t\t\tpollMessagesUnlessAborted(config.getSteeringMessages, signal),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (steeringMessagesResult.status === \"aborted\") {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpendingMessages = steeringMessagesResult.value;\n\t\t\t// Steering drained by this poll owns the turn boundary; stop only when it was empty.\n\t\t\tif (pendingMessages.length === 0 && shouldStopBeforeTurn()) {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (shouldStopBeforeTurn()) break;\n\t\tconst followUpMessagesResult = await settlePostTurn(\n\t\t\tpollMessagesUnlessAborted(config.getFollowUpMessages, signal),\n\t\t\tsignal,\n\t\t);\n\t\tif (followUpMessagesResult.status === \"aborted\") {\n\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\treturn;\n\t\t}\n\t\tconst followUpMessages = followUpMessagesResult.value;\n\t\tif (followUpMessages.length > 0) {\n\t\t\tpendingMessages = followUpMessages;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (shouldStopBeforeTurn()) break;\n\t\tif (lastTurn && config.getContinuationOutcome) {\n\t\t\tconst outcome = await settlePostTurn(\n\t\t\t\tmaybePromiseWithAbort(\n\t\t\t\t\tconfig.getContinuationOutcome(output ? { ...lastTurn, newMessages: output.copy() } : lastTurn, signal),\n\t\t\t\t\tsignal,\n\t\t\t\t),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (outcome.status === \"completed\" && outcome.value.kind === \"continue\") {\n\t\t\t\tpendingMessages = outcome.value.messages;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tconst continuationMessagesResult = lastTurn\n\t\t\t? await settlePostTurn(\n\t\t\t\t\tmaybePromiseWithAbort(\n\t\t\t\t\t\tconfig.getContinuationMessages?.(\n\t\t\t\t\t\t\toutput ? { ...lastTurn, newMessages: output.copy() } : lastTurn,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t) ?? [],\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t),\n\t\t\t\t\tsignal,\n\t\t\t\t)\n\t\t\t: ({ status: \"completed\", value: [] } satisfies PostTurnResult<AgentMessage[]>);\n\t\tif (continuationMessagesResult.status === \"aborted\") {\n\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\treturn;\n\t\t}\n\t\tconst continuationMessages = continuationMessagesResult.value || [];\n\t\tif (continuationMessages.length > 0) {\n\t\t\tpendingMessages = continuationMessages;\n\t\t\tcontinue;\n\t\t}\n\n\t\tbreak;\n\t}\n\n\tawait emit({ type: \"agent_end\", messages: newMessages });\n}\n\nasync function streamAssistantResponse(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n\tallowRecovery = true,\n\tallowReprepare = true,\n): Promise<AssistantMessage> {\n\tconst build: { projection: AgentContextBuildResult } = { projection: undefined };\n\tlet addedPartial = false;\n\tconst runResponse = async (): Promise<AssistantMessage> => {\n\t\tlet partialMessage: AssistantMessage | null = null;\n\t\tconst finishAbortedMessage = async () => {\n\t\t\tconst finalMessage = createAbortedAssistantMessage(config, partialMessage);\n\t\t\tif (addedPartial) {\n\t\t\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t\t\t} else {\n\t\t\t\tcontext.messages.push(finalMessage);\n\t\t\t\tawait emit({ type: \"message_start\", message: { ...finalMessage } });\n\t\t\t}\n\t\t\tawait emit({ type: \"message_end\", message: finalMessage });\n\t\t\treturn finalMessage;\n\t\t};\n\n\t\ttry {\n\t\t\tthrowIfAborted(signal);\n\t\t\t// Do not race source persistence against cancellation; drain it before leaving this build.\n\t\t\tconst projection = await config.beforeContextBuild?.();\n\t\t\tbuild.projection = projection;\n\t\t\tif (projection && projection.adoptMessages === true) {\n\t\t\t\tcontext.messages = projection.messages.slice();\n\t\t\t\tawait config.onContextAdopted?.(context.messages);\n\t\t\t}\n\t\t\tthrowIfAborted(signal);\n\t\t\tlet messages = projection ? projection.messages.slice() : context.messages;\n\t\t\tif (config.transformContext) {\n\t\t\t\tmessages = await maybePromiseWithAbort(config.transformContext(messages, signal), signal);\n\t\t\t}\n\n\t\t\tconst llmMessages = await maybePromiseWithAbort(config.convertToLlm(messages), signal);\n\n\t\t\tconst streamFunction = streamFn || streamSimple;\n\n\t\t\tconst resolvedApiKey =\n\t\t\t\t(config.getApiKey\n\t\t\t\t\t? await maybePromiseWithAbort(config.getApiKey(config.model.provider), signal)\n\t\t\t\t\t: undefined) || config.apiKey;\n\n\t\t\tconst llmContext: Context = {\n\t\t\t\tsystemPrompt: config.getSystemPrompt?.() ?? context.systemPrompt,\n\t\t\t\tmessages: llmMessages,\n\t\t\t\ttools: context.tools,\n\t\t\t};\n\n\t\t\tconst {\n\t\t\t\tbeforeContextBuild: _beforeContextBuild,\n\t\t\t\tonContextAdopted: _onContextAdopted,\n\t\t\t\trecoverRequestPreparation: _recoverRequestPreparation,\n\t\t\t\trecoverProviderFailure: _recoverProviderFailure,\n\t\t\t\toutputPolicy: _outputPolicy,\n\t\t\t\townedStreamFn,\n\t\t\t\t...streamOptions\n\t\t\t} = config;\n\t\t\tconst options = { ...streamOptions, apiKey: resolvedApiKey, signal };\n\t\t\tconst response = await maybePromiseWithAbort(\n\t\t\t\townedStreamFn\n\t\t\t\t\t? ownedStreamFn(config.model, llmContext, options, projection ? projection.streamContext : undefined)\n\t\t\t\t\t: streamFunction(config.model, llmContext, options),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tconst iterator = response[Symbol.asyncIterator]();\n\t\t\tconst closeIterator = () => {\n\t\t\t\tvoid Promise.resolve(iterator.return?.()).catch(() => undefined);\n\t\t\t};\n\t\t\twhile (true) {\n\t\t\t\tconst next = await raceWithAbort<IteratorResult<AssistantMessageEvent>>(\n\t\t\t\t\titerator.next(),\n\t\t\t\t\tsignal,\n\t\t\t\t\tcloseIterator,\n\t\t\t\t);\n\t\t\t\tif (next.done) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tconst event = next.value;\n\t\t\t\tswitch (event.type) {\n\t\t\t\t\tcase \"start\":\n\t\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\t\tcontext.messages.push(partialMessage);\n\t\t\t\t\t\taddedPartial = true;\n\t\t\t\t\t\tawait emit({ type: \"message_start\", message: { ...partialMessage } });\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"text_start\":\n\t\t\t\t\tcase \"text_delta\":\n\t\t\t\t\tcase \"text_end\":\n\t\t\t\t\tcase \"thinking_start\":\n\t\t\t\t\tcase \"thinking_delta\":\n\t\t\t\t\tcase \"thinking_end\":\n\t\t\t\t\tcase \"toolcall_start\":\n\t\t\t\t\tcase \"toolcall_delta\":\n\t\t\t\t\tcase \"toolcall_end\":\n\t\t\t\t\t\tif (partialMessage) {\n\t\t\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\t\t\tcontext.messages[context.messages.length - 1] = partialMessage;\n\t\t\t\t\t\t\tawait emit({\n\t\t\t\t\t\t\t\ttype: \"message_update\",\n\t\t\t\t\t\t\t\tassistantMessageEvent: event,\n\t\t\t\t\t\t\t\tmessage: { ...partialMessage },\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"done\":\n\t\t\t\t\tcase \"error\": {\n\t\t\t\t\t\tlet finalMessage = getTerminalMessage(event);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tfinalMessage = await maybePromiseWithAbort(response.result(), signal);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tif (!signal?.aborted || !isAbortError(error)) {\n\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (addedPartial) {\n\t\t\t\t\t\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcontext.messages.push(finalMessage);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!addedPartial) {\n\t\t\t\t\t\t\tawait emit({ type: \"message_start\", message: { ...finalMessage } });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tawait emit({ type: \"message_end\", message: finalMessage });\n\t\t\t\t\t\treturn finalMessage;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst finalMessage = await maybePromiseWithAbort(response.result(), signal);\n\t\t\tif (addedPartial) {\n\t\t\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t\t\t} else {\n\t\t\t\tcontext.messages.push(finalMessage);\n\t\t\t\tawait emit({ type: \"message_start\", message: { ...finalMessage } });\n\t\t\t}\n\t\t\tawait emit({ type: \"message_end\", message: finalMessage });\n\t\t\treturn finalMessage;\n\t\t} catch (error) {\n\t\t\tif (signal?.aborted && isAbortError(error)) {\n\t\t\t\treturn await finishAbortedMessage();\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t};\n\n\tlet outcome: { message: AssistantMessage } | { error: unknown };\n\ttry {\n\t\toutcome = { message: await runResponse() };\n\t} catch (error) {\n\t\toutcome = { error };\n\t}\n\ttry {\n\t\tif (build.projection) await build.projection.release?.();\n\t} catch (error) {\n\t\tif (\"error\" in outcome) {\n\t\t\tthrow new AggregateError(\n\t\t\t\t[outcome.error, error],\n\t\t\t\t`Agent inference and context cleanup failed: ${String(outcome.error)}`,\n\t\t\t);\n\t\t}\n\t\tthrow error;\n\t}\n\tif (\"error\" in outcome) {\n\t\tif (\n\t\t\tallowRecovery &&\n\t\t\t!addedPartial &&\n\t\t\tisLocalRequestPreparationError(outcome.error) &&\n\t\t\tconfig.recoverRequestPreparation\n\t\t) {\n\t\t\tlet recovered: boolean | \"reprepare\";\n\t\t\ttry {\n\t\t\t\trecovered = await config.recoverRequestPreparation(outcome.error, signal);\n\t\t\t} catch (error) {\n\t\t\t\t// Preserve the real owner error, including a post-ACK compaction failure.\n\t\t\t\tmarkLocalRequestPreparationError(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (recovered === \"reprepare\" && allowReprepare) {\n\t\t\t\t// A bounded deterministic change (for example, rebasing a TaskFrame) must\n\t\t\t\t// not consume the one recovery available if the new request still cannot fit.\n\t\t\t\treturn streamAssistantResponse(context, config, signal, emit, streamFn, true, false);\n\t\t\t}\n\t\t\tif (recovered === true) {\n\t\t\t\t// Keep this invocation's output collector, completed tools and emitted messages.\n\t\t\t\treturn streamAssistantResponse(context, config, signal, emit, streamFn, false, false);\n\t\t\t}\n\t\t}\n\t\tthrow outcome.error;\n\t}\n\treturn outcome.message;\n}\n\nasync function executeToolCalls(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\toutput?: InvocationOutput,\n): Promise<ExecutedToolCallBatch> {\n\tconst toolCalls = assistantMessage.content\n\t\t.filter((c) => c.type === \"toolCall\")\n\t\t.map((toolCall, sourceOrder) => ({\n\t\t\ttoolCall,\n\t\t\tsourceOrder,\n\t\t\texecutionId: crypto.randomUUID(),\n\t\t\tassistantMessage,\n\t\t\toriginalInput: structuredClone(toolCall.arguments),\n\t\t}));\n\tconst hasSequentialToolCall = toolCalls.some(\n\t\t({ toolCall }) => currentContext.tools?.find((t) => t.name === toolCall.name)?.executionMode === \"sequential\",\n\t);\n\tif (config.toolExecution === \"sequential\" || hasSequentialToolCall) {\n\t\treturn executeToolCallsSequential(currentContext, assistantMessage, toolCalls, config, signal, emit, output);\n\t}\n\treturn executeToolCallsParallel(currentContext, assistantMessage, toolCalls, config, signal, emit);\n}\n\ntype ToolCallSource = {\n\towner?: BoundToolExecution;\n\texecutionId: string;\n\tassistantMessage: AssistantMessage;\n\ttoolCall: AgentToolCall;\n\tsourceOrder: number;\n\toriginalInput: unknown;\n};\n\ntype ExecutedToolCallBatch = {\n\tmessages: ToolResultMessage[];\n\texchanges: FinalizedToolExchange[];\n\ttoolExecution: ToolExecutionMode;\n\tterminate: boolean;\n};\n\nasync function executeToolCallsSequential(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: ToolCallSource[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\toutput?: InvocationOutput,\n): Promise<ExecutedToolCallBatch> {\n\tconst finalizedCalls: FinalizedToolCallOutcome[] = [];\n\tconst messages: ToolResultMessage[] = [];\n\tconst exchanges: FinalizedToolExchange[] = [];\n\n\tfor (const source of toolCalls) {\n\t\tconst { toolCall } = source;\n\t\tif (signal?.aborted) {\n\t\t\tbreak;\n\t\t}\n\n\t\tawait emit({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\targs: toolCall.arguments,\n\t\t});\n\n\t\tconst preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);\n\t\tlet finalized: FinalizedToolCallOutcome;\n\t\tif (preparation.kind === \"immediate\") {\n\t\t\tfinalized = {\n\t\t\t\ttoolCall,\n\t\t\t\tresult: preparation.result,\n\t\t\t\tisError: preparation.isError,\n\t\t\t\texecutionOutcome: \"not_started\",\n\t\t\t};\n\t\t} else {\n\t\t\tconst executed = await executePreparedToolCall(preparation, source, \"sequential\", config, signal, emit);\n\t\t\tfinalized = await finalizeExecutedToolCall(\n\t\t\t\tcurrentContext,\n\t\t\t\tassistantMessage,\n\t\t\t\tpreparation,\n\t\t\t\texecuted,\n\t\t\t\tconfig,\n\t\t\t\tsignal,\n\t\t\t);\n\t\t}\n\n\t\tconst published = await publishToolExchange(finalized, source, \"sequential\", config, signal, emit);\n\t\tawait emitToolResultMessage(published.exchange.result, emit);\n\t\tfinalizedCalls.push(finalized);\n\t\tmessages.push(published.exchange.result);\n\t\texchanges.push(published.exchange);\n\n\t\tif (signal?.aborted || output?.refusal) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn {\n\t\tmessages,\n\t\texchanges,\n\t\ttoolExecution: \"sequential\",\n\t\tterminate: shouldTerminateToolBatch(finalizedCalls),\n\t};\n}\n\nasync function executeToolCallsParallel(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: ToolCallSource[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallBatch> {\n\tconst finalizedCalls: FinalizedToolCallEntry[] = [];\n\n\tfor (const source of toolCalls) {\n\t\tconst { toolCall } = source;\n\t\tawait emit({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\targs: toolCall.arguments,\n\t\t});\n\n\t\tconst preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);\n\t\tif (preparation.kind === \"immediate\") {\n\t\t\tconst finalized = {\n\t\t\t\ttoolCall,\n\t\t\t\tresult: preparation.result,\n\t\t\t\tisError: preparation.isError,\n\t\t\t\texecutionOutcome: \"not_started\",\n\t\t\t} satisfies FinalizedToolCallOutcome;\n\t\t\tfinalizedCalls.push(await publishToolExchange(finalized, source, \"parallel\", config, signal, emit));\n\t\t\tcontinue;\n\t\t}\n\n\t\tfinalizedCalls.push(async () => {\n\t\t\tconst executed = await executePreparedToolCall(preparation, source, \"parallel\", config, signal, emit);\n\t\t\tconst finalized = await finalizeExecutedToolCall(\n\t\t\t\tcurrentContext,\n\t\t\t\tassistantMessage,\n\t\t\t\tpreparation,\n\t\t\t\texecuted,\n\t\t\t\tconfig,\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\treturn publishToolExchange(finalized, source, \"parallel\", config, signal, emit);\n\t\t});\n\t}\n\n\t// An owner/publication failure must not abandon other invocations already started.\n\tconst settledCalls = await Promise.allSettled(\n\t\tfinalizedCalls.map((entry) => (typeof entry === \"function\" ? entry() : Promise.resolve(entry))),\n\t);\n\tconst orderedFinalizedCalls = settledCalls.flatMap((settled) =>\n\t\tsettled.status === \"fulfilled\" ? [settled.value] : [],\n\t);\n\tconst failure = settledCalls.find((settled) => settled.status === \"rejected\");\n\tconst messages: ToolResultMessage[] = [];\n\tfor (const finalized of orderedFinalizedCalls) {\n\t\tconst toolResultMessage = finalized.exchange.result;\n\t\tawait emitToolResultMessage(toolResultMessage, emit);\n\t\tmessages.push(toolResultMessage);\n\t}\n\n\tif (failure?.status === \"rejected\") throw failure.reason;\n\treturn {\n\t\tmessages,\n\t\texchanges: orderedFinalizedCalls.map((finalized) => finalized.exchange),\n\t\ttoolExecution: \"parallel\",\n\t\tterminate: shouldTerminateToolBatch(orderedFinalizedCalls),\n\t};\n}\n\ntype PreparedToolCall = {\n\tkind: \"prepared\";\n\ttoolCall: AgentToolCall;\n\ttool: AgentTool<any>;\n\targs: unknown;\n};\n\ntype ImmediateToolCallOutcome = {\n\tkind: \"immediate\";\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n};\n\ntype ExecutedToolCallOutcome = {\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n\texecutedInput?: unknown;\n\texecutionOutcome: ToolExecutionOutcome;\n};\n\ntype FinalizedToolCallOutcome = ExecutedToolCallOutcome & {\n\ttoolCall: AgentToolCall;\n};\n\ntype PublishedToolCallOutcome = FinalizedToolCallOutcome & { exchange: FinalizedToolExchange };\n\ntype FinalizedToolCallEntry = PublishedToolCallOutcome | (() => Promise<PublishedToolCallOutcome>);\n\nfunction shouldTerminateToolBatch(finalizedCalls: FinalizedToolCallOutcome[]): boolean {\n\treturn finalizedCalls.length > 0 && finalizedCalls.every((finalized) => finalized.result.terminate === true);\n}\n\nfunction prepareToolCallArguments(tool: AgentTool<any>, toolCall: AgentToolCall): AgentToolCall {\n\tif (!tool.prepareArguments) {\n\t\treturn toolCall;\n\t}\n\tconst preparedArguments = tool.prepareArguments(toolCall.arguments);\n\tif (preparedArguments === toolCall.arguments) {\n\t\treturn toolCall;\n\t}\n\treturn {\n\t\t...toolCall,\n\t\targuments: preparedArguments as Record<string, any>,\n\t};\n}\n\nasync function prepareToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCall: AgentToolCall,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<PreparedToolCall | ImmediateToolCallOutcome> {\n\tconst tool = currentContext.tools?.find((t) => t.name === toolCall.name);\n\tif (!tool) {\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(`Tool ${toolCall.name} not found`),\n\t\t\tisError: true,\n\t\t};\n\t}\n\n\ttry {\n\t\tconst preparedToolCall = prepareToolCallArguments(tool, toolCall);\n\t\tconst validatedArgs = validateToolArguments(tool, preparedToolCall);\n\t\tif (config.beforeToolCall) {\n\t\t\tconst beforeResult = await maybePromiseWithAbort(\n\t\t\t\tconfig.beforeToolCall(\n\t\t\t\t\t{\n\t\t\t\t\t\tassistantMessage,\n\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\targs: validatedArgs,\n\t\t\t\t\t\tcontext: currentContext,\n\t\t\t\t\t},\n\t\t\t\t\tsignal,\n\t\t\t\t),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (beforeResult?.block) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"immediate\",\n\t\t\t\t\tresult: createErrorToolResult(beforeResult.reason || \"Tool execution was blocked\"),\n\t\t\t\t\tisError: true,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tkind: \"prepared\",\n\t\t\ttoolCall,\n\t\t\ttool,\n\t\t\targs: validatedArgs,\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(error instanceof Error ? error.message : String(error)),\n\t\t\tisError: true,\n\t\t};\n\t}\n}\n\nasync function executePreparedToolCall(\n\tprepared: PreparedToolCall,\n\tsource: ToolCallSource,\n\ttoolExecution: ToolExecutionMode,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallOutcome> {\n\tconst invocationArgs = structuredClone(prepared.args);\n\tconst executedInput = structuredClone(invocationArgs);\n\tconst execute = prepared.tool.execute;\n\tif (!signal?.aborted) {\n\t\t// Admission failures must not become synthetic tool results or fall through to effects.\n\t\tconst owner = await config.onToolInvocationStarting?.(\n\t\t\t{\n\t\t\t\texecutionId: source.executionId,\n\t\t\t\tsourceOrder: source.sourceOrder,\n\t\t\t\ttoolCallId: prepared.toolCall.id,\n\t\t\t\ttoolName: prepared.toolCall.name,\n\t\t\t\toriginalInput: source.originalInput,\n\t\t\t\texecutedInput,\n\t\t\t\ttoolExecution,\n\t\t\t},\n\t\t\tsignal,\n\t\t\tprepared.tool,\n\t\t\texecute,\n\t\t\tsource.assistantMessage,\n\t\t);\n\t\tif (owner) source.owner = owner;\n\t}\n\tlet acceptingUpdates = true;\n\tlet pendingUpdates = 0;\n\tlet finishUpdates!: () => void;\n\tlet failUpdates!: (error: unknown) => void;\n\tconst updateEvents = new Promise<void>((resolve, reject) => {\n\t\tfinishUpdates = resolve;\n\t\tfailUpdates = reject;\n\t});\n\t// Observe early failures now; the normal execution path still awaits and reports them.\n\tvoid updateEvents.catch(() => undefined);\n\tconst settleUpdate = () => {\n\t\tpendingUpdates--;\n\t\tif (!acceptingUpdates && pendingUpdates === 0) finishUpdates();\n\t};\n\tconst stopUpdates = () => {\n\t\tacceptingUpdates = false;\n\t\tif (pendingUpdates === 0) finishUpdates();\n\t};\n\tlet executionStarted = false;\n\n\ttry {\n\t\tthrowIfAborted(signal);\n\t\texecutionStarted = true;\n\t\tconst run = () =>\n\t\t\texecute.call(prepared.tool, prepared.toolCall.id, invocationArgs as never, signal, (partialResult) => {\n\t\t\t\tif (!acceptingUpdates || signal?.aborted) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst update = Promise.resolve(\n\t\t\t\t\temit({\n\t\t\t\t\t\ttype: \"tool_execution_update\",\n\t\t\t\t\t\ttoolCallId: prepared.toolCall.id,\n\t\t\t\t\t\ttoolName: prepared.toolCall.name,\n\t\t\t\t\t\targs: prepared.toolCall.arguments,\n\t\t\t\t\t\tpartialResult,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\t// Do not retain every stdout callback or feed an unbounded array to Promise.all.\n\t\t\t\tpendingUpdates++;\n\t\t\t\tvoid update.then(settleUpdate, (error) => {\n\t\t\t\t\tfailUpdates(error);\n\t\t\t\t\tsettleUpdate();\n\t\t\t\t});\n\t\t\t});\n\t\tconst result = await raceWithAbort(source.owner ? source.owner.run(run) : run(), signal);\n\t\tstopUpdates();\n\t\ttry {\n\t\t\tawait raceWithAbort(updateEvents, signal);\n\t\t} catch (error) {\n\t\t\tif (!signal?.aborted || !isAbortError(error)) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\treturn { result, isError: result.isError ?? false, executedInput, executionOutcome: \"completed\" };\n\t} catch (error) {\n\t\tstopUpdates();\n\t\tawait raceWithAbort(updateEvents, signal).catch(() => undefined);\n\t\treturn {\n\t\t\tresult: createErrorToolResult(\n\t\t\t\tsignal?.aborted ? \"Tool execution aborted\" : error instanceof Error ? error.message : String(error),\n\t\t\t),\n\t\t\tisError: true,\n\t\t\t...(executionStarted ? { executedInput } : {}),\n\t\t\texecutionOutcome: !executionStarted ? \"not_started\" : signal?.aborted ? \"outcome_unknown\" : \"failed\",\n\t\t};\n\t}\n}\n\nasync function finalizeExecutedToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tprepared: PreparedToolCall,\n\texecuted: ExecutedToolCallOutcome,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<FinalizedToolCallOutcome> {\n\tlet result = executed.result;\n\tlet isError = executed.isError;\n\n\tif (config.afterToolCall) {\n\t\ttry {\n\t\t\tconst afterResult = await maybePromiseWithAbort(\n\t\t\t\tconfig.afterToolCall(\n\t\t\t\t\t{\n\t\t\t\t\t\tassistantMessage,\n\t\t\t\t\t\ttoolCall: prepared.toolCall,\n\t\t\t\t\t\targs: prepared.args,\n\t\t\t\t\t\tresult,\n\t\t\t\t\t\tisError,\n\t\t\t\t\t\tcontext: currentContext,\n\t\t\t\t\t},\n\t\t\t\t\tsignal,\n\t\t\t\t),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (afterResult) {\n\t\t\t\tresult = {\n\t\t\t\t\tcontent: afterResult.content ?? result.content,\n\t\t\t\t\tdetails: afterResult.details ?? result.details,\n\t\t\t\t\tterminate: afterResult.terminate ?? result.terminate,\n\t\t\t\t};\n\t\t\t\tisError = afterResult.isError ?? isError;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tresult = createErrorToolResult(error instanceof Error ? error.message : String(error));\n\t\t\tisError = true;\n\t\t}\n\t}\n\n\treturn {\n\t\t...executed,\n\t\ttoolCall: prepared.toolCall,\n\t\tresult,\n\t\tisError,\n\t};\n}\n\nfunction createErrorToolResult(message: string): AgentToolResult<any> {\n\treturn {\n\t\tcontent: [{ type: \"text\", text: message }],\n\t\tdetails: {},\n\t};\n}\n\nasync function publishToolExchange(\n\tfinalized: FinalizedToolCallOutcome,\n\tsource: ToolCallSource,\n\ttoolExecution: ToolExecutionMode,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<PublishedToolCallOutcome> {\n\tconst exchange: FinalizedToolExchange = {\n\t\texecutionId: source.executionId,\n\t\tsourceOrder: source.sourceOrder,\n\t\ttoolCallId: finalized.toolCall.id,\n\t\ttoolName: finalized.toolCall.name,\n\t\toriginalInput: source.originalInput,\n\t\t...(finalized.executionOutcome === \"not_started\" ? {} : { executedInput: finalized.executedInput }),\n\t\ttoolExecution,\n\t\texecutionOutcome: finalized.executionOutcome,\n\t\tcancellationRequested: signal?.aborted ?? false,\n\t\tresult: createToolResultMessage(finalized),\n\t};\n\tawait config.onToolExchangeFinalized?.(exchange, signal, source.owner);\n\tawait emit({\n\t\ttype: \"tool_execution_end\",\n\t\ttoolCallId: finalized.toolCall.id,\n\t\ttoolName: finalized.toolCall.name,\n\t\tresult: finalized.result,\n\t\tisError: finalized.isError,\n\t\texchange,\n\t});\n\treturn { ...finalized, exchange };\n}\n\nfunction createToolResultMessage(finalized: FinalizedToolCallOutcome): ToolResultMessage {\n\treturn {\n\t\trole: \"toolResult\",\n\t\ttoolCallId: finalized.toolCall.id,\n\t\ttoolName: finalized.toolCall.name,\n\t\tcontent: finalized.result.content,\n\t\tdetails: finalized.result.details,\n\t\tisError: finalized.isError,\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nasync function emitToolResultMessage(toolResultMessage: ToolResultMessage, emit: AgentEventSink): Promise<void> {\n\tawait emit({ type: \"message_start\", message: toolResultMessage });\n\tawait emit({ type: \"message_end\", message: toolResultMessage });\n}\n"]}
@@ -1,13 +1,13 @@
1
1
  {
2
- "sourceCommit": "3da00112a267d34bb304f74ff0f854c0f5548b17",
2
+ "sourceCommit": "22f815fbf324ca4df1a886c8e71c819d765caba1",
3
3
  "sourceDirty": false,
4
4
  "buildHost": {
5
5
  "platform": "linux",
6
6
  "arch": "x64"
7
7
  },
8
8
  "toolchain": {
9
- "node": "v22.12.0",
10
- "npm": "10.9.0",
9
+ "node": "v22.22.1",
10
+ "npm": "11.19.0",
11
11
  "tsgo": "Version 7.0.0-dev.20260120.1",
12
12
  "esbuild": "0.28.1"
13
13
  }
package/dist/types.d.ts CHANGED
@@ -405,6 +405,8 @@ export interface AgentToolResult<T> {
405
405
  content: (TextContent | ImageContent)[];
406
406
  /** Structured details for logs or UI rendering. */
407
407
  details: T;
408
+ /** Whether the tool reported an error. Defaults to false. */
409
+ isError?: boolean;
408
410
  /**
409
411
  * Hint that the agent should stop after the current tool batch.
410
412
  * Early termination only happens when every finalized tool result in the batch sets this to true.
@@ -422,7 +424,7 @@ export interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any
422
424
  * Must return an object that matches `TParameters`.
423
425
  */
424
426
  prepareArguments?: (args: unknown) => Static<TParameters>;
425
- /** Execute the tool call. Throw on failure instead of encoding errors in `content`. */
427
+ /** Execute the tool call. Throw on failure or return a result with `isError: true`. */
426
428
  execute: (toolCallId: string, params: Static<TParameters>, signal?: AbortSignal, onUpdate?: AgentToolUpdateCallback<TDetails>) => Promise<AgentToolResult<TDetails>>;
427
429
  /**
428
430
  * Per-tool execution mode override.
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,gBAAgB,EAChB,qBAAqB,EACrB,YAAY,EACZ,OAAO,EACP,KAAK,EACL,WAAW,EACX,mBAAmB,EACnB,YAAY,EACZ,WAAW,EACX,IAAI,EACJ,iBAAiB,EACjB,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAE/C;;;;;;;;GAQG;AACH,MAAM,MAAM,QAAQ,GAAG,CACtB,GAAG,IAAI,EAAE,UAAU,CAAC,OAAO,YAAY,CAAC,KACpC,UAAU,CAAC,OAAO,YAAY,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC,CAAC;AAEhF,MAAM,WAAW,sBAAsB;IACtC,QAAQ,EAAE,YAAY,EAAE,CAAC;IACzB;;;;OAIG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,OAAO,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9B;AAGD,MAAM,MAAM,uBAAuB,GAAG,IAAI,GAAG,sBAAsB,CAAC;AAEpE,MAAM,MAAM,kBAAkB,GAAG,CAAC,GAAG,IAAI,EAAE,CAAC,GAAG,UAAU,CAAC,QAAQ,CAAC,EAAE,aAAa,CAAC,EAAE,OAAO,CAAC,KAAK,UAAU,CAAC,QAAQ,CAAC,CAAC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M,CAAC;IAAC,IAAI,EAAE,GAAG,CAAC;IAAC,aAAa,EAAE,GAAG,CAAA;CAAE,GACtG;IACA,IAAI,EAAE,oBAAoB,CAAC;IAC3B,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,GAAG,CAAC;IACZ,OAAO,EAAE,OAAO,CAAC;IACjB,8EAA8E;IAC9E,QAAQ,CAAC,EAAE,qBAAqB,CAAC;CAChC,CAAC","sourcesContent":["import type {\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tImageContent,\n\tMessage,\n\tModel,\n\tServiceTier,\n\tSimpleStreamOptions,\n\tstreamSimple,\n\tTextContent,\n\tTool,\n\tToolResultMessage,\n} from \"@ponythewhite/base-context-ai\";\nimport type { Static, TSchema } from \"typebox\";\n\n/**\n * Stream function used by the agent loop.\n *\n * Contract:\n * - Must not throw or return a rejected promise for request/model/runtime failures.\n * - Must return an AssistantMessageEventStream.\n * - Failures must be encoded in the returned stream via protocol events and a\n * final AssistantMessage with stopReason \"error\" or \"aborted\" and errorMessage.\n */\nexport type StreamFn = (\n\t...args: Parameters<typeof streamSimple>\n) => ReturnType<typeof streamSimple> | Promise<ReturnType<typeof streamSimple>>;\n\nexport interface AgentContextProjection {\n\tmessages: AgentMessage[];\n\t/**\n\t * Adopt this complete working set in the owning Agent and loop, not only for inference.\n\t * It must include the current turn and pending tool closure. This is not a last-N tail.\n\t * Omitted/false preserves the existing inference-only projection behavior.\n\t */\n\tadoptMessages?: boolean;\n\tstreamContext?: unknown;\n\trelease?: () => Promise<void>;\n}\n\n// biome-ignore lint/suspicious/noConfusingVoidType: this return contract accepts existing Promise<void> context barriers.\nexport type AgentContextBuildResult = void | AgentContextProjection;\n\nexport type AgentOwnedStreamFn = (...args: [...Parameters<StreamFn>, streamContext?: unknown]) => ReturnType<StreamFn>;\n\n/**\n * Configuration for how tool calls from a single assistant message are executed.\n *\n * - \"sequential\": each tool call is prepared, executed, and finalized before the next one starts.\n * - \"parallel\": tool calls are prepared sequentially, then allowed tools execute concurrently.\n * `tool_execution_end` is emitted in tool completion order after each tool is finalized,\n * while tool-result message artifacts are emitted later in assistant source order.\n */\nexport type ToolExecutionMode = \"sequential\" | \"parallel\";\n\n/** A tool-call content block emitted by an assistant message. */\nexport type AgentToolCall = Extract<AssistantMessage[\"content\"][number], { type: \"toolCall\" }>;\n\n/**\n * Result returned from `beforeToolCall`.\n *\n * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.\n * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.\n */\nexport interface BeforeToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n}\n\n/**\n * Partial override returned from `afterToolCall`.\n *\n * Merge semantics are field-by-field:\n * - `content`: if provided, replaces the tool result content array in full\n * - `details`: if provided, replaces the tool result details value in full\n * - `isError`: if provided, replaces the tool result error flag\n * - `terminate`: if provided, replaces the early-termination hint\n *\n * Omitted fields keep the original executed tool result values.\n * There is no deep merge for `content` or `details`.\n */\nexport interface AfterToolCallResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tisError?: boolean;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Context passed to `beforeToolCall` after arguments are validated. */\nexport interface BeforeToolCallContext {\n\t/** Assistant message that requested the call. */\n\tassistantMessage: AssistantMessage;\n\t/** Raw tool-call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated arguments for the target tool schema. */\n\targs: unknown;\n\t/** Agent context when this call is prepared. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `afterToolCall`. */\nexport interface AfterToolCallContext {\n\t/** Assistant message that requested the call. */\n\tassistantMessage: AssistantMessage;\n\t/** Raw tool-call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated arguments for the target tool schema. */\n\targs: unknown;\n\t/** Executed result before any `afterToolCall` overrides. */\n\tresult: AgentToolResult<any>;\n\t/** Whether the executed result is currently treated as an error. */\n\tisError: boolean;\n\t/** Agent context when this call is finalized. */\n\tcontext: AgentContext;\n}\n\n/** What is known about the actual invocation, independently of middleware result overrides. */\nexport type ToolExecutionOutcome = \"not_started\" | \"completed\" | \"failed\" | \"outcome_unknown\";\n\n/** Immutable invocation admitted by the execution owner before the tool can run. */\nexport interface ToolInvocation {\n\treadonly executionId: string;\n\treadonly sourceOrder: number;\n\treadonly toolCallId: string;\n\treadonly toolName: string;\n\t/** Snapshot before argument preparation, validation, or tool middleware. */\n\treadonly originalInput: unknown;\n\t/** Arguments reserved for this invocation, not a live middleware object. */\n\treadonly executedInput: unknown;\n\treadonly toolExecution: ToolExecutionMode;\n}\n\n/** @internal Per-invocation owner closure; never serialized or supplied by result metadata. */\nexport interface BoundToolExecution {\n\trun(execute: () => Promise<AgentToolResult<unknown>>): Promise<AgentToolResult<unknown>>;\n\tfinalize(exchange: FinalizedToolExchange, signal?: AbortSignal): void | Promise<void>;\n}\n\n/** Finalized source evidence; parallel exchanges retain assistant call order via sourceOrder. */\nexport interface FinalizedToolExchange extends Omit<ToolInvocation, \"executedInput\"> {\n\t/** Snapshot at invocation; absent when execution never started. */\n\treadonly executedInput?: unknown;\n\t/** An aborted wait does not establish whether an external effect stopped. */\n\treadonly executionOutcome: ToolExecutionOutcome;\n\treadonly cancellationRequested: boolean;\n\t/** Final middleware result, also used for the tool-result message. */\n\treadonly result: ToolResultMessage;\n}\n\n/** Limits on the complete invocation result, not the working context or observer queues. */\nexport interface AgentOutputLimits {\n\tmaxMessages: number;\n\tmaxSourceBytes: number;\n}\n\nexport interface AgentOutputRefusal extends AgentOutputLimits {\n\tkind: \"output_limit\";\n\tlimit: \"messages\" | \"source_bytes\" | \"value_encoding\";\n}\n\nexport interface AgentOutputPolicy {\n\tlimits: AgentOutputLimits;\n\t/** Optional native update feed. Its synchronous refresh never revokes an ACK or throws a quota error. */\n\tbindUpdates?(refresh: (message: AgentMessage) => boolean): () => void;\n\t/** Close update admission and join the updates already accepted at this terminal boundary. */\n\tsettleUpdates?(): Promise<void>;\n\t/** Copy one finalized value within the supplied JSON-byte budget; undefined means it does not fit. */\n\tsnapshot(message: AgentMessage, maxSourceBytes: number): { message: AgentMessage; sourceBytes: number } | undefined;\n}\n\n/** Context passed to `shouldStopAfterTurn` and both continuation callbacks. */\nexport interface ShouldStopAfterTurnContext {\n\t/** Assistant message that completed the turn. */\n\tmessage: AssistantMessage;\n\t/** Tool-result messages included in the preceding `turn_end` event. */\n\ttoolResults: ToolResultMessage[];\n\t/** Context after appending the turn's assistant message and tool results. */\n\tcontext: AgentContext;\n\t/** Messages returned by this invocation; prompts include initial prompts, continuations exclude prior context. */\n\tnewMessages: AgentMessage[];\n}\n\n/** The finalized loop decision, not a guess from the rendered message tail. */\nexport interface GetTurnOutcomeContext extends ShouldStopAfterTurnContext {\n\thasMoreToolCalls: boolean;\n}\n\n/** Control before queue polling; proceed keeps the ordinary loop policy. */\nexport type AgentTurnOutcome = { kind: \"proceed\" | \"finish\" | \"checkpoint_then_continue\" | \"cancelled\" };\n\nexport type GetContinuationMessagesContext = ShouldStopAfterTurnContext;\n\n/** Runtime control at a natural turn boundary; message payload does not decide whether to restart. */\nexport type AgentContinuationOutcome =\n\t| { kind: \"continue\"; messages: AgentMessage[] }\n\t| { kind: \"finish\" | \"wait_for_owned_work\" | \"cancelled\" };\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\t/** Opt-in bounded finalized results. Native sinks must join their message_end job. */\n\toutputPolicy?: AgentOutputPolicy;\n\tmodel: Model<any>;\n\n\t/** Native owner barrier before transform/convert. Rejection stops context construction. */\n\tbeforeContextBuild?: () => Promise<AgentContextBuildResult>;\n\n\t/** Internal state mirror for adopted working sets. Awaited and excluded from provider options. */\n\tonContextAdopted?: (messages: AgentMessage[]) => void | Promise<void>;\n\n\t/** Native owner recovery after release. One deterministic reprepare may precede one recovery. */\n\trecoverRequestPreparation?: (error: unknown, signal?: AbortSignal) => Promise<boolean | \"reprepare\">;\n\n\t/** Retry a settled provider failure within this invocation and its output allowance. */\n\trecoverProviderFailure?: (message: AssistantMessage, signal?: AbortSignal) => Promise<boolean>;\n\n\t/** Copied native owner callback; excluded from configured/provider stream options. */\n\townedStreamFn?: AgentOwnedStreamFn;\n\n\t/**\n\t * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.\n\t *\n\t * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage\n\t * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,\n\t * status messages) should be filtered out.\n\t *\n\t * Contract: must not throw or reject. Return a safe fallback value instead.\n\t * Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t *\n\t * @example\n\t * ```typescript\n\t * convertToLlm: (messages) => messages.flatMap(m => {\n\t * if (m.role === \"custom\") {\n\t * // Convert custom message to user message\n\t * return [{ role: \"user\", content: m.content, timestamp: m.timestamp }];\n\t * }\n\t * if (m.role === \"notification\") {\n\t * // Filter out UI-only messages\n\t * return [];\n\t * }\n\t * // Pass through standard LLM messages\n\t * return [m];\n\t * })\n\t * ```\n\t */\n\tconvertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\n\t/**\n\t * Optional transform applied to the context before `convertToLlm`.\n\t *\n\t * Use this for operations that work at the AgentMessage level:\n\t * - Context window management (pruning old messages)\n\t * - Injecting context from external sources\n\t *\n\t * Contract: must not throw or reject. Return the original messages or another\n\t * safe fallback value instead.\n\t *\n\t * @example\n\t * ```typescript\n\t * transformContext: async (messages) => {\n\t * if (estimateTokens(messages) > MAX_TOKENS) {\n\t * return pruneOldMessages(messages);\n\t * }\n\t * return messages;\n\t * }\n\t * ```\n\t */\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/** Resolves the system prompt immediately before each LLM call. */\n\tgetSystemPrompt?: () => string;\n\n\t/**\n\t * Resolves an API key dynamically for each LLM call.\n\t *\n\t * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire\n\t * during long-running tool execution phases.\n\t *\n\t * Contract: must not throw or reject. Return undefined when no key is available.\n\t */\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\n\t/**\n\t * Called after each turn fully completes and `turn_end` has been emitted.\n\t *\n\t * If it returns true, the loop emits `agent_end` and exits before polling steering or follow-up queues,\n\t * without starting another LLM call. The current assistant response and any tool executions finish normally.\n\t *\n\t * Use this to request a graceful stop after the current turn, e.g. before context gets too full.\n\t *\n\t * Contract: must not throw or reject. Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t */\n\tshouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;\n\n\t/** When present, this typed owner replaces shouldStopAfterTurn; it does not replace natural continuation. */\n\tgetTurnOutcome?: (\n\t\tcontext: GetTurnOutcomeContext,\n\t\tsignal?: AbortSignal,\n\t) => AgentTurnOutcome | Promise<AgentTurnOutcome>;\n\n\t/**\n\t * Called synchronously after a completed turn and before polling work for another turn.\n\t * Return true to emit `agent_end` without starting another provider call. Work returned by\n\t * an asynchronous poll owns that boundary; queue owners must suppress stale continuation\n\t * results if their higher-level stop condition changes while generating them.\n\t * The hook is never checked before the initial assistant turn.\n\t */\n\tshouldStopBeforeTurn?: () => boolean;\n\n\t/**\n\t * Returns steering messages to inject into the conversation mid-run.\n\t *\n\t * Called after the current assistant turn finishes executing its tool calls, unless `shouldStopAfterTurn` exits first.\n\t * If messages are returned, they are added to the context before the next LLM call.\n\t * Tool calls from the current assistant message are not skipped.\n\t *\n\t * Use this for \"steering\" the agent while it's working.\n\t *\n\t * Contract: must not throw or reject. Return [] when no steering messages are available.\n\t */\n\tgetSteeringMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns follow-up messages to process after the agent would otherwise stop.\n\t *\n\t * Called when the agent has no more tool calls and no steering messages.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for follow-up messages that should wait until the agent finishes.\n\t *\n\t * Contract: must not throw or reject. Return [] when no follow-up messages are available.\n\t */\n\tgetFollowUpMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns continuation messages when the agent would otherwise stop.\n\t *\n\t * Called after follow-up messages have been polled and none are available.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for host-owned continuation policies such as long-running goals.\n\t * Explicit follow-up messages always take precedence over continuation messages.\n\t *\n\t * Contract: must not throw or reject. Return [] when no continuation should run.\n\t */\n\tgetContinuationMessages?: (context: GetContinuationMessagesContext, signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/**\n\t * Authoritative runtime continuation control, after steering and explicit follow-ups.\n\t * When present, only this callback is called; getContinuationMessages is not polled.\n\t * Only continue restarts this invocation. Waiting leaves future work with its existing owner.\n\t */\n\tgetContinuationOutcome?: (\n\t\tcontext: GetContinuationMessagesContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentContinuationOutcome>;\n\n\t/**\n\t * Tool execution mode. Defaults to `\"parallel\"`.\n\t * Parallel mode preflights calls sequentially, executes allowed calls concurrently, emits\n\t * `tool_execution_end` in completion order, then emits tool-result messages in assistant source order.\n\t */\n\ttoolExecution?: ToolExecutionMode;\n\n\t/**\n\t * Awaited before invoking the tool. Rejection prevents execution and stops the loop.\n\t * The owner records intent here; admission is not proof that an external effect occurred.\n\t */\n\tonToolInvocationStarting?: (\n\t\tinvocation: ToolInvocation,\n\t\tsignal: AbortSignal | undefined,\n\t\ttool: AgentTool,\n\t\texecute: AgentTool[\"execute\"],\n\t\tassistantMessage?: AssistantMessage,\n\t) => void | BoundToolExecution | Promise<void> | Promise<BoundToolExecution | undefined>;\n\n\t/**\n\t * Native execution owner, awaited after final middleware and before observer/result events.\n\t * Persist source evidence here. Rejection stops publication; this is not an observer hook.\n\t * Cancellation does not skip settlement. The owner must bound its own persistence work.\n\t */\n\tonToolExchangeFinalized?: (\n\t\texchange: FinalizedToolExchange,\n\t\tsignal?: AbortSignal,\n\t\towner?: BoundToolExecution,\n\t) => void | Promise<void>;\n\n\t/**\n\t * Called before a tool is executed, after arguments have been validated.\n\t *\n\t * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\n\t/**\n\t * Called after a tool finishes executing, before `tool_execution_end` and tool-result message events are emitted.\n\t *\n\t * Return an `AfterToolCallResult` to override parts of the executed tool result:\n\t * - `content` replaces the full content array\n\t * - `details` replaces the full details payload\n\t * - `isError` replaces the error flag\n\t * - `terminate` replaces the early-termination hint\n\t *\n\t * Any omitted fields keep their original values. No deep merge is performed.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n}\n\n/**\n * Thinking/reasoning level for models that support it.\n * Note: \"xhigh\" and \"max\" are only supported by selected model families. Use model\n * thinking-level metadata from @ponythewhite/base-context-ai to detect support for a concrete model.\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n/**\n * Extensible interface for custom app messages.\n * Apps can extend via declaration merging:\n *\n * @example\n * ```typescript\n * declare module \"@mariozechner/agent\" {\n * interface CustomAgentMessages {\n * artifact: ArtifactMessage;\n * notification: NotificationMessage;\n * }\n * }\n * ```\n */\nexport interface CustomAgentMessages {}\n\nexport type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];\n\n/**\n * Public agent state.\n *\n * `tools` and `messages` use accessor properties so implementations can copy\n * assigned arrays before storing them.\n */\nexport interface AgentState {\n\t/** System prompt sent with each model request. */\n\tsystemPrompt: string;\n\t/** Model used for future turns. */\n\tmodel: Model<any> | undefined;\n\t/** Requested reasoning level for future turns. */\n\tthinkingLevel: ThinkingLevel;\n\t/** Requested provider service tier for future turns. */\n\tserviceTier: ServiceTier;\n\t/** Available tools. Assigning a new array copies its top-level array. */\n\tset tools(tools: AgentTool<any>[]);\n\tget tools(): AgentTool<any>[];\n\t/** Conversation transcript. Assigning a new array copies its top-level array. */\n\tset messages(messages: AgentMessage[]);\n\tget messages(): AgentMessage[];\n\t/** True while processing a prompt or continuation, including awaited `agent_end` listeners. */\n\treadonly isStreaming: boolean;\n\t/** Partial assistant message for the active streamed response, if any. */\n\treadonly streamingMessage?: AgentMessage;\n\t/** Tool-call IDs currently executing. */\n\treadonly pendingToolCalls: ReadonlySet<string>;\n\t/** Error from the most recent failed or aborted assistant turn, if any. */\n\treadonly errorMessage?: string;\n}\n\n/** Final or partial result produced by a tool. */\nexport interface AgentToolResult<T> {\n\t/** Text or image content returned to the model. */\n\tcontent: (TextContent | ImageContent)[];\n\t/** Structured details for logs or UI rendering. */\n\tdetails: T;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Callback used by tools to publish partial execution updates. */\nexport type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;\n\n/** Tool definition used by the agent runtime. */\nexport interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {\n\t/** Human-readable label for UI display. */\n\tlabel: string;\n\t/**\n\t * Optional compatibility shim for raw tool-call arguments before schema validation.\n\t * Must return an object that matches `TParameters`.\n\t */\n\tprepareArguments?: (args: unknown) => Static<TParameters>;\n\t/** Execute the tool call. Throw on failure instead of encoding errors in `content`. */\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: Static<TParameters>,\n\t\tsignal?: AbortSignal,\n\t\tonUpdate?: AgentToolUpdateCallback<TDetails>,\n\t) => Promise<AgentToolResult<TDetails>>;\n\t/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool must execute one at a time with other tool calls.\n\t * - \"parallel\": this tool can execute concurrently with other tool calls.\n\t *\n\t * If omitted, the default execution mode applies.\n\t */\n\texecutionMode?: ToolExecutionMode;\n}\n\n/** Context snapshot passed to the low-level agent loop and tool hooks. */\nexport interface AgentContext {\n\t/** System prompt included with the request. */\n\tsystemPrompt: string;\n\t/** Transcript visible to the model. */\n\tmessages: AgentMessage[];\n\t/** Tools available for this run. */\n\ttools?: AgentTool<any>[];\n}\n\n/**\n * Events emitted by the Agent for UI updates.\n *\n * `agent_end` is the last event emitted for a run, but awaited `Agent.subscribe()`\n * listeners for that event are still part of run settlement. The agent becomes\n * idle only after those listeners finish.\n */\nexport type AgentEvent =\n\t/** Starts and ends one agent run; `agent_end` carries all messages produced by that run. */\n\t| { type: \"agent_start\" }\n\t| { type: \"agent_end\"; messages: AgentMessage[]; refusal?: never }\n\t| { type: \"agent_end\"; refusal: AgentOutputRefusal; messages?: never }\n\t/** One assistant response and its resulting tool calls. */\n\t| { type: \"turn_start\" }\n\t| {\n\t\t\ttype: \"turn_end\";\n\t\t\tmessage: AgentMessage;\n\t\t\ttoolResults: ToolResultMessage[];\n\t\t\t/** Always populated by native execution; historical observer events may omit it. */\n\t\t\ttoolExecution?: ToolExecutionMode;\n\t\t\t/** Settled calls in source order. Absent historical evidence is not reconstructed. */\n\t\t\texchanges?: readonly FinalizedToolExchange[];\n\t }\n\t/** Lifecycle events for user, assistant, and tool-result messages. */\n\t| { type: \"message_start\"; message: AgentMessage }\n\t/** Only emitted for assistant messages during streaming. */\n\t| { type: \"message_update\"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }\n\t| { type: \"message_end\"; message: AgentMessage }\n\t/** Tool execution events; parallel calls may end in completion rather than source order. */\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: any }\n\t| { type: \"tool_execution_update\"; toolCallId: string; toolName: string; args: any; partialResult: any }\n\t| {\n\t\t\ttype: \"tool_execution_end\";\n\t\t\ttoolCallId: string;\n\t\t\ttoolName: string;\n\t\t\tresult: any;\n\t\t\tisError: boolean;\n\t\t\t/** Always populated by native execution; absent for older observer events. */\n\t\t\texchange?: FinalizedToolExchange;\n\t };\n"]}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,gBAAgB,EAChB,qBAAqB,EACrB,YAAY,EACZ,OAAO,EACP,KAAK,EACL,WAAW,EACX,mBAAmB,EACnB,YAAY,EACZ,WAAW,EACX,IAAI,EACJ,iBAAiB,EACjB,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAE/C;;;;;;;;GAQG;AACH,MAAM,MAAM,QAAQ,GAAG,CACtB,GAAG,IAAI,EAAE,UAAU,CAAC,OAAO,YAAY,CAAC,KACpC,UAAU,CAAC,OAAO,YAAY,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC,CAAC;AAEhF,MAAM,WAAW,sBAAsB;IACtC,QAAQ,EAAE,YAAY,EAAE,CAAC;IACzB;;;;OAIG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,OAAO,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9B;AAGD,MAAM,MAAM,uBAAuB,GAAG,IAAI,GAAG,sBAAsB,CAAC;AAEpE,MAAM,MAAM,kBAAkB,GAAG,CAAC,GAAG,IAAI,EAAE,CAAC,GAAG,UAAU,CAAC,QAAQ,CAAC,EAAE,aAAa,CAAC,EAAE,OAAO,CAAC,KAAK,UAAU,CAAC,QAAQ,CAAC,CAAC;AAEvH;;;;;;;GAOG;AACH,MAAM,MAAM,iBAAiB,GAAG,YAAY,GAAG,UAAU,CAAC;AAE1D,iEAAiE;AACjE,MAAM,MAAM,aAAa,GAAG,OAAO,CAAC,gBAAgB,CAAC,SAAS,CAAC,CA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IAC3B,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,GAAG,CAAC;IACZ,OAAO,EAAE,OAAO,CAAC;IACjB,8EAA8E;IAC9E,QAAQ,CAAC,EAAE,qBAAqB,CAAC;CAChC,CAAC","sourcesContent":["import type {\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tImageContent,\n\tMessage,\n\tModel,\n\tServiceTier,\n\tSimpleStreamOptions,\n\tstreamSimple,\n\tTextContent,\n\tTool,\n\tToolResultMessage,\n} from \"@ponythewhite/base-context-ai\";\nimport type { Static, TSchema } from \"typebox\";\n\n/**\n * Stream function used by the agent loop.\n *\n * Contract:\n * - Must not throw or return a rejected promise for request/model/runtime failures.\n * - Must return an AssistantMessageEventStream.\n * - Failures must be encoded in the returned stream via protocol events and a\n * final AssistantMessage with stopReason \"error\" or \"aborted\" and errorMessage.\n */\nexport type StreamFn = (\n\t...args: Parameters<typeof streamSimple>\n) => ReturnType<typeof streamSimple> | Promise<ReturnType<typeof streamSimple>>;\n\nexport interface AgentContextProjection {\n\tmessages: AgentMessage[];\n\t/**\n\t * Adopt this complete working set in the owning Agent and loop, not only for inference.\n\t * It must include the current turn and pending tool closure. This is not a last-N tail.\n\t * Omitted/false preserves the existing inference-only projection behavior.\n\t */\n\tadoptMessages?: boolean;\n\tstreamContext?: unknown;\n\trelease?: () => Promise<void>;\n}\n\n// biome-ignore lint/suspicious/noConfusingVoidType: this return contract accepts existing Promise<void> context barriers.\nexport type AgentContextBuildResult = void | AgentContextProjection;\n\nexport type AgentOwnedStreamFn = (...args: [...Parameters<StreamFn>, streamContext?: unknown]) => ReturnType<StreamFn>;\n\n/**\n * Configuration for how tool calls from a single assistant message are executed.\n *\n * - \"sequential\": each tool call is prepared, executed, and finalized before the next one starts.\n * - \"parallel\": tool calls are prepared sequentially, then allowed tools execute concurrently.\n * `tool_execution_end` is emitted in tool completion order after each tool is finalized,\n * while tool-result message artifacts are emitted later in assistant source order.\n */\nexport type ToolExecutionMode = \"sequential\" | \"parallel\";\n\n/** A tool-call content block emitted by an assistant message. */\nexport type AgentToolCall = Extract<AssistantMessage[\"content\"][number], { type: \"toolCall\" }>;\n\n/**\n * Result returned from `beforeToolCall`.\n *\n * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.\n * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.\n */\nexport interface BeforeToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n}\n\n/**\n * Partial override returned from `afterToolCall`.\n *\n * Merge semantics are field-by-field:\n * - `content`: if provided, replaces the tool result content array in full\n * - `details`: if provided, replaces the tool result details value in full\n * - `isError`: if provided, replaces the tool result error flag\n * - `terminate`: if provided, replaces the early-termination hint\n *\n * Omitted fields keep the original executed tool result values.\n * There is no deep merge for `content` or `details`.\n */\nexport interface AfterToolCallResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tisError?: boolean;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Context passed to `beforeToolCall` after arguments are validated. */\nexport interface BeforeToolCallContext {\n\t/** Assistant message that requested the call. */\n\tassistantMessage: AssistantMessage;\n\t/** Raw tool-call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated arguments for the target tool schema. */\n\targs: unknown;\n\t/** Agent context when this call is prepared. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `afterToolCall`. */\nexport interface AfterToolCallContext {\n\t/** Assistant message that requested the call. */\n\tassistantMessage: AssistantMessage;\n\t/** Raw tool-call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated arguments for the target tool schema. */\n\targs: unknown;\n\t/** Executed result before any `afterToolCall` overrides. */\n\tresult: AgentToolResult<any>;\n\t/** Whether the executed result is currently treated as an error. */\n\tisError: boolean;\n\t/** Agent context when this call is finalized. */\n\tcontext: AgentContext;\n}\n\n/** What is known about the actual invocation, independently of middleware result overrides. */\nexport type ToolExecutionOutcome = \"not_started\" | \"completed\" | \"failed\" | \"outcome_unknown\";\n\n/** Immutable invocation admitted by the execution owner before the tool can run. */\nexport interface ToolInvocation {\n\treadonly executionId: string;\n\treadonly sourceOrder: number;\n\treadonly toolCallId: string;\n\treadonly toolName: string;\n\t/** Snapshot before argument preparation, validation, or tool middleware. */\n\treadonly originalInput: unknown;\n\t/** Arguments reserved for this invocation, not a live middleware object. */\n\treadonly executedInput: unknown;\n\treadonly toolExecution: ToolExecutionMode;\n}\n\n/** @internal Per-invocation owner closure; never serialized or supplied by result metadata. */\nexport interface BoundToolExecution {\n\trun(execute: () => Promise<AgentToolResult<unknown>>): Promise<AgentToolResult<unknown>>;\n\tfinalize(exchange: FinalizedToolExchange, signal?: AbortSignal): void | Promise<void>;\n}\n\n/** Finalized source evidence; parallel exchanges retain assistant call order via sourceOrder. */\nexport interface FinalizedToolExchange extends Omit<ToolInvocation, \"executedInput\"> {\n\t/** Snapshot at invocation; absent when execution never started. */\n\treadonly executedInput?: unknown;\n\t/** An aborted wait does not establish whether an external effect stopped. */\n\treadonly executionOutcome: ToolExecutionOutcome;\n\treadonly cancellationRequested: boolean;\n\t/** Final middleware result, also used for the tool-result message. */\n\treadonly result: ToolResultMessage;\n}\n\n/** Limits on the complete invocation result, not the working context or observer queues. */\nexport interface AgentOutputLimits {\n\tmaxMessages: number;\n\tmaxSourceBytes: number;\n}\n\nexport interface AgentOutputRefusal extends AgentOutputLimits {\n\tkind: \"output_limit\";\n\tlimit: \"messages\" | \"source_bytes\" | \"value_encoding\";\n}\n\nexport interface AgentOutputPolicy {\n\tlimits: AgentOutputLimits;\n\t/** Optional native update feed. Its synchronous refresh never revokes an ACK or throws a quota error. */\n\tbindUpdates?(refresh: (message: AgentMessage) => boolean): () => void;\n\t/** Close update admission and join the updates already accepted at this terminal boundary. */\n\tsettleUpdates?(): Promise<void>;\n\t/** Copy one finalized value within the supplied JSON-byte budget; undefined means it does not fit. */\n\tsnapshot(message: AgentMessage, maxSourceBytes: number): { message: AgentMessage; sourceBytes: number } | undefined;\n}\n\n/** Context passed to `shouldStopAfterTurn` and both continuation callbacks. */\nexport interface ShouldStopAfterTurnContext {\n\t/** Assistant message that completed the turn. */\n\tmessage: AssistantMessage;\n\t/** Tool-result messages included in the preceding `turn_end` event. */\n\ttoolResults: ToolResultMessage[];\n\t/** Context after appending the turn's assistant message and tool results. */\n\tcontext: AgentContext;\n\t/** Messages returned by this invocation; prompts include initial prompts, continuations exclude prior context. */\n\tnewMessages: AgentMessage[];\n}\n\n/** The finalized loop decision, not a guess from the rendered message tail. */\nexport interface GetTurnOutcomeContext extends ShouldStopAfterTurnContext {\n\thasMoreToolCalls: boolean;\n}\n\n/** Control before queue polling; proceed keeps the ordinary loop policy. */\nexport type AgentTurnOutcome = { kind: \"proceed\" | \"finish\" | \"checkpoint_then_continue\" | \"cancelled\" };\n\nexport type GetContinuationMessagesContext = ShouldStopAfterTurnContext;\n\n/** Runtime control at a natural turn boundary; message payload does not decide whether to restart. */\nexport type AgentContinuationOutcome =\n\t| { kind: \"continue\"; messages: AgentMessage[] }\n\t| { kind: \"finish\" | \"wait_for_owned_work\" | \"cancelled\" };\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\t/** Opt-in bounded finalized results. Native sinks must join their message_end job. */\n\toutputPolicy?: AgentOutputPolicy;\n\tmodel: Model<any>;\n\n\t/** Native owner barrier before transform/convert. Rejection stops context construction. */\n\tbeforeContextBuild?: () => Promise<AgentContextBuildResult>;\n\n\t/** Internal state mirror for adopted working sets. Awaited and excluded from provider options. */\n\tonContextAdopted?: (messages: AgentMessage[]) => void | Promise<void>;\n\n\t/** Native owner recovery after release. One deterministic reprepare may precede one recovery. */\n\trecoverRequestPreparation?: (error: unknown, signal?: AbortSignal) => Promise<boolean | \"reprepare\">;\n\n\t/** Retry a settled provider failure within this invocation and its output allowance. */\n\trecoverProviderFailure?: (message: AssistantMessage, signal?: AbortSignal) => Promise<boolean>;\n\n\t/** Copied native owner callback; excluded from configured/provider stream options. */\n\townedStreamFn?: AgentOwnedStreamFn;\n\n\t/**\n\t * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.\n\t *\n\t * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage\n\t * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,\n\t * status messages) should be filtered out.\n\t *\n\t * Contract: must not throw or reject. Return a safe fallback value instead.\n\t * Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t *\n\t * @example\n\t * ```typescript\n\t * convertToLlm: (messages) => messages.flatMap(m => {\n\t * if (m.role === \"custom\") {\n\t * // Convert custom message to user message\n\t * return [{ role: \"user\", content: m.content, timestamp: m.timestamp }];\n\t * }\n\t * if (m.role === \"notification\") {\n\t * // Filter out UI-only messages\n\t * return [];\n\t * }\n\t * // Pass through standard LLM messages\n\t * return [m];\n\t * })\n\t * ```\n\t */\n\tconvertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\n\t/**\n\t * Optional transform applied to the context before `convertToLlm`.\n\t *\n\t * Use this for operations that work at the AgentMessage level:\n\t * - Context window management (pruning old messages)\n\t * - Injecting context from external sources\n\t *\n\t * Contract: must not throw or reject. Return the original messages or another\n\t * safe fallback value instead.\n\t *\n\t * @example\n\t * ```typescript\n\t * transformContext: async (messages) => {\n\t * if (estimateTokens(messages) > MAX_TOKENS) {\n\t * return pruneOldMessages(messages);\n\t * }\n\t * return messages;\n\t * }\n\t * ```\n\t */\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/** Resolves the system prompt immediately before each LLM call. */\n\tgetSystemPrompt?: () => string;\n\n\t/**\n\t * Resolves an API key dynamically for each LLM call.\n\t *\n\t * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire\n\t * during long-running tool execution phases.\n\t *\n\t * Contract: must not throw or reject. Return undefined when no key is available.\n\t */\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\n\t/**\n\t * Called after each turn fully completes and `turn_end` has been emitted.\n\t *\n\t * If it returns true, the loop emits `agent_end` and exits before polling steering or follow-up queues,\n\t * without starting another LLM call. The current assistant response and any tool executions finish normally.\n\t *\n\t * Use this to request a graceful stop after the current turn, e.g. before context gets too full.\n\t *\n\t * Contract: must not throw or reject. Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t */\n\tshouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;\n\n\t/** When present, this typed owner replaces shouldStopAfterTurn; it does not replace natural continuation. */\n\tgetTurnOutcome?: (\n\t\tcontext: GetTurnOutcomeContext,\n\t\tsignal?: AbortSignal,\n\t) => AgentTurnOutcome | Promise<AgentTurnOutcome>;\n\n\t/**\n\t * Called synchronously after a completed turn and before polling work for another turn.\n\t * Return true to emit `agent_end` without starting another provider call. Work returned by\n\t * an asynchronous poll owns that boundary; queue owners must suppress stale continuation\n\t * results if their higher-level stop condition changes while generating them.\n\t * The hook is never checked before the initial assistant turn.\n\t */\n\tshouldStopBeforeTurn?: () => boolean;\n\n\t/**\n\t * Returns steering messages to inject into the conversation mid-run.\n\t *\n\t * Called after the current assistant turn finishes executing its tool calls, unless `shouldStopAfterTurn` exits first.\n\t * If messages are returned, they are added to the context before the next LLM call.\n\t * Tool calls from the current assistant message are not skipped.\n\t *\n\t * Use this for \"steering\" the agent while it's working.\n\t *\n\t * Contract: must not throw or reject. Return [] when no steering messages are available.\n\t */\n\tgetSteeringMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns follow-up messages to process after the agent would otherwise stop.\n\t *\n\t * Called when the agent has no more tool calls and no steering messages.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for follow-up messages that should wait until the agent finishes.\n\t *\n\t * Contract: must not throw or reject. Return [] when no follow-up messages are available.\n\t */\n\tgetFollowUpMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns continuation messages when the agent would otherwise stop.\n\t *\n\t * Called after follow-up messages have been polled and none are available.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for host-owned continuation policies such as long-running goals.\n\t * Explicit follow-up messages always take precedence over continuation messages.\n\t *\n\t * Contract: must not throw or reject. Return [] when no continuation should run.\n\t */\n\tgetContinuationMessages?: (context: GetContinuationMessagesContext, signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/**\n\t * Authoritative runtime continuation control, after steering and explicit follow-ups.\n\t * When present, only this callback is called; getContinuationMessages is not polled.\n\t * Only continue restarts this invocation. Waiting leaves future work with its existing owner.\n\t */\n\tgetContinuationOutcome?: (\n\t\tcontext: GetContinuationMessagesContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentContinuationOutcome>;\n\n\t/**\n\t * Tool execution mode. Defaults to `\"parallel\"`.\n\t * Parallel mode preflights calls sequentially, executes allowed calls concurrently, emits\n\t * `tool_execution_end` in completion order, then emits tool-result messages in assistant source order.\n\t */\n\ttoolExecution?: ToolExecutionMode;\n\n\t/**\n\t * Awaited before invoking the tool. Rejection prevents execution and stops the loop.\n\t * The owner records intent here; admission is not proof that an external effect occurred.\n\t */\n\tonToolInvocationStarting?: (\n\t\tinvocation: ToolInvocation,\n\t\tsignal: AbortSignal | undefined,\n\t\ttool: AgentTool,\n\t\texecute: AgentTool[\"execute\"],\n\t\tassistantMessage?: AssistantMessage,\n\t) => void | BoundToolExecution | Promise<void> | Promise<BoundToolExecution | undefined>;\n\n\t/**\n\t * Native execution owner, awaited after final middleware and before observer/result events.\n\t * Persist source evidence here. Rejection stops publication; this is not an observer hook.\n\t * Cancellation does not skip settlement. The owner must bound its own persistence work.\n\t */\n\tonToolExchangeFinalized?: (\n\t\texchange: FinalizedToolExchange,\n\t\tsignal?: AbortSignal,\n\t\towner?: BoundToolExecution,\n\t) => void | Promise<void>;\n\n\t/**\n\t * Called before a tool is executed, after arguments have been validated.\n\t *\n\t * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\n\t/**\n\t * Called after a tool finishes executing, before `tool_execution_end` and tool-result message events are emitted.\n\t *\n\t * Return an `AfterToolCallResult` to override parts of the executed tool result:\n\t * - `content` replaces the full content array\n\t * - `details` replaces the full details payload\n\t * - `isError` replaces the error flag\n\t * - `terminate` replaces the early-termination hint\n\t *\n\t * Any omitted fields keep their original values. No deep merge is performed.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n}\n\n/**\n * Thinking/reasoning level for models that support it.\n * Note: \"xhigh\" and \"max\" are only supported by selected model families. Use model\n * thinking-level metadata from @ponythewhite/base-context-ai to detect support for a concrete model.\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n/**\n * Extensible interface for custom app messages.\n * Apps can extend via declaration merging:\n *\n * @example\n * ```typescript\n * declare module \"@mariozechner/agent\" {\n * interface CustomAgentMessages {\n * artifact: ArtifactMessage;\n * notification: NotificationMessage;\n * }\n * }\n * ```\n */\nexport interface CustomAgentMessages {}\n\nexport type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];\n\n/**\n * Public agent state.\n *\n * `tools` and `messages` use accessor properties so implementations can copy\n * assigned arrays before storing them.\n */\nexport interface AgentState {\n\t/** System prompt sent with each model request. */\n\tsystemPrompt: string;\n\t/** Model used for future turns. */\n\tmodel: Model<any> | undefined;\n\t/** Requested reasoning level for future turns. */\n\tthinkingLevel: ThinkingLevel;\n\t/** Requested provider service tier for future turns. */\n\tserviceTier: ServiceTier;\n\t/** Available tools. Assigning a new array copies its top-level array. */\n\tset tools(tools: AgentTool<any>[]);\n\tget tools(): AgentTool<any>[];\n\t/** Conversation transcript. Assigning a new array copies its top-level array. */\n\tset messages(messages: AgentMessage[]);\n\tget messages(): AgentMessage[];\n\t/** True while processing a prompt or continuation, including awaited `agent_end` listeners. */\n\treadonly isStreaming: boolean;\n\t/** Partial assistant message for the active streamed response, if any. */\n\treadonly streamingMessage?: AgentMessage;\n\t/** Tool-call IDs currently executing. */\n\treadonly pendingToolCalls: ReadonlySet<string>;\n\t/** Error from the most recent failed or aborted assistant turn, if any. */\n\treadonly errorMessage?: string;\n}\n\n/** Final or partial result produced by a tool. */\nexport interface AgentToolResult<T> {\n\t/** Text or image content returned to the model. */\n\tcontent: (TextContent | ImageContent)[];\n\t/** Structured details for logs or UI rendering. */\n\tdetails: T;\n\t/** Whether the tool reported an error. Defaults to false. */\n\tisError?: boolean;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Callback used by tools to publish partial execution updates. */\nexport type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;\n\n/** Tool definition used by the agent runtime. */\nexport interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {\n\t/** Human-readable label for UI display. */\n\tlabel: string;\n\t/**\n\t * Optional compatibility shim for raw tool-call arguments before schema validation.\n\t * Must return an object that matches `TParameters`.\n\t */\n\tprepareArguments?: (args: unknown) => Static<TParameters>;\n\t/** Execute the tool call. Throw on failure or return a result with `isError: true`. */\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: Static<TParameters>,\n\t\tsignal?: AbortSignal,\n\t\tonUpdate?: AgentToolUpdateCallback<TDetails>,\n\t) => Promise<AgentToolResult<TDetails>>;\n\t/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool must execute one at a time with other tool calls.\n\t * - \"parallel\": this tool can execute concurrently with other tool calls.\n\t *\n\t * If omitted, the default execution mode applies.\n\t */\n\texecutionMode?: ToolExecutionMode;\n}\n\n/** Context snapshot passed to the low-level agent loop and tool hooks. */\nexport interface AgentContext {\n\t/** System prompt included with the request. */\n\tsystemPrompt: string;\n\t/** Transcript visible to the model. */\n\tmessages: AgentMessage[];\n\t/** Tools available for this run. */\n\ttools?: AgentTool<any>[];\n}\n\n/**\n * Events emitted by the Agent for UI updates.\n *\n * `agent_end` is the last event emitted for a run, but awaited `Agent.subscribe()`\n * listeners for that event are still part of run settlement. The agent becomes\n * idle only after those listeners finish.\n */\nexport type AgentEvent =\n\t/** Starts and ends one agent run; `agent_end` carries all messages produced by that run. */\n\t| { type: \"agent_start\" }\n\t| { type: \"agent_end\"; messages: AgentMessage[]; refusal?: never }\n\t| { type: \"agent_end\"; refusal: AgentOutputRefusal; messages?: never }\n\t/** One assistant response and its resulting tool calls. */\n\t| { type: \"turn_start\" }\n\t| {\n\t\t\ttype: \"turn_end\";\n\t\t\tmessage: AgentMessage;\n\t\t\ttoolResults: ToolResultMessage[];\n\t\t\t/** Always populated by native execution; historical observer events may omit it. */\n\t\t\ttoolExecution?: ToolExecutionMode;\n\t\t\t/** Settled calls in source order. Absent historical evidence is not reconstructed. */\n\t\t\texchanges?: readonly FinalizedToolExchange[];\n\t }\n\t/** Lifecycle events for user, assistant, and tool-result messages. */\n\t| { type: \"message_start\"; message: AgentMessage }\n\t/** Only emitted for assistant messages during streaming. */\n\t| { type: \"message_update\"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }\n\t| { type: \"message_end\"; message: AgentMessage }\n\t/** Tool execution events; parallel calls may end in completion rather than source order. */\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: any }\n\t| { type: \"tool_execution_update\"; toolCallId: string; toolName: string; args: any; partialResult: any }\n\t| {\n\t\t\ttype: \"tool_execution_end\";\n\t\t\ttoolCallId: string;\n\t\t\ttoolName: string;\n\t\t\tresult: any;\n\t\t\tisError: boolean;\n\t\t\t/** Always populated by native execution; absent for older observer events. */\n\t\t\texchange?: FinalizedToolExchange;\n\t };\n"]}
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tImageContent,\n\tMessage,\n\tModel,\n\tServiceTier,\n\tSimpleStreamOptions,\n\tstreamSimple,\n\tTextContent,\n\tTool,\n\tToolResultMessage,\n} from \"@ponythewhite/base-context-ai\";\nimport type { Static, TSchema } from \"typebox\";\n\n/**\n * Stream function used by the agent loop.\n *\n * Contract:\n * - Must not throw or return a rejected promise for request/model/runtime failures.\n * - Must return an AssistantMessageEventStream.\n * - Failures must be encoded in the returned stream via protocol events and a\n * final AssistantMessage with stopReason \"error\" or \"aborted\" and errorMessage.\n */\nexport type StreamFn = (\n\t...args: Parameters<typeof streamSimple>\n) => ReturnType<typeof streamSimple> | Promise<ReturnType<typeof streamSimple>>;\n\nexport interface AgentContextProjection {\n\tmessages: AgentMessage[];\n\t/**\n\t * Adopt this complete working set in the owning Agent and loop, not only for inference.\n\t * It must include the current turn and pending tool closure. This is not a last-N tail.\n\t * Omitted/false preserves the existing inference-only projection behavior.\n\t */\n\tadoptMessages?: boolean;\n\tstreamContext?: unknown;\n\trelease?: () => Promise<void>;\n}\n\n// biome-ignore lint/suspicious/noConfusingVoidType: this return contract accepts existing Promise<void> context barriers.\nexport type AgentContextBuildResult = void | AgentContextProjection;\n\nexport type AgentOwnedStreamFn = (...args: [...Parameters<StreamFn>, streamContext?: unknown]) => ReturnType<StreamFn>;\n\n/**\n * Configuration for how tool calls from a single assistant message are executed.\n *\n * - \"sequential\": each tool call is prepared, executed, and finalized before the next one starts.\n * - \"parallel\": tool calls are prepared sequentially, then allowed tools execute concurrently.\n * `tool_execution_end` is emitted in tool completion order after each tool is finalized,\n * while tool-result message artifacts are emitted later in assistant source order.\n */\nexport type ToolExecutionMode = \"sequential\" | \"parallel\";\n\n/** A tool-call content block emitted by an assistant message. */\nexport type AgentToolCall = Extract<AssistantMessage[\"content\"][number], { type: \"toolCall\" }>;\n\n/**\n * Result returned from `beforeToolCall`.\n *\n * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.\n * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.\n */\nexport interface BeforeToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n}\n\n/**\n * Partial override returned from `afterToolCall`.\n *\n * Merge semantics are field-by-field:\n * - `content`: if provided, replaces the tool result content array in full\n * - `details`: if provided, replaces the tool result details value in full\n * - `isError`: if provided, replaces the tool result error flag\n * - `terminate`: if provided, replaces the early-termination hint\n *\n * Omitted fields keep the original executed tool result values.\n * There is no deep merge for `content` or `details`.\n */\nexport interface AfterToolCallResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tisError?: boolean;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Context passed to `beforeToolCall` after arguments are validated. */\nexport interface BeforeToolCallContext {\n\t/** Assistant message that requested the call. */\n\tassistantMessage: AssistantMessage;\n\t/** Raw tool-call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated arguments for the target tool schema. */\n\targs: unknown;\n\t/** Agent context when this call is prepared. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `afterToolCall`. */\nexport interface AfterToolCallContext {\n\t/** Assistant message that requested the call. */\n\tassistantMessage: AssistantMessage;\n\t/** Raw tool-call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated arguments for the target tool schema. */\n\targs: unknown;\n\t/** Executed result before any `afterToolCall` overrides. */\n\tresult: AgentToolResult<any>;\n\t/** Whether the executed result is currently treated as an error. */\n\tisError: boolean;\n\t/** Agent context when this call is finalized. */\n\tcontext: AgentContext;\n}\n\n/** What is known about the actual invocation, independently of middleware result overrides. */\nexport type ToolExecutionOutcome = \"not_started\" | \"completed\" | \"failed\" | \"outcome_unknown\";\n\n/** Immutable invocation admitted by the execution owner before the tool can run. */\nexport interface ToolInvocation {\n\treadonly executionId: string;\n\treadonly sourceOrder: number;\n\treadonly toolCallId: string;\n\treadonly toolName: string;\n\t/** Snapshot before argument preparation, validation, or tool middleware. */\n\treadonly originalInput: unknown;\n\t/** Arguments reserved for this invocation, not a live middleware object. */\n\treadonly executedInput: unknown;\n\treadonly toolExecution: ToolExecutionMode;\n}\n\n/** @internal Per-invocation owner closure; never serialized or supplied by result metadata. */\nexport interface BoundToolExecution {\n\trun(execute: () => Promise<AgentToolResult<unknown>>): Promise<AgentToolResult<unknown>>;\n\tfinalize(exchange: FinalizedToolExchange, signal?: AbortSignal): void | Promise<void>;\n}\n\n/** Finalized source evidence; parallel exchanges retain assistant call order via sourceOrder. */\nexport interface FinalizedToolExchange extends Omit<ToolInvocation, \"executedInput\"> {\n\t/** Snapshot at invocation; absent when execution never started. */\n\treadonly executedInput?: unknown;\n\t/** An aborted wait does not establish whether an external effect stopped. */\n\treadonly executionOutcome: ToolExecutionOutcome;\n\treadonly cancellationRequested: boolean;\n\t/** Final middleware result, also used for the tool-result message. */\n\treadonly result: ToolResultMessage;\n}\n\n/** Limits on the complete invocation result, not the working context or observer queues. */\nexport interface AgentOutputLimits {\n\tmaxMessages: number;\n\tmaxSourceBytes: number;\n}\n\nexport interface AgentOutputRefusal extends AgentOutputLimits {\n\tkind: \"output_limit\";\n\tlimit: \"messages\" | \"source_bytes\" | \"value_encoding\";\n}\n\nexport interface AgentOutputPolicy {\n\tlimits: AgentOutputLimits;\n\t/** Optional native update feed. Its synchronous refresh never revokes an ACK or throws a quota error. */\n\tbindUpdates?(refresh: (message: AgentMessage) => boolean): () => void;\n\t/** Close update admission and join the updates already accepted at this terminal boundary. */\n\tsettleUpdates?(): Promise<void>;\n\t/** Copy one finalized value within the supplied JSON-byte budget; undefined means it does not fit. */\n\tsnapshot(message: AgentMessage, maxSourceBytes: number): { message: AgentMessage; sourceBytes: number } | undefined;\n}\n\n/** Context passed to `shouldStopAfterTurn` and both continuation callbacks. */\nexport interface ShouldStopAfterTurnContext {\n\t/** Assistant message that completed the turn. */\n\tmessage: AssistantMessage;\n\t/** Tool-result messages included in the preceding `turn_end` event. */\n\ttoolResults: ToolResultMessage[];\n\t/** Context after appending the turn's assistant message and tool results. */\n\tcontext: AgentContext;\n\t/** Messages returned by this invocation; prompts include initial prompts, continuations exclude prior context. */\n\tnewMessages: AgentMessage[];\n}\n\n/** The finalized loop decision, not a guess from the rendered message tail. */\nexport interface GetTurnOutcomeContext extends ShouldStopAfterTurnContext {\n\thasMoreToolCalls: boolean;\n}\n\n/** Control before queue polling; proceed keeps the ordinary loop policy. */\nexport type AgentTurnOutcome = { kind: \"proceed\" | \"finish\" | \"checkpoint_then_continue\" | \"cancelled\" };\n\nexport type GetContinuationMessagesContext = ShouldStopAfterTurnContext;\n\n/** Runtime control at a natural turn boundary; message payload does not decide whether to restart. */\nexport type AgentContinuationOutcome =\n\t| { kind: \"continue\"; messages: AgentMessage[] }\n\t| { kind: \"finish\" | \"wait_for_owned_work\" | \"cancelled\" };\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\t/** Opt-in bounded finalized results. Native sinks must join their message_end job. */\n\toutputPolicy?: AgentOutputPolicy;\n\tmodel: Model<any>;\n\n\t/** Native owner barrier before transform/convert. Rejection stops context construction. */\n\tbeforeContextBuild?: () => Promise<AgentContextBuildResult>;\n\n\t/** Internal state mirror for adopted working sets. Awaited and excluded from provider options. */\n\tonContextAdopted?: (messages: AgentMessage[]) => void | Promise<void>;\n\n\t/** Native owner recovery after release. One deterministic reprepare may precede one recovery. */\n\trecoverRequestPreparation?: (error: unknown, signal?: AbortSignal) => Promise<boolean | \"reprepare\">;\n\n\t/** Retry a settled provider failure within this invocation and its output allowance. */\n\trecoverProviderFailure?: (message: AssistantMessage, signal?: AbortSignal) => Promise<boolean>;\n\n\t/** Copied native owner callback; excluded from configured/provider stream options. */\n\townedStreamFn?: AgentOwnedStreamFn;\n\n\t/**\n\t * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.\n\t *\n\t * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage\n\t * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,\n\t * status messages) should be filtered out.\n\t *\n\t * Contract: must not throw or reject. Return a safe fallback value instead.\n\t * Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t *\n\t * @example\n\t * ```typescript\n\t * convertToLlm: (messages) => messages.flatMap(m => {\n\t * if (m.role === \"custom\") {\n\t * // Convert custom message to user message\n\t * return [{ role: \"user\", content: m.content, timestamp: m.timestamp }];\n\t * }\n\t * if (m.role === \"notification\") {\n\t * // Filter out UI-only messages\n\t * return [];\n\t * }\n\t * // Pass through standard LLM messages\n\t * return [m];\n\t * })\n\t * ```\n\t */\n\tconvertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\n\t/**\n\t * Optional transform applied to the context before `convertToLlm`.\n\t *\n\t * Use this for operations that work at the AgentMessage level:\n\t * - Context window management (pruning old messages)\n\t * - Injecting context from external sources\n\t *\n\t * Contract: must not throw or reject. Return the original messages or another\n\t * safe fallback value instead.\n\t *\n\t * @example\n\t * ```typescript\n\t * transformContext: async (messages) => {\n\t * if (estimateTokens(messages) > MAX_TOKENS) {\n\t * return pruneOldMessages(messages);\n\t * }\n\t * return messages;\n\t * }\n\t * ```\n\t */\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/** Resolves the system prompt immediately before each LLM call. */\n\tgetSystemPrompt?: () => string;\n\n\t/**\n\t * Resolves an API key dynamically for each LLM call.\n\t *\n\t * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire\n\t * during long-running tool execution phases.\n\t *\n\t * Contract: must not throw or reject. Return undefined when no key is available.\n\t */\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\n\t/**\n\t * Called after each turn fully completes and `turn_end` has been emitted.\n\t *\n\t * If it returns true, the loop emits `agent_end` and exits before polling steering or follow-up queues,\n\t * without starting another LLM call. The current assistant response and any tool executions finish normally.\n\t *\n\t * Use this to request a graceful stop after the current turn, e.g. before context gets too full.\n\t *\n\t * Contract: must not throw or reject. Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t */\n\tshouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;\n\n\t/** When present, this typed owner replaces shouldStopAfterTurn; it does not replace natural continuation. */\n\tgetTurnOutcome?: (\n\t\tcontext: GetTurnOutcomeContext,\n\t\tsignal?: AbortSignal,\n\t) => AgentTurnOutcome | Promise<AgentTurnOutcome>;\n\n\t/**\n\t * Called synchronously after a completed turn and before polling work for another turn.\n\t * Return true to emit `agent_end` without starting another provider call. Work returned by\n\t * an asynchronous poll owns that boundary; queue owners must suppress stale continuation\n\t * results if their higher-level stop condition changes while generating them.\n\t * The hook is never checked before the initial assistant turn.\n\t */\n\tshouldStopBeforeTurn?: () => boolean;\n\n\t/**\n\t * Returns steering messages to inject into the conversation mid-run.\n\t *\n\t * Called after the current assistant turn finishes executing its tool calls, unless `shouldStopAfterTurn` exits first.\n\t * If messages are returned, they are added to the context before the next LLM call.\n\t * Tool calls from the current assistant message are not skipped.\n\t *\n\t * Use this for \"steering\" the agent while it's working.\n\t *\n\t * Contract: must not throw or reject. Return [] when no steering messages are available.\n\t */\n\tgetSteeringMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns follow-up messages to process after the agent would otherwise stop.\n\t *\n\t * Called when the agent has no more tool calls and no steering messages.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for follow-up messages that should wait until the agent finishes.\n\t *\n\t * Contract: must not throw or reject. Return [] when no follow-up messages are available.\n\t */\n\tgetFollowUpMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns continuation messages when the agent would otherwise stop.\n\t *\n\t * Called after follow-up messages have been polled and none are available.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for host-owned continuation policies such as long-running goals.\n\t * Explicit follow-up messages always take precedence over continuation messages.\n\t *\n\t * Contract: must not throw or reject. Return [] when no continuation should run.\n\t */\n\tgetContinuationMessages?: (context: GetContinuationMessagesContext, signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/**\n\t * Authoritative runtime continuation control, after steering and explicit follow-ups.\n\t * When present, only this callback is called; getContinuationMessages is not polled.\n\t * Only continue restarts this invocation. Waiting leaves future work with its existing owner.\n\t */\n\tgetContinuationOutcome?: (\n\t\tcontext: GetContinuationMessagesContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentContinuationOutcome>;\n\n\t/**\n\t * Tool execution mode. Defaults to `\"parallel\"`.\n\t * Parallel mode preflights calls sequentially, executes allowed calls concurrently, emits\n\t * `tool_execution_end` in completion order, then emits tool-result messages in assistant source order.\n\t */\n\ttoolExecution?: ToolExecutionMode;\n\n\t/**\n\t * Awaited before invoking the tool. Rejection prevents execution and stops the loop.\n\t * The owner records intent here; admission is not proof that an external effect occurred.\n\t */\n\tonToolInvocationStarting?: (\n\t\tinvocation: ToolInvocation,\n\t\tsignal: AbortSignal | undefined,\n\t\ttool: AgentTool,\n\t\texecute: AgentTool[\"execute\"],\n\t\tassistantMessage?: AssistantMessage,\n\t) => void | BoundToolExecution | Promise<void> | Promise<BoundToolExecution | undefined>;\n\n\t/**\n\t * Native execution owner, awaited after final middleware and before observer/result events.\n\t * Persist source evidence here. Rejection stops publication; this is not an observer hook.\n\t * Cancellation does not skip settlement. The owner must bound its own persistence work.\n\t */\n\tonToolExchangeFinalized?: (\n\t\texchange: FinalizedToolExchange,\n\t\tsignal?: AbortSignal,\n\t\towner?: BoundToolExecution,\n\t) => void | Promise<void>;\n\n\t/**\n\t * Called before a tool is executed, after arguments have been validated.\n\t *\n\t * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\n\t/**\n\t * Called after a tool finishes executing, before `tool_execution_end` and tool-result message events are emitted.\n\t *\n\t * Return an `AfterToolCallResult` to override parts of the executed tool result:\n\t * - `content` replaces the full content array\n\t * - `details` replaces the full details payload\n\t * - `isError` replaces the error flag\n\t * - `terminate` replaces the early-termination hint\n\t *\n\t * Any omitted fields keep their original values. No deep merge is performed.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n}\n\n/**\n * Thinking/reasoning level for models that support it.\n * Note: \"xhigh\" and \"max\" are only supported by selected model families. Use model\n * thinking-level metadata from @ponythewhite/base-context-ai to detect support for a concrete model.\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n/**\n * Extensible interface for custom app messages.\n * Apps can extend via declaration merging:\n *\n * @example\n * ```typescript\n * declare module \"@mariozechner/agent\" {\n * interface CustomAgentMessages {\n * artifact: ArtifactMessage;\n * notification: NotificationMessage;\n * }\n * }\n * ```\n */\nexport interface CustomAgentMessages {}\n\nexport type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];\n\n/**\n * Public agent state.\n *\n * `tools` and `messages` use accessor properties so implementations can copy\n * assigned arrays before storing them.\n */\nexport interface AgentState {\n\t/** System prompt sent with each model request. */\n\tsystemPrompt: string;\n\t/** Model used for future turns. */\n\tmodel: Model<any> | undefined;\n\t/** Requested reasoning level for future turns. */\n\tthinkingLevel: ThinkingLevel;\n\t/** Requested provider service tier for future turns. */\n\tserviceTier: ServiceTier;\n\t/** Available tools. Assigning a new array copies its top-level array. */\n\tset tools(tools: AgentTool<any>[]);\n\tget tools(): AgentTool<any>[];\n\t/** Conversation transcript. Assigning a new array copies its top-level array. */\n\tset messages(messages: AgentMessage[]);\n\tget messages(): AgentMessage[];\n\t/** True while processing a prompt or continuation, including awaited `agent_end` listeners. */\n\treadonly isStreaming: boolean;\n\t/** Partial assistant message for the active streamed response, if any. */\n\treadonly streamingMessage?: AgentMessage;\n\t/** Tool-call IDs currently executing. */\n\treadonly pendingToolCalls: ReadonlySet<string>;\n\t/** Error from the most recent failed or aborted assistant turn, if any. */\n\treadonly errorMessage?: string;\n}\n\n/** Final or partial result produced by a tool. */\nexport interface AgentToolResult<T> {\n\t/** Text or image content returned to the model. */\n\tcontent: (TextContent | ImageContent)[];\n\t/** Structured details for logs or UI rendering. */\n\tdetails: T;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Callback used by tools to publish partial execution updates. */\nexport type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;\n\n/** Tool definition used by the agent runtime. */\nexport interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {\n\t/** Human-readable label for UI display. */\n\tlabel: string;\n\t/**\n\t * Optional compatibility shim for raw tool-call arguments before schema validation.\n\t * Must return an object that matches `TParameters`.\n\t */\n\tprepareArguments?: (args: unknown) => Static<TParameters>;\n\t/** Execute the tool call. Throw on failure instead of encoding errors in `content`. */\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: Static<TParameters>,\n\t\tsignal?: AbortSignal,\n\t\tonUpdate?: AgentToolUpdateCallback<TDetails>,\n\t) => Promise<AgentToolResult<TDetails>>;\n\t/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool must execute one at a time with other tool calls.\n\t * - \"parallel\": this tool can execute concurrently with other tool calls.\n\t *\n\t * If omitted, the default execution mode applies.\n\t */\n\texecutionMode?: ToolExecutionMode;\n}\n\n/** Context snapshot passed to the low-level agent loop and tool hooks. */\nexport interface AgentContext {\n\t/** System prompt included with the request. */\n\tsystemPrompt: string;\n\t/** Transcript visible to the model. */\n\tmessages: AgentMessage[];\n\t/** Tools available for this run. */\n\ttools?: AgentTool<any>[];\n}\n\n/**\n * Events emitted by the Agent for UI updates.\n *\n * `agent_end` is the last event emitted for a run, but awaited `Agent.subscribe()`\n * listeners for that event are still part of run settlement. The agent becomes\n * idle only after those listeners finish.\n */\nexport type AgentEvent =\n\t/** Starts and ends one agent run; `agent_end` carries all messages produced by that run. */\n\t| { type: \"agent_start\" }\n\t| { type: \"agent_end\"; messages: AgentMessage[]; refusal?: never }\n\t| { type: \"agent_end\"; refusal: AgentOutputRefusal; messages?: never }\n\t/** One assistant response and its resulting tool calls. */\n\t| { type: \"turn_start\" }\n\t| {\n\t\t\ttype: \"turn_end\";\n\t\t\tmessage: AgentMessage;\n\t\t\ttoolResults: ToolResultMessage[];\n\t\t\t/** Always populated by native execution; historical observer events may omit it. */\n\t\t\ttoolExecution?: ToolExecutionMode;\n\t\t\t/** Settled calls in source order. Absent historical evidence is not reconstructed. */\n\t\t\texchanges?: readonly FinalizedToolExchange[];\n\t }\n\t/** Lifecycle events for user, assistant, and tool-result messages. */\n\t| { type: \"message_start\"; message: AgentMessage }\n\t/** Only emitted for assistant messages during streaming. */\n\t| { type: \"message_update\"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }\n\t| { type: \"message_end\"; message: AgentMessage }\n\t/** Tool execution events; parallel calls may end in completion rather than source order. */\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: any }\n\t| { type: \"tool_execution_update\"; toolCallId: string; toolName: string; args: any; partialResult: any }\n\t| {\n\t\t\ttype: \"tool_execution_end\";\n\t\t\ttoolCallId: string;\n\t\t\ttoolName: string;\n\t\t\tresult: any;\n\t\t\tisError: boolean;\n\t\t\t/** Always populated by native execution; absent for older observer events. */\n\t\t\texchange?: FinalizedToolExchange;\n\t };\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tImageContent,\n\tMessage,\n\tModel,\n\tServiceTier,\n\tSimpleStreamOptions,\n\tstreamSimple,\n\tTextContent,\n\tTool,\n\tToolResultMessage,\n} from \"@ponythewhite/base-context-ai\";\nimport type { Static, TSchema } from \"typebox\";\n\n/**\n * Stream function used by the agent loop.\n *\n * Contract:\n * - Must not throw or return a rejected promise for request/model/runtime failures.\n * - Must return an AssistantMessageEventStream.\n * - Failures must be encoded in the returned stream via protocol events and a\n * final AssistantMessage with stopReason \"error\" or \"aborted\" and errorMessage.\n */\nexport type StreamFn = (\n\t...args: Parameters<typeof streamSimple>\n) => ReturnType<typeof streamSimple> | Promise<ReturnType<typeof streamSimple>>;\n\nexport interface AgentContextProjection {\n\tmessages: AgentMessage[];\n\t/**\n\t * Adopt this complete working set in the owning Agent and loop, not only for inference.\n\t * It must include the current turn and pending tool closure. This is not a last-N tail.\n\t * Omitted/false preserves the existing inference-only projection behavior.\n\t */\n\tadoptMessages?: boolean;\n\tstreamContext?: unknown;\n\trelease?: () => Promise<void>;\n}\n\n// biome-ignore lint/suspicious/noConfusingVoidType: this return contract accepts existing Promise<void> context barriers.\nexport type AgentContextBuildResult = void | AgentContextProjection;\n\nexport type AgentOwnedStreamFn = (...args: [...Parameters<StreamFn>, streamContext?: unknown]) => ReturnType<StreamFn>;\n\n/**\n * Configuration for how tool calls from a single assistant message are executed.\n *\n * - \"sequential\": each tool call is prepared, executed, and finalized before the next one starts.\n * - \"parallel\": tool calls are prepared sequentially, then allowed tools execute concurrently.\n * `tool_execution_end` is emitted in tool completion order after each tool is finalized,\n * while tool-result message artifacts are emitted later in assistant source order.\n */\nexport type ToolExecutionMode = \"sequential\" | \"parallel\";\n\n/** A tool-call content block emitted by an assistant message. */\nexport type AgentToolCall = Extract<AssistantMessage[\"content\"][number], { type: \"toolCall\" }>;\n\n/**\n * Result returned from `beforeToolCall`.\n *\n * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.\n * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.\n */\nexport interface BeforeToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n}\n\n/**\n * Partial override returned from `afterToolCall`.\n *\n * Merge semantics are field-by-field:\n * - `content`: if provided, replaces the tool result content array in full\n * - `details`: if provided, replaces the tool result details value in full\n * - `isError`: if provided, replaces the tool result error flag\n * - `terminate`: if provided, replaces the early-termination hint\n *\n * Omitted fields keep the original executed tool result values.\n * There is no deep merge for `content` or `details`.\n */\nexport interface AfterToolCallResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tisError?: boolean;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Context passed to `beforeToolCall` after arguments are validated. */\nexport interface BeforeToolCallContext {\n\t/** Assistant message that requested the call. */\n\tassistantMessage: AssistantMessage;\n\t/** Raw tool-call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated arguments for the target tool schema. */\n\targs: unknown;\n\t/** Agent context when this call is prepared. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `afterToolCall`. */\nexport interface AfterToolCallContext {\n\t/** Assistant message that requested the call. */\n\tassistantMessage: AssistantMessage;\n\t/** Raw tool-call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated arguments for the target tool schema. */\n\targs: unknown;\n\t/** Executed result before any `afterToolCall` overrides. */\n\tresult: AgentToolResult<any>;\n\t/** Whether the executed result is currently treated as an error. */\n\tisError: boolean;\n\t/** Agent context when this call is finalized. */\n\tcontext: AgentContext;\n}\n\n/** What is known about the actual invocation, independently of middleware result overrides. */\nexport type ToolExecutionOutcome = \"not_started\" | \"completed\" | \"failed\" | \"outcome_unknown\";\n\n/** Immutable invocation admitted by the execution owner before the tool can run. */\nexport interface ToolInvocation {\n\treadonly executionId: string;\n\treadonly sourceOrder: number;\n\treadonly toolCallId: string;\n\treadonly toolName: string;\n\t/** Snapshot before argument preparation, validation, or tool middleware. */\n\treadonly originalInput: unknown;\n\t/** Arguments reserved for this invocation, not a live middleware object. */\n\treadonly executedInput: unknown;\n\treadonly toolExecution: ToolExecutionMode;\n}\n\n/** @internal Per-invocation owner closure; never serialized or supplied by result metadata. */\nexport interface BoundToolExecution {\n\trun(execute: () => Promise<AgentToolResult<unknown>>): Promise<AgentToolResult<unknown>>;\n\tfinalize(exchange: FinalizedToolExchange, signal?: AbortSignal): void | Promise<void>;\n}\n\n/** Finalized source evidence; parallel exchanges retain assistant call order via sourceOrder. */\nexport interface FinalizedToolExchange extends Omit<ToolInvocation, \"executedInput\"> {\n\t/** Snapshot at invocation; absent when execution never started. */\n\treadonly executedInput?: unknown;\n\t/** An aborted wait does not establish whether an external effect stopped. */\n\treadonly executionOutcome: ToolExecutionOutcome;\n\treadonly cancellationRequested: boolean;\n\t/** Final middleware result, also used for the tool-result message. */\n\treadonly result: ToolResultMessage;\n}\n\n/** Limits on the complete invocation result, not the working context or observer queues. */\nexport interface AgentOutputLimits {\n\tmaxMessages: number;\n\tmaxSourceBytes: number;\n}\n\nexport interface AgentOutputRefusal extends AgentOutputLimits {\n\tkind: \"output_limit\";\n\tlimit: \"messages\" | \"source_bytes\" | \"value_encoding\";\n}\n\nexport interface AgentOutputPolicy {\n\tlimits: AgentOutputLimits;\n\t/** Optional native update feed. Its synchronous refresh never revokes an ACK or throws a quota error. */\n\tbindUpdates?(refresh: (message: AgentMessage) => boolean): () => void;\n\t/** Close update admission and join the updates already accepted at this terminal boundary. */\n\tsettleUpdates?(): Promise<void>;\n\t/** Copy one finalized value within the supplied JSON-byte budget; undefined means it does not fit. */\n\tsnapshot(message: AgentMessage, maxSourceBytes: number): { message: AgentMessage; sourceBytes: number } | undefined;\n}\n\n/** Context passed to `shouldStopAfterTurn` and both continuation callbacks. */\nexport interface ShouldStopAfterTurnContext {\n\t/** Assistant message that completed the turn. */\n\tmessage: AssistantMessage;\n\t/** Tool-result messages included in the preceding `turn_end` event. */\n\ttoolResults: ToolResultMessage[];\n\t/** Context after appending the turn's assistant message and tool results. */\n\tcontext: AgentContext;\n\t/** Messages returned by this invocation; prompts include initial prompts, continuations exclude prior context. */\n\tnewMessages: AgentMessage[];\n}\n\n/** The finalized loop decision, not a guess from the rendered message tail. */\nexport interface GetTurnOutcomeContext extends ShouldStopAfterTurnContext {\n\thasMoreToolCalls: boolean;\n}\n\n/** Control before queue polling; proceed keeps the ordinary loop policy. */\nexport type AgentTurnOutcome = { kind: \"proceed\" | \"finish\" | \"checkpoint_then_continue\" | \"cancelled\" };\n\nexport type GetContinuationMessagesContext = ShouldStopAfterTurnContext;\n\n/** Runtime control at a natural turn boundary; message payload does not decide whether to restart. */\nexport type AgentContinuationOutcome =\n\t| { kind: \"continue\"; messages: AgentMessage[] }\n\t| { kind: \"finish\" | \"wait_for_owned_work\" | \"cancelled\" };\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\t/** Opt-in bounded finalized results. Native sinks must join their message_end job. */\n\toutputPolicy?: AgentOutputPolicy;\n\tmodel: Model<any>;\n\n\t/** Native owner barrier before transform/convert. Rejection stops context construction. */\n\tbeforeContextBuild?: () => Promise<AgentContextBuildResult>;\n\n\t/** Internal state mirror for adopted working sets. Awaited and excluded from provider options. */\n\tonContextAdopted?: (messages: AgentMessage[]) => void | Promise<void>;\n\n\t/** Native owner recovery after release. One deterministic reprepare may precede one recovery. */\n\trecoverRequestPreparation?: (error: unknown, signal?: AbortSignal) => Promise<boolean | \"reprepare\">;\n\n\t/** Retry a settled provider failure within this invocation and its output allowance. */\n\trecoverProviderFailure?: (message: AssistantMessage, signal?: AbortSignal) => Promise<boolean>;\n\n\t/** Copied native owner callback; excluded from configured/provider stream options. */\n\townedStreamFn?: AgentOwnedStreamFn;\n\n\t/**\n\t * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.\n\t *\n\t * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage\n\t * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,\n\t * status messages) should be filtered out.\n\t *\n\t * Contract: must not throw or reject. Return a safe fallback value instead.\n\t * Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t *\n\t * @example\n\t * ```typescript\n\t * convertToLlm: (messages) => messages.flatMap(m => {\n\t * if (m.role === \"custom\") {\n\t * // Convert custom message to user message\n\t * return [{ role: \"user\", content: m.content, timestamp: m.timestamp }];\n\t * }\n\t * if (m.role === \"notification\") {\n\t * // Filter out UI-only messages\n\t * return [];\n\t * }\n\t * // Pass through standard LLM messages\n\t * return [m];\n\t * })\n\t * ```\n\t */\n\tconvertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\n\t/**\n\t * Optional transform applied to the context before `convertToLlm`.\n\t *\n\t * Use this for operations that work at the AgentMessage level:\n\t * - Context window management (pruning old messages)\n\t * - Injecting context from external sources\n\t *\n\t * Contract: must not throw or reject. Return the original messages or another\n\t * safe fallback value instead.\n\t *\n\t * @example\n\t * ```typescript\n\t * transformContext: async (messages) => {\n\t * if (estimateTokens(messages) > MAX_TOKENS) {\n\t * return pruneOldMessages(messages);\n\t * }\n\t * return messages;\n\t * }\n\t * ```\n\t */\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/** Resolves the system prompt immediately before each LLM call. */\n\tgetSystemPrompt?: () => string;\n\n\t/**\n\t * Resolves an API key dynamically for each LLM call.\n\t *\n\t * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire\n\t * during long-running tool execution phases.\n\t *\n\t * Contract: must not throw or reject. Return undefined when no key is available.\n\t */\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\n\t/**\n\t * Called after each turn fully completes and `turn_end` has been emitted.\n\t *\n\t * If it returns true, the loop emits `agent_end` and exits before polling steering or follow-up queues,\n\t * without starting another LLM call. The current assistant response and any tool executions finish normally.\n\t *\n\t * Use this to request a graceful stop after the current turn, e.g. before context gets too full.\n\t *\n\t * Contract: must not throw or reject. Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t */\n\tshouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;\n\n\t/** When present, this typed owner replaces shouldStopAfterTurn; it does not replace natural continuation. */\n\tgetTurnOutcome?: (\n\t\tcontext: GetTurnOutcomeContext,\n\t\tsignal?: AbortSignal,\n\t) => AgentTurnOutcome | Promise<AgentTurnOutcome>;\n\n\t/**\n\t * Called synchronously after a completed turn and before polling work for another turn.\n\t * Return true to emit `agent_end` without starting another provider call. Work returned by\n\t * an asynchronous poll owns that boundary; queue owners must suppress stale continuation\n\t * results if their higher-level stop condition changes while generating them.\n\t * The hook is never checked before the initial assistant turn.\n\t */\n\tshouldStopBeforeTurn?: () => boolean;\n\n\t/**\n\t * Returns steering messages to inject into the conversation mid-run.\n\t *\n\t * Called after the current assistant turn finishes executing its tool calls, unless `shouldStopAfterTurn` exits first.\n\t * If messages are returned, they are added to the context before the next LLM call.\n\t * Tool calls from the current assistant message are not skipped.\n\t *\n\t * Use this for \"steering\" the agent while it's working.\n\t *\n\t * Contract: must not throw or reject. Return [] when no steering messages are available.\n\t */\n\tgetSteeringMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns follow-up messages to process after the agent would otherwise stop.\n\t *\n\t * Called when the agent has no more tool calls and no steering messages.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for follow-up messages that should wait until the agent finishes.\n\t *\n\t * Contract: must not throw or reject. Return [] when no follow-up messages are available.\n\t */\n\tgetFollowUpMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns continuation messages when the agent would otherwise stop.\n\t *\n\t * Called after follow-up messages have been polled and none are available.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for host-owned continuation policies such as long-running goals.\n\t * Explicit follow-up messages always take precedence over continuation messages.\n\t *\n\t * Contract: must not throw or reject. Return [] when no continuation should run.\n\t */\n\tgetContinuationMessages?: (context: GetContinuationMessagesContext, signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/**\n\t * Authoritative runtime continuation control, after steering and explicit follow-ups.\n\t * When present, only this callback is called; getContinuationMessages is not polled.\n\t * Only continue restarts this invocation. Waiting leaves future work with its existing owner.\n\t */\n\tgetContinuationOutcome?: (\n\t\tcontext: GetContinuationMessagesContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentContinuationOutcome>;\n\n\t/**\n\t * Tool execution mode. Defaults to `\"parallel\"`.\n\t * Parallel mode preflights calls sequentially, executes allowed calls concurrently, emits\n\t * `tool_execution_end` in completion order, then emits tool-result messages in assistant source order.\n\t */\n\ttoolExecution?: ToolExecutionMode;\n\n\t/**\n\t * Awaited before invoking the tool. Rejection prevents execution and stops the loop.\n\t * The owner records intent here; admission is not proof that an external effect occurred.\n\t */\n\tonToolInvocationStarting?: (\n\t\tinvocation: ToolInvocation,\n\t\tsignal: AbortSignal | undefined,\n\t\ttool: AgentTool,\n\t\texecute: AgentTool[\"execute\"],\n\t\tassistantMessage?: AssistantMessage,\n\t) => void | BoundToolExecution | Promise<void> | Promise<BoundToolExecution | undefined>;\n\n\t/**\n\t * Native execution owner, awaited after final middleware and before observer/result events.\n\t * Persist source evidence here. Rejection stops publication; this is not an observer hook.\n\t * Cancellation does not skip settlement. The owner must bound its own persistence work.\n\t */\n\tonToolExchangeFinalized?: (\n\t\texchange: FinalizedToolExchange,\n\t\tsignal?: AbortSignal,\n\t\towner?: BoundToolExecution,\n\t) => void | Promise<void>;\n\n\t/**\n\t * Called before a tool is executed, after arguments have been validated.\n\t *\n\t * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\n\t/**\n\t * Called after a tool finishes executing, before `tool_execution_end` and tool-result message events are emitted.\n\t *\n\t * Return an `AfterToolCallResult` to override parts of the executed tool result:\n\t * - `content` replaces the full content array\n\t * - `details` replaces the full details payload\n\t * - `isError` replaces the error flag\n\t * - `terminate` replaces the early-termination hint\n\t *\n\t * Any omitted fields keep their original values. No deep merge is performed.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n}\n\n/**\n * Thinking/reasoning level for models that support it.\n * Note: \"xhigh\" and \"max\" are only supported by selected model families. Use model\n * thinking-level metadata from @ponythewhite/base-context-ai to detect support for a concrete model.\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n/**\n * Extensible interface for custom app messages.\n * Apps can extend via declaration merging:\n *\n * @example\n * ```typescript\n * declare module \"@mariozechner/agent\" {\n * interface CustomAgentMessages {\n * artifact: ArtifactMessage;\n * notification: NotificationMessage;\n * }\n * }\n * ```\n */\nexport interface CustomAgentMessages {}\n\nexport type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];\n\n/**\n * Public agent state.\n *\n * `tools` and `messages` use accessor properties so implementations can copy\n * assigned arrays before storing them.\n */\nexport interface AgentState {\n\t/** System prompt sent with each model request. */\n\tsystemPrompt: string;\n\t/** Model used for future turns. */\n\tmodel: Model<any> | undefined;\n\t/** Requested reasoning level for future turns. */\n\tthinkingLevel: ThinkingLevel;\n\t/** Requested provider service tier for future turns. */\n\tserviceTier: ServiceTier;\n\t/** Available tools. Assigning a new array copies its top-level array. */\n\tset tools(tools: AgentTool<any>[]);\n\tget tools(): AgentTool<any>[];\n\t/** Conversation transcript. Assigning a new array copies its top-level array. */\n\tset messages(messages: AgentMessage[]);\n\tget messages(): AgentMessage[];\n\t/** True while processing a prompt or continuation, including awaited `agent_end` listeners. */\n\treadonly isStreaming: boolean;\n\t/** Partial assistant message for the active streamed response, if any. */\n\treadonly streamingMessage?: AgentMessage;\n\t/** Tool-call IDs currently executing. */\n\treadonly pendingToolCalls: ReadonlySet<string>;\n\t/** Error from the most recent failed or aborted assistant turn, if any. */\n\treadonly errorMessage?: string;\n}\n\n/** Final or partial result produced by a tool. */\nexport interface AgentToolResult<T> {\n\t/** Text or image content returned to the model. */\n\tcontent: (TextContent | ImageContent)[];\n\t/** Structured details for logs or UI rendering. */\n\tdetails: T;\n\t/** Whether the tool reported an error. Defaults to false. */\n\tisError?: boolean;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Callback used by tools to publish partial execution updates. */\nexport type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;\n\n/** Tool definition used by the agent runtime. */\nexport interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {\n\t/** Human-readable label for UI display. */\n\tlabel: string;\n\t/**\n\t * Optional compatibility shim for raw tool-call arguments before schema validation.\n\t * Must return an object that matches `TParameters`.\n\t */\n\tprepareArguments?: (args: unknown) => Static<TParameters>;\n\t/** Execute the tool call. Throw on failure or return a result with `isError: true`. */\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: Static<TParameters>,\n\t\tsignal?: AbortSignal,\n\t\tonUpdate?: AgentToolUpdateCallback<TDetails>,\n\t) => Promise<AgentToolResult<TDetails>>;\n\t/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool must execute one at a time with other tool calls.\n\t * - \"parallel\": this tool can execute concurrently with other tool calls.\n\t *\n\t * If omitted, the default execution mode applies.\n\t */\n\texecutionMode?: ToolExecutionMode;\n}\n\n/** Context snapshot passed to the low-level agent loop and tool hooks. */\nexport interface AgentContext {\n\t/** System prompt included with the request. */\n\tsystemPrompt: string;\n\t/** Transcript visible to the model. */\n\tmessages: AgentMessage[];\n\t/** Tools available for this run. */\n\ttools?: AgentTool<any>[];\n}\n\n/**\n * Events emitted by the Agent for UI updates.\n *\n * `agent_end` is the last event emitted for a run, but awaited `Agent.subscribe()`\n * listeners for that event are still part of run settlement. The agent becomes\n * idle only after those listeners finish.\n */\nexport type AgentEvent =\n\t/** Starts and ends one agent run; `agent_end` carries all messages produced by that run. */\n\t| { type: \"agent_start\" }\n\t| { type: \"agent_end\"; messages: AgentMessage[]; refusal?: never }\n\t| { type: \"agent_end\"; refusal: AgentOutputRefusal; messages?: never }\n\t/** One assistant response and its resulting tool calls. */\n\t| { type: \"turn_start\" }\n\t| {\n\t\t\ttype: \"turn_end\";\n\t\t\tmessage: AgentMessage;\n\t\t\ttoolResults: ToolResultMessage[];\n\t\t\t/** Always populated by native execution; historical observer events may omit it. */\n\t\t\ttoolExecution?: ToolExecutionMode;\n\t\t\t/** Settled calls in source order. Absent historical evidence is not reconstructed. */\n\t\t\texchanges?: readonly FinalizedToolExchange[];\n\t }\n\t/** Lifecycle events for user, assistant, and tool-result messages. */\n\t| { type: \"message_start\"; message: AgentMessage }\n\t/** Only emitted for assistant messages during streaming. */\n\t| { type: \"message_update\"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }\n\t| { type: \"message_end\"; message: AgentMessage }\n\t/** Tool execution events; parallel calls may end in completion rather than source order. */\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: any }\n\t| { type: \"tool_execution_update\"; toolCallId: string; toolName: string; args: any; partialResult: any }\n\t| {\n\t\t\ttype: \"tool_execution_end\";\n\t\t\ttoolCallId: string;\n\t\t\ttoolName: string;\n\t\t\tresult: any;\n\t\t\tisError: boolean;\n\t\t\t/** Always populated by native execution; absent for older observer events. */\n\t\t\texchange?: FinalizedToolExchange;\n\t };\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ponythewhite/base-context-agent",
3
- "version": "1.0.21",
3
+ "version": "1.1.1",
4
4
  "description": "Synerise base-context agent runtime with context management and native recovery",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -19,7 +19,7 @@
19
19
  "prepublishOnly": "npm --prefix ../.. run build:source"
20
20
  },
21
21
  "dependencies": {
22
- "@ponythewhite/base-context-ai": "1.0.21",
22
+ "@ponythewhite/base-context-ai": "1.1.1",
23
23
  "typebox": "^1.3.9"
24
24
  },
25
25
  "keywords": [