@ponythewhite/base-context-agent 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/NOTICE CHANGED
@@ -14,9 +14,4 @@ this fork is not an official Prime Intellect release.
14
14
  Prime Agent builds on Mario Zechner's Pi project:
15
15
  https://github.com/badlogic/pi-mono
16
16
 
17
- We also credit Prime Intellect's PrimeRL authors for their open-source
18
- reinforcement-learning work: https://github.com/PrimeIntellect-ai/prime-rl
19
- This acknowledgement does not imply that PrimeRL is a runtime dependency
20
- or that upstream authors endorse this fork.
21
-
22
17
  Third-party dependencies retain their own licenses and notices.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Stateful agent runtime with native context and recovery ownership.
4
4
 
5
- Part of **[Synerise base-context](https://github.com/BaseModelAI/base-context)**. Forked from Prime Intellect's [Prime Agent](https://github.com/PrimeIntellect-ai/prime-agent), built on Mario Zechner's Pi. MIT; see [LICENSE](LICENSE) and [NOTICE](NOTICE).
5
+ Part of **[Synerise base-context](https://github.com/BaseModelAI/base-context)**. MIT; see [LICENSE](LICENSE) and [NOTICE](NOTICE).
6
6
 
7
7
  ## Workspace Package
8
8
 
package/dist/NOTICE CHANGED
@@ -14,9 +14,4 @@ this fork is not an official Prime Intellect release.
14
14
  Prime Agent builds on Mario Zechner's Pi project:
15
15
  https://github.com/badlogic/pi-mono
16
16
 
17
- We also credit Prime Intellect's PrimeRL authors for their open-source
18
- reinforcement-learning work: https://github.com/PrimeIntellect-ai/prime-rl
19
- This acknowledgement does not imply that PrimeRL is a runtime dependency
20
- or that upstream authors endorse this fork.
21
-
22
17
  Third-party dependencies retain their own licenses and notices.
@@ -1 +1 @@
1
- {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,KAAK,YAAY,EAEjB,KAAK,OAAO,EAGZ,KAAK,mBAAmB,EAGxB,KAAK,eAAe,EACp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tRequestTokenBudgetError,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"@ponythewhite/base-context-ai\";\nimport { runAgentLoop, runAgentLoopContinue } from \"./agent-loop.js\";\nimport { AgentOutputLimitError } from \"./invocation-output.js\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentContextBuildResult,\n\tAgentContinuationOutcome,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentOutputPolicy,\n\tAgentOwnedStreamFn,\n\tAgentState,\n\tAgentTool,\n\tAgentTurnOutcome,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tFinalizedToolExchange,\n\tGetContinuationMessagesContext,\n\tGetTurnOutcomeContext,\n\tShouldStopAfterTurnContext,\n\tStreamFn,\n\tToolExecutionMode,\n\tToolInvocation,\n} from \"./types.js\";\n\n/** Preserve actual local request preparation failures and primary cleanup chains without inventing an assistant. */\nfunction isRequestTokenBudgetFailure(error: unknown): error is Error {\n\treturn (\n\t\terror instanceof RequestTokenBudgetError ||\n\t\tisLocalRequestPreparationError(error) ||\n\t\t(error instanceof AggregateError && isRequestTokenBudgetFailure(error.errors[0]))\n\t);\n}\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) => message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\",\n\t);\n}\n\nconst EMPTY_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\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype QueueMode = \"all\" | \"one-at-a-time\";\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\nfunction createMutableAgentState(\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>,\n): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\n\treturn {\n\t\tsystemPrompt: initialState?.systemPrompt ?? \"\",\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tserviceTier: initialState?.serviceTier ?? \"default\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tonToolInvocationStarting?: (invocation: ToolInvocation, signal?: AbortSignal) => void | Promise<void>;\n\tonToolExchangeFinalized?: (exchange: FinalizedToolExchange, signal?: AbortSignal) => void | Promise<void>;\n\tshouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;\n\tgetTurnOutcome?: (\n\t\tcontext: GetTurnOutcomeContext,\n\t\tsignal?: AbortSignal,\n\t) => AgentTurnOutcome | Promise<AgentTurnOutcome>;\n\tshouldStopBeforeTurn?: () => boolean;\n\tgetContinuationMessages?: (context: GetContinuationMessagesContext, signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tgetContinuationOutcome?: (\n\t\tcontext: GetContinuationMessagesContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentContinuationOutcome>;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\ttoolExecution?: ToolExecutionMode;\n}\n\nclass PendingMessageQueue {\n\tprivate batches: AgentMessage[][] = [];\n\n\tconstructor(public mode: QueueMode) {}\n\n\tenqueue(message: AgentMessage | AgentMessage[]): void {\n\t\tconst batch = Array.isArray(message) ? message.slice() : [message];\n\t\tif (batch.length > 0) {\n\t\t\tthis.batches.push(batch);\n\t\t}\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.batches.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.batches.flat();\n\t\t\tthis.batches = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.batches[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.batches = this.batches.slice(1);\n\t\treturn first;\n\t}\n\n\tclear(): void {\n\t\tthis.batches = [];\n\t}\n\n\tremoveWhere(predicate: (message: AgentMessage) => boolean): AgentMessage[] {\n\t\tconst removed: AgentMessage[] = [];\n\t\tconst retained: AgentMessage[][] = [];\n\t\tfor (const batch of this.batches) {\n\t\t\tif (batch.some(predicate)) {\n\t\t\t\tremoved.push(...batch);\n\t\t\t} else {\n\t\t\t\tretained.push(batch);\n\t\t\t}\n\t\t}\n\t\tthis.batches = retained;\n\t\treturn removed;\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/** Why {@link Agent.continue} refused to start a continuation. */\nexport type AgentContinueErrorCode = \"busy\" | \"nothing-to-continue\";\n\n/** Typed precondition failure from {@link Agent.continue}, so callers classify by code instead of message text. */\nexport class AgentContinueError extends Error {\n\tconstructor(\n\t\treadonly code: AgentContinueErrorCode,\n\t\tmessage: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"AgentContinueError\";\n\t}\n}\n\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tprivate initializationOwner?: () => Promise<void>;\n\tprivate contextOwner?: () => Promise<AgentContextBuildResult>;\n\tprivate requestPreparationRecoveryOwner?: AgentLoopConfig[\"recoverRequestPreparation\"];\n\tprivate providerFailureRecoveryOwner?: {\n\t\trecover: NonNullable<AgentLoopConfig[\"recoverProviderFailure\"]>;\n\t\tsettle?: () => void;\n\t};\n\tprivate outputOwner?: () => AgentOutputPolicy | undefined;\n\tprivate activeOutputPolicy?: AgentOutputPolicy;\n\n\t/** Native sinks join finalized message values; configuration is captured once per invocation. */\n\tbindOutputOwner(owner: () => AgentOutputPolicy | undefined): void {\n\t\tif (this.outputOwner) throw new Error(\"Agent output owner is already bound\");\n\t\tthis.outputOwner = owner;\n\t}\n\n\t/** Finish native initialization before capturing context or emitting loop events. */\n\tbindInitializationOwner(owner: () => Promise<void>): void {\n\t\tif (this.initializationOwner) throw new Error(\"Agent initialization owner is already bound\");\n\t\tthis.initializationOwner = owner;\n\t}\n\n\t/** Native persistence remains ahead of replaceable context callbacks. */\n\tbindContextOwner(owner: () => Promise<AgentContextBuildResult>): void {\n\t\tif (this.contextOwner) throw new Error(\"Agent context owner is already bound\");\n\t\tthis.contextOwner = owner;\n\t}\n\n\tbindRequestPreparationRecoveryOwner(owner: NonNullable<AgentLoopConfig[\"recoverRequestPreparation\"]>): void {\n\t\tif (this.requestPreparationRecoveryOwner)\n\t\t\tthrow new Error(\"Agent request preparation recovery owner is already bound\");\n\t\tthis.requestPreparationRecoveryOwner = owner;\n\t}\n\n\tbindProviderFailureRecoveryOwner(owner: {\n\t\trecover: NonNullable<AgentLoopConfig[\"recoverProviderFailure\"]>;\n\t\tsettle?: () => void;\n\t}): void {\n\t\tif (this.providerFailureRecoveryOwner) throw new Error(\"Agent provider failure recovery owner is already bound\");\n\t\tthis.providerFailureRecoveryOwner = owner;\n\t}\n\n\tprivate configuredStreamFn!: StreamFn;\n\tprivate effectiveStreamFn!: StreamFn;\n\tprivate ownedStreamFn?: AgentOwnedStreamFn;\n\tprivate streamOwner?: (streamFn: StreamFn) => AgentOwnedStreamFn;\n\n\tget streamFn(): StreamFn {\n\t\treturn this.effectiveStreamFn;\n\t}\n\tset streamFn(streamFn: StreamFn) {\n\t\tthis.configuredStreamFn = streamFn;\n\t\tconst ownedStreamFn = this.streamOwner?.(streamFn);\n\t\tthis.ownedStreamFn = ownedStreamFn;\n\t\tthis.effectiveStreamFn = ownedStreamFn ?? streamFn;\n\t}\n\n\t/** A native owner remains in the path when an embedding changes its configured stream. */\n\tbindStreamOwner(owner: (streamFn: StreamFn) => AgentOwnedStreamFn): void {\n\t\tif (this.streamOwner) throw new Error(\"Agent stream owner is already bound\");\n\t\tthis.streamOwner = owner;\n\t\tthis.streamFn = this.configuredStreamFn;\n\t}\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic onToolInvocationStarting?: (invocation: ToolInvocation, signal?: AbortSignal) => void | Promise<void>;\n\tpublic onToolExchangeFinalized?: (exchange: FinalizedToolExchange, signal?: AbortSignal) => void | Promise<void>;\n\tprivate toolExecutionOwner?: Required<Pick<AgentLoopConfig, \"onToolInvocationStarting\" | \"onToolExchangeFinalized\">>;\n\n\t/** Native persistence runs before replaceable caller hooks. */\n\tbindToolExecutionOwner(\n\t\towner: Required<Pick<AgentLoopConfig, \"onToolInvocationStarting\" | \"onToolExchangeFinalized\">>,\n\t): void {\n\t\tif (this.toolExecutionOwner) throw new Error(\"Agent tool execution owner is already bound\");\n\t\tthis.toolExecutionOwner = {\n\t\t\tonToolInvocationStarting: owner.onToolInvocationStarting,\n\t\t\tonToolExchangeFinalized: owner.onToolExchangeFinalized,\n\t\t};\n\t}\n\n\tpublic shouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;\n\tpublic getTurnOutcome?: (\n\t\tcontext: GetTurnOutcomeContext,\n\t\tsignal?: AbortSignal,\n\t) => AgentTurnOutcome | Promise<AgentTurnOutcome>;\n\tpublic shouldStopBeforeTurn?: () => boolean;\n\tpublic getContinuationMessages?: (\n\t\tcontext: GetContinuationMessagesContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentMessage[]>;\n\tpublic getContinuationOutcome?: (\n\t\tcontext: GetContinuationMessagesContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentContinuationOutcome>;\n\tprivate activeRun?: ActiveRun;\n\tpublic sessionId?: string;\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\tpublic transport: Transport;\n\tpublic maxRetryDelayMs?: number;\n\tpublic toolExecution: ToolExecutionMode;\n\n\tconstructor(options: AgentOptions = {}) {\n\t\tthis._state = createMutableAgentState(options.initialState);\n\t\tthis.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = options.transformContext;\n\t\tthis.streamFn = options.streamFn ?? streamSimple;\n\t\tthis.getApiKey = options.getApiKey;\n\t\tthis.onPayload = options.onPayload;\n\t\tthis.onResponse = options.onResponse;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.onToolInvocationStarting = options.onToolInvocationStarting;\n\t\tthis.onToolExchangeFinalized = options.onToolExchangeFinalized;\n\t\tthis.shouldStopAfterTurn = options.shouldStopAfterTurn;\n\t\tthis.getTurnOutcome = options.getTurnOutcome;\n\t\tthis.shouldStopBeforeTurn = options.shouldStopBeforeTurn;\n\t\tthis.getContinuationMessages = options.getContinuationMessages;\n\t\tthis.getContinuationOutcome = options.getContinuationOutcome;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.toolExecution = options.toolExecution ?? \"parallel\";\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order and are included in\n\t * the current run's settlement. Listeners also receive the active abort\n\t * signal for the current run.\n\t *\n\t * `agent_end` is the final emitted event for a run, but the agent does not\n\t * become idle until all awaited listeners for that event have settled.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message batch to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage | AgentMessage[]): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message batch to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage | AgentMessage[]): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\tremoveQueuedMessages(predicate: (message: AgentMessage) => boolean): AgentMessage[] {\n\t\treturn [...this.steeringQueue.removeWhere(predicate), ...this.followUpQueue.removeWhere(predicate)];\n\t}\n\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** The last message must convert to a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new AgentContinueError(\"busy\", \"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst runQueuedMessages = (): Promise<void> | undefined => {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\treturn this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\treturn this.runPromptMessages(queuedFollowUps);\n\t\t\t}\n\n\t\t\treturn undefined;\n\t\t};\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tconst queuedRun = runQueuedMessages();\n\t\t\tif (queuedRun) {\n\t\t\t\tawait queuedRun;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new AgentContinueError(\"nothing-to-continue\", \"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedRun = runQueuedMessages();\n\t\t\tif (queuedRun) {\n\t\t\t\tawait queuedRun;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new AgentContinueError(\"nothing-to-continue\", \"Cannot continue from message role: assistant\");\n\t\t}\n\n\t\tconst lastMessageRole: string = lastMessage.role;\n\t\tif (lastMessageRole === \"custom\") {\n\t\t\tconst queuedRun = runQueuedMessages();\n\t\t\tif (queuedRun) {\n\t\t\t\tawait queuedRun;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\tconst onToolInvocationStarting = this.onToolInvocationStarting;\n\t\tconst onToolExchangeFinalized = this.onToolExchangeFinalized;\n\t\treturn {\n\t\t\toutputPolicy: this.activeOutputPolicy,\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel,\n\t\t\tserviceTier: this._state.serviceTier,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tonToolInvocationStarting: async (invocation, signal, tool, execute, assistantMessage) => {\n\t\t\t\tconst owner = await this.toolExecutionOwner?.onToolInvocationStarting(\n\t\t\t\t\tinvocation,\n\t\t\t\t\tsignal,\n\t\t\t\t\ttool,\n\t\t\t\t\texecute,\n\t\t\t\t\tassistantMessage,\n\t\t\t\t);\n\t\t\t\tawait onToolInvocationStarting?.(invocation, signal);\n\t\t\t\treturn owner || undefined;\n\t\t\t},\n\t\t\tonToolExchangeFinalized: async (exchange, signal, owner) => {\n\t\t\t\tif (owner) await owner.finalize(exchange, signal);\n\t\t\t\telse await this.toolExecutionOwner?.onToolExchangeFinalized(exchange, signal);\n\t\t\t\tawait onToolExchangeFinalized?.(exchange, signal);\n\t\t\t},\n\t\t\tshouldStopAfterTurn: async (context) => this.shouldStopAfterTurn?.(context) ?? false,\n\t\t\tgetTurnOutcome: this.getTurnOutcome?.bind(this),\n\t\t\tshouldStopBeforeTurn: () => this.shouldStopBeforeTurn?.() ?? false,\n\t\t\tbeforeContextBuild: async () => this.contextOwner?.(),\n\t\t\trecoverRequestPreparation: this.requestPreparationRecoveryOwner,\n\t\t\trecoverProviderFailure: this.providerFailureRecoveryOwner?.recover,\n\t\t\tonContextAdopted: (messages) => {\n\t\t\t\tthis._state.messages = messages;\n\t\t\t},\n\t\t\townedStreamFn: this.ownedStreamFn,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetSystemPrompt: () => this._state.systemPrompt,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t\tgetContinuationMessages: async (context, signal) => this.getContinuationMessages?.(context, signal) ?? [],\n\t\t\tgetContinuationOutcome: this.getContinuationOutcome?.bind(this),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tconst outputPolicy = this.outputOwner?.();\n\t\t\tthis.activeOutputPolicy = outputPolicy\n\t\t\t\t? {\n\t\t\t\t\t\tlimits: { ...outputPolicy.limits },\n\t\t\t\t\t\tsnapshot: outputPolicy.snapshot.bind(outputPolicy),\n\t\t\t\t\t\tbindUpdates: outputPolicy.bindUpdates?.bind(outputPolicy),\n\t\t\t\t\t\tsettleUpdates: outputPolicy.settleUpdates?.bind(outputPolicy),\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\t\t\tif (this.initializationOwner) {\n\t\t\t\tawait this.initializationOwner();\n\t\t\t\tabortController.signal.throwIfAborted();\n\t\t\t}\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tif (error instanceof AgentOutputLimitError || isRequestTokenBudgetFailure(error)) {\n\t\t\t\tthis._state.errorMessage = error.message;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tawait this.handleRunFailure(error, abortController.signal.aborted);\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tthis.providerFailureRecoveryOwner?.settle?.();\n\t\t\t} finally {\n\t\t\t\tthis.finishRun();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\tconst failureMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\t\tapi: this._state.model.api,\n\t\t\tprovider: this._state.model.provider,\n\t\t\tmodel: this._state.model.id,\n\t\t\tusage: EMPTY_USAGE,\n\t\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\tdiagnostics: aborted\n\t\t\t\t? undefined\n\t\t\t\t: [createAssistantMessageDiagnostic(\"agent_lifecycle_failure\", error, { source: \"run_with_lifecycle\" })],\n\t\t\ttimestamp: Date.now(),\n\t\t} satisfies AgentMessage;\n\t\tthis._state.errorMessage = failureMessage.errorMessage;\n\t\tawait this.processEvents({ type: \"message_start\", message: failureMessage }).catch(() => undefined);\n\t\tawait this.processEvents({ type: \"message_end\", message: failureMessage }).catch(() => undefined);\n\t\tawait this.processEvents({ type: \"agent_end\", messages: [failureMessage] }).catch(() => undefined);\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis.activeOutputPolicy = undefined;\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/**\n\t * Reduce internal state for a loop event, then await listeners.\n\t *\n\t * `agent_end` only means no further loop events will be emitted. The run is\n\t * considered idle later, after all awaited listeners for `agent_end` finish\n\t * and `finishRun()` clears runtime-owned state.\n\t */\n\tprivate async processEvents(event: AgentEvent): Promise<void> {\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.add(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tif (event.refusal) this._state.errorMessage = new AgentOutputLimitError(event.refusal).message;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tfor (const listener of this.listeners) {\n\t\t\tawait listener(event, signal);\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,KAAK,YAAY,EAEjB,KAAK,OAAO,EAEZ,KAAK,mBAAmB,EAGxB,KAAK,eAAe,EACpB,KAAK,SAAS,EACd,MAAM,+BAA+B,CAAC;AAGvC,OAAO,KAAK,EACX,oBAAoB,EACpB,mBAAmB,EAEnB,uBAAuB,EACvB,wBAAwB,EACxB,UAAU,EACV,eAAe,EACf,YAAY,EACZ,iBAAiB,EACjB,kBAAkB,EAClB,UAAU,EAEV,gBAAgB,EAChB,qBAAqB,EACrB,oBAAoB,EACpB,qBAAqB,EACrB,8BAA8B,EAC9B,qBAAqB,EACrB,0BAA0B,EAC1B,QAAQ,EACR,iBAAiB,EACjB,cAAc,EACd,MAAM,YAAY,CAAC;AA0BpB,KAAK,SAAS,GAAG,KAAK,GAAG,eAAe,CAAC;AAuCzC,MAAM,WAAW,YAAY;IAC5B,YAAY,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,UAAU,EAAE,kBAAkB,GAAG,aAAa,GAAG,kBAAkB,GAAG,cAAc,CAAC,CAAC,CAAC;IACnH,YAAY,CAAC,EAAE,CAAC,QAAQ,EAAE,YAAY,EAAE,KAAK,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;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IAEK,MAAM,CAAC,OAAO,EAAE,YAAY,GAAG,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9D,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAWpE,sEAAsE;IAChE,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAkD9B;IAED,OAAO,CAAC,oBAAoB;YAmBd,iBAAiB;YAgBjB,eAAe;IAY7B,OAAO,CAAC,qBAAqB;IAQ7B,OAAO,CAAC,gBAAgB;YA+DV,gBAAgB;YAgDhB,gBAAgB;IAsB9B,OAAO,CAAC,SAAS;YAgBH,aAAa;CAiD3B","sourcesContent":["import {\n\tcreateAssistantMessageDiagnostic,\n\ttype ImageContent,\n\tisLocalRequestPreparationError,\n\ttype Message,\n\tRequestTokenBudgetError,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"@ponythewhite/base-context-ai\";\nimport { runAgentLoop, runAgentLoopContinue } from \"./agent-loop.js\";\nimport { AgentOutputLimitError } from \"./invocation-output.js\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentContextBuildResult,\n\tAgentContinuationOutcome,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentOutputPolicy,\n\tAgentOwnedStreamFn,\n\tAgentState,\n\tAgentTool,\n\tAgentTurnOutcome,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tFinalizedToolExchange,\n\tGetContinuationMessagesContext,\n\tGetTurnOutcomeContext,\n\tShouldStopAfterTurnContext,\n\tStreamFn,\n\tToolExecutionMode,\n\tToolInvocation,\n} from \"./types.js\";\n\n/** Preserve actual local request preparation failures and primary cleanup chains without inventing an assistant. */\nfunction isRequestTokenBudgetFailure(error: unknown): error is Error {\n\treturn (\n\t\terror instanceof RequestTokenBudgetError ||\n\t\tisLocalRequestPreparationError(error) ||\n\t\t(error instanceof AggregateError && isRequestTokenBudgetFailure(error.errors[0]))\n\t);\n}\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) => message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\",\n\t);\n}\n\nconst EMPTY_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\ntype QueueMode = \"all\" | \"one-at-a-time\";\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\nfunction createMutableAgentState(\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>,\n): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\n\treturn {\n\t\tsystemPrompt: initialState?.systemPrompt ?? \"\",\n\t\tmodel: initialState?.model,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tserviceTier: initialState?.serviceTier ?? \"default\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tonToolInvocationStarting?: (invocation: ToolInvocation, signal?: AbortSignal) => void | Promise<void>;\n\tonToolExchangeFinalized?: (exchange: FinalizedToolExchange, signal?: AbortSignal) => void | Promise<void>;\n\tshouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;\n\tgetTurnOutcome?: (\n\t\tcontext: GetTurnOutcomeContext,\n\t\tsignal?: AbortSignal,\n\t) => AgentTurnOutcome | Promise<AgentTurnOutcome>;\n\tshouldStopBeforeTurn?: () => boolean;\n\tgetContinuationMessages?: (context: GetContinuationMessagesContext, signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tgetContinuationOutcome?: (\n\t\tcontext: GetContinuationMessagesContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentContinuationOutcome>;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\ttoolExecution?: ToolExecutionMode;\n}\n\nclass PendingMessageQueue {\n\tprivate batches: AgentMessage[][] = [];\n\n\tconstructor(public mode: QueueMode) {}\n\n\tenqueue(message: AgentMessage | AgentMessage[]): void {\n\t\tconst batch = Array.isArray(message) ? message.slice() : [message];\n\t\tif (batch.length > 0) {\n\t\t\tthis.batches.push(batch);\n\t\t}\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.batches.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.batches.flat();\n\t\t\tthis.batches = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.batches[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.batches = this.batches.slice(1);\n\t\treturn first;\n\t}\n\n\tclear(): void {\n\t\tthis.batches = [];\n\t}\n\n\tremoveWhere(predicate: (message: AgentMessage) => boolean): AgentMessage[] {\n\t\tconst removed: AgentMessage[] = [];\n\t\tconst retained: AgentMessage[][] = [];\n\t\tfor (const batch of this.batches) {\n\t\t\tif (batch.some(predicate)) {\n\t\t\t\tremoved.push(...batch);\n\t\t\t} else {\n\t\t\t\tretained.push(batch);\n\t\t\t}\n\t\t}\n\t\tthis.batches = retained;\n\t\treturn removed;\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/** Why {@link Agent.continue} refused to start a continuation. */\nexport type AgentContinueErrorCode = \"busy\" | \"nothing-to-continue\";\n\n/** Typed precondition failure from {@link Agent.continue}, so callers classify by code instead of message text. */\nexport class AgentContinueError extends Error {\n\tconstructor(\n\t\treadonly code: AgentContinueErrorCode,\n\t\tmessage: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"AgentContinueError\";\n\t}\n}\n\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tprivate initializationOwner?: () => Promise<void>;\n\tprivate contextOwner?: () => Promise<AgentContextBuildResult>;\n\tprivate requestPreparationRecoveryOwner?: AgentLoopConfig[\"recoverRequestPreparation\"];\n\tprivate providerFailureRecoveryOwner?: {\n\t\trecover: NonNullable<AgentLoopConfig[\"recoverProviderFailure\"]>;\n\t\tsettle?: () => void;\n\t};\n\tprivate outputOwner?: () => AgentOutputPolicy | undefined;\n\tprivate activeOutputPolicy?: AgentOutputPolicy;\n\n\t/** Native sinks join finalized message values; configuration is captured once per invocation. */\n\tbindOutputOwner(owner: () => AgentOutputPolicy | undefined): void {\n\t\tif (this.outputOwner) throw new Error(\"Agent output owner is already bound\");\n\t\tthis.outputOwner = owner;\n\t}\n\n\t/** Finish native initialization before capturing context or emitting loop events. */\n\tbindInitializationOwner(owner: () => Promise<void>): void {\n\t\tif (this.initializationOwner) throw new Error(\"Agent initialization owner is already bound\");\n\t\tthis.initializationOwner = owner;\n\t}\n\n\t/** Native persistence remains ahead of replaceable context callbacks. */\n\tbindContextOwner(owner: () => Promise<AgentContextBuildResult>): void {\n\t\tif (this.contextOwner) throw new Error(\"Agent context owner is already bound\");\n\t\tthis.contextOwner = owner;\n\t}\n\n\tbindRequestPreparationRecoveryOwner(owner: NonNullable<AgentLoopConfig[\"recoverRequestPreparation\"]>): void {\n\t\tif (this.requestPreparationRecoveryOwner)\n\t\t\tthrow new Error(\"Agent request preparation recovery owner is already bound\");\n\t\tthis.requestPreparationRecoveryOwner = owner;\n\t}\n\n\tbindProviderFailureRecoveryOwner(owner: {\n\t\trecover: NonNullable<AgentLoopConfig[\"recoverProviderFailure\"]>;\n\t\tsettle?: () => void;\n\t}): void {\n\t\tif (this.providerFailureRecoveryOwner) throw new Error(\"Agent provider failure recovery owner is already bound\");\n\t\tthis.providerFailureRecoveryOwner = owner;\n\t}\n\n\tprivate configuredStreamFn!: StreamFn;\n\tprivate effectiveStreamFn!: StreamFn;\n\tprivate ownedStreamFn?: AgentOwnedStreamFn;\n\tprivate streamOwner?: (streamFn: StreamFn) => AgentOwnedStreamFn;\n\n\tget streamFn(): StreamFn {\n\t\treturn this.effectiveStreamFn;\n\t}\n\tset streamFn(streamFn: StreamFn) {\n\t\tthis.configuredStreamFn = streamFn;\n\t\tconst ownedStreamFn = this.streamOwner?.(streamFn);\n\t\tthis.ownedStreamFn = ownedStreamFn;\n\t\tthis.effectiveStreamFn = ownedStreamFn ?? streamFn;\n\t}\n\n\t/** A native owner remains in the path when an embedding changes its configured stream. */\n\tbindStreamOwner(owner: (streamFn: StreamFn) => AgentOwnedStreamFn): void {\n\t\tif (this.streamOwner) throw new Error(\"Agent stream owner is already bound\");\n\t\tthis.streamOwner = owner;\n\t\tthis.streamFn = this.configuredStreamFn;\n\t}\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic onToolInvocationStarting?: (invocation: ToolInvocation, signal?: AbortSignal) => void | Promise<void>;\n\tpublic onToolExchangeFinalized?: (exchange: FinalizedToolExchange, signal?: AbortSignal) => void | Promise<void>;\n\tprivate toolExecutionOwner?: Required<Pick<AgentLoopConfig, \"onToolInvocationStarting\" | \"onToolExchangeFinalized\">>;\n\n\t/** Native persistence runs before replaceable caller hooks. */\n\tbindToolExecutionOwner(\n\t\towner: Required<Pick<AgentLoopConfig, \"onToolInvocationStarting\" | \"onToolExchangeFinalized\">>,\n\t): void {\n\t\tif (this.toolExecutionOwner) throw new Error(\"Agent tool execution owner is already bound\");\n\t\tthis.toolExecutionOwner = {\n\t\t\tonToolInvocationStarting: owner.onToolInvocationStarting,\n\t\t\tonToolExchangeFinalized: owner.onToolExchangeFinalized,\n\t\t};\n\t}\n\n\tpublic shouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;\n\tpublic getTurnOutcome?: (\n\t\tcontext: GetTurnOutcomeContext,\n\t\tsignal?: AbortSignal,\n\t) => AgentTurnOutcome | Promise<AgentTurnOutcome>;\n\tpublic shouldStopBeforeTurn?: () => boolean;\n\tpublic getContinuationMessages?: (\n\t\tcontext: GetContinuationMessagesContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentMessage[]>;\n\tpublic getContinuationOutcome?: (\n\t\tcontext: GetContinuationMessagesContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentContinuationOutcome>;\n\tprivate activeRun?: ActiveRun;\n\tpublic sessionId?: string;\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\tpublic transport: Transport;\n\tpublic maxRetryDelayMs?: number;\n\tpublic toolExecution: ToolExecutionMode;\n\n\tconstructor(options: AgentOptions = {}) {\n\t\tthis._state = createMutableAgentState(options.initialState);\n\t\tthis.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = options.transformContext;\n\t\tthis.streamFn = options.streamFn ?? streamSimple;\n\t\tthis.getApiKey = options.getApiKey;\n\t\tthis.onPayload = options.onPayload;\n\t\tthis.onResponse = options.onResponse;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.onToolInvocationStarting = options.onToolInvocationStarting;\n\t\tthis.onToolExchangeFinalized = options.onToolExchangeFinalized;\n\t\tthis.shouldStopAfterTurn = options.shouldStopAfterTurn;\n\t\tthis.getTurnOutcome = options.getTurnOutcome;\n\t\tthis.shouldStopBeforeTurn = options.shouldStopBeforeTurn;\n\t\tthis.getContinuationMessages = options.getContinuationMessages;\n\t\tthis.getContinuationOutcome = options.getContinuationOutcome;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.toolExecution = options.toolExecution ?? \"parallel\";\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order and are included in\n\t * the current run's settlement. Listeners also receive the active abort\n\t * signal for the current run.\n\t *\n\t * `agent_end` is the final emitted event for a run, but the agent does not\n\t * become idle until all awaited listeners for that event have settled.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message batch to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage | AgentMessage[]): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message batch to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage | AgentMessage[]): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\tremoveQueuedMessages(predicate: (message: AgentMessage) => boolean): AgentMessage[] {\n\t\treturn [...this.steeringQueue.removeWhere(predicate), ...this.followUpQueue.removeWhere(predicate)];\n\t}\n\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** The last message must convert to a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new AgentContinueError(\"busy\", \"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst runQueuedMessages = (): Promise<void> | undefined => {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\treturn this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\treturn this.runPromptMessages(queuedFollowUps);\n\t\t\t}\n\n\t\t\treturn undefined;\n\t\t};\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tconst queuedRun = runQueuedMessages();\n\t\t\tif (queuedRun) {\n\t\t\t\tawait queuedRun;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new AgentContinueError(\"nothing-to-continue\", \"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedRun = runQueuedMessages();\n\t\t\tif (queuedRun) {\n\t\t\t\tawait queuedRun;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new AgentContinueError(\"nothing-to-continue\", \"Cannot continue from message role: assistant\");\n\t\t}\n\n\t\tconst lastMessageRole: string = lastMessage.role;\n\t\tif (lastMessageRole === \"custom\") {\n\t\t\tconst queuedRun = runQueuedMessages();\n\t\t\tif (queuedRun) {\n\t\t\t\tawait queuedRun;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tif (!this._state.model)\n\t\t\tthrow new Error(\"No model selected. Select a provider and model before starting the agent.\");\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\tconst onToolInvocationStarting = this.onToolInvocationStarting;\n\t\tconst onToolExchangeFinalized = this.onToolExchangeFinalized;\n\t\treturn {\n\t\t\toutputPolicy: this.activeOutputPolicy,\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel,\n\t\t\tserviceTier: this._state.serviceTier,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tonToolInvocationStarting: async (invocation, signal, tool, execute, assistantMessage) => {\n\t\t\t\tconst owner = await this.toolExecutionOwner?.onToolInvocationStarting(\n\t\t\t\t\tinvocation,\n\t\t\t\t\tsignal,\n\t\t\t\t\ttool,\n\t\t\t\t\texecute,\n\t\t\t\t\tassistantMessage,\n\t\t\t\t);\n\t\t\t\tawait onToolInvocationStarting?.(invocation, signal);\n\t\t\t\treturn owner || undefined;\n\t\t\t},\n\t\t\tonToolExchangeFinalized: async (exchange, signal, owner) => {\n\t\t\t\tif (owner) await owner.finalize(exchange, signal);\n\t\t\t\telse await this.toolExecutionOwner?.onToolExchangeFinalized(exchange, signal);\n\t\t\t\tawait onToolExchangeFinalized?.(exchange, signal);\n\t\t\t},\n\t\t\tshouldStopAfterTurn: async (context) => this.shouldStopAfterTurn?.(context) ?? false,\n\t\t\tgetTurnOutcome: this.getTurnOutcome?.bind(this),\n\t\t\tshouldStopBeforeTurn: () => this.shouldStopBeforeTurn?.() ?? false,\n\t\t\tbeforeContextBuild: async () => this.contextOwner?.(),\n\t\t\trecoverRequestPreparation: this.requestPreparationRecoveryOwner,\n\t\t\trecoverProviderFailure: this.providerFailureRecoveryOwner?.recover,\n\t\t\tonContextAdopted: (messages) => {\n\t\t\t\tthis._state.messages = messages;\n\t\t\t},\n\t\t\townedStreamFn: this.ownedStreamFn,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetSystemPrompt: () => this._state.systemPrompt,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t\tgetContinuationMessages: async (context, signal) => this.getContinuationMessages?.(context, signal) ?? [],\n\t\t\tgetContinuationOutcome: this.getContinuationOutcome?.bind(this),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\t\tif (!this._state.model)\n\t\t\tthrow new Error(\"No model selected. Select a provider and model before starting the agent.\");\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tconst outputPolicy = this.outputOwner?.();\n\t\t\tthis.activeOutputPolicy = outputPolicy\n\t\t\t\t? {\n\t\t\t\t\t\tlimits: { ...outputPolicy.limits },\n\t\t\t\t\t\tsnapshot: outputPolicy.snapshot.bind(outputPolicy),\n\t\t\t\t\t\tbindUpdates: outputPolicy.bindUpdates?.bind(outputPolicy),\n\t\t\t\t\t\tsettleUpdates: outputPolicy.settleUpdates?.bind(outputPolicy),\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\t\t\tif (this.initializationOwner) {\n\t\t\t\tawait this.initializationOwner();\n\t\t\t\tabortController.signal.throwIfAborted();\n\t\t\t}\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tif (error instanceof AgentOutputLimitError || isRequestTokenBudgetFailure(error)) {\n\t\t\t\tthis._state.errorMessage = error.message;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tawait this.handleRunFailure(error, abortController.signal.aborted);\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tthis.providerFailureRecoveryOwner?.settle?.();\n\t\t\t} finally {\n\t\t\t\tthis.finishRun();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\tif (!this._state.model) throw error;\n\t\tconst failureMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\t\tapi: this._state.model.api,\n\t\t\tprovider: this._state.model.provider,\n\t\t\tmodel: this._state.model.id,\n\t\t\tusage: EMPTY_USAGE,\n\t\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\tdiagnostics: aborted\n\t\t\t\t? undefined\n\t\t\t\t: [createAssistantMessageDiagnostic(\"agent_lifecycle_failure\", error, { source: \"run_with_lifecycle\" })],\n\t\t\ttimestamp: Date.now(),\n\t\t} satisfies AgentMessage;\n\t\tthis._state.errorMessage = failureMessage.errorMessage;\n\t\tawait this.processEvents({ type: \"message_start\", message: failureMessage }).catch(() => undefined);\n\t\tawait this.processEvents({ type: \"message_end\", message: failureMessage }).catch(() => undefined);\n\t\tawait this.processEvents({ type: \"agent_end\", messages: [failureMessage] }).catch(() => undefined);\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis.activeOutputPolicy = undefined;\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/**\n\t * Reduce internal state for a loop event, then await listeners.\n\t *\n\t * `agent_end` only means no further loop events will be emitted. The run is\n\t * considered idle later, after all awaited listeners for `agent_end` finish\n\t * and `finishRun()` clears runtime-owned state.\n\t */\n\tprivate async processEvents(event: AgentEvent): Promise<void> {\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.add(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tif (event.refusal) this._state.errorMessage = new AgentOutputLimitError(event.refusal).message;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tfor (const listener of this.listeners) {\n\t\t\tawait listener(event, signal);\n\t\t}\n\t}\n}\n"]}
package/dist/agent.js CHANGED
@@ -18,24 +18,12 @@ const EMPTY_USAGE = {
18
18
  totalTokens: 0,
19
19
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
20
20
  };
21
- const DEFAULT_MODEL = {
22
- id: "unknown",
23
- name: "unknown",
24
- api: "unknown",
25
- provider: "unknown",
26
- baseUrl: "",
27
- reasoning: false,
28
- input: [],
29
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
30
- contextWindow: 0,
31
- maxTokens: 0,
32
- };
33
21
  function createMutableAgentState(initialState) {
34
22
  let tools = initialState?.tools?.slice() ?? [];
35
23
  let messages = initialState?.messages?.slice() ?? [];
36
24
  return {
37
25
  systemPrompt: initialState?.systemPrompt ?? "",
38
- model: initialState?.model ?? DEFAULT_MODEL,
26
+ model: initialState?.model,
39
27
  thinkingLevel: initialState?.thinkingLevel ?? "off",
40
28
  serviceTier: initialState?.serviceTier ?? "default",
41
29
  get tools() {
@@ -387,6 +375,8 @@ export class Agent {
387
375
  };
388
376
  }
389
377
  createLoopConfig(options = {}) {
378
+ if (!this._state.model)
379
+ throw new Error("No model selected. Select a provider and model before starting the agent.");
390
380
  let skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;
391
381
  const onToolInvocationStarting = this.onToolInvocationStarting;
392
382
  const onToolExchangeFinalized = this.onToolExchangeFinalized;
@@ -446,6 +436,8 @@ export class Agent {
446
436
  if (this.activeRun) {
447
437
  throw new Error("Agent is already processing.");
448
438
  }
439
+ if (!this._state.model)
440
+ throw new Error("No model selected. Select a provider and model before starting the agent.");
449
441
  const abortController = new AbortController();
450
442
  let resolvePromise = () => { };
451
443
  const promise = new Promise((resolve) => {
@@ -488,6 +480,8 @@ export class Agent {
488
480
  }
489
481
  }
490
482
  async handleRunFailure(error, aborted) {
483
+ if (!this._state.model)
484
+ throw error;
491
485
  const failureMessage = {
492
486
  role: "assistant",
493
487
  content: [{ type: "text", text: "" }],
package/dist/agent.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,gCAAgC,EAEhC,8BAA8B,EAG9B,uBAAuB,EAEvB,YAAY,GAIZ,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACrE,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AA0B/D,oHAAoH;AACpH,SAAS,2BAA2B,CAAC,KAAc,EAAkB;IACpE,OAAO,CACN,KAAK,YAAY,uBAAuB;QAC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AC,MAAM,CAAC,YAAY,GAAG,IAAI,qBAAqB,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC;gBAC/F,MAAM;QACR,CAAC;QAED,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,EAAE,eAAe,CAAC,MAAM,CAAC;QACtD,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;QAC9D,CAAC;QACD,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACvC,MAAM,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAC/B,CAAC;IAAA,CACD;CACD","sourcesContent":["import {\n\tcreateAssistantMessageDiagnostic,\n\ttype ImageContent,\n\tisLocalRequestPreparationError,\n\ttype Message,\n\ttype Model,\n\tRequestTokenBudgetError,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"@ponythewhite/base-context-ai\";\nimport { runAgentLoop, runAgentLoopContinue } from \"./agent-loop.js\";\nimport { AgentOutputLimitError } from \"./invocation-output.js\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentContextBuildResult,\n\tAgentContinuationOutcome,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentOutputPolicy,\n\tAgentOwnedStreamFn,\n\tAgentState,\n\tAgentTool,\n\tAgentTurnOutcome,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tFinalizedToolExchange,\n\tGetContinuationMessagesContext,\n\tGetTurnOutcomeContext,\n\tShouldStopAfterTurnContext,\n\tStreamFn,\n\tToolExecutionMode,\n\tToolInvocation,\n} from \"./types.js\";\n\n/** Preserve actual local request preparation failures and primary cleanup chains without inventing an assistant. */\nfunction isRequestTokenBudgetFailure(error: unknown): error is Error {\n\treturn (\n\t\terror instanceof RequestTokenBudgetError ||\n\t\tisLocalRequestPreparationError(error) ||\n\t\t(error instanceof AggregateError && isRequestTokenBudgetFailure(error.errors[0]))\n\t);\n}\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) => message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\",\n\t);\n}\n\nconst EMPTY_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\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype QueueMode = \"all\" | \"one-at-a-time\";\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\nfunction createMutableAgentState(\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>,\n): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\n\treturn {\n\t\tsystemPrompt: initialState?.systemPrompt ?? \"\",\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tserviceTier: initialState?.serviceTier ?? \"default\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tonToolInvocationStarting?: (invocation: ToolInvocation, signal?: AbortSignal) => void | Promise<void>;\n\tonToolExchangeFinalized?: (exchange: FinalizedToolExchange, signal?: AbortSignal) => void | Promise<void>;\n\tshouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;\n\tgetTurnOutcome?: (\n\t\tcontext: GetTurnOutcomeContext,\n\t\tsignal?: AbortSignal,\n\t) => AgentTurnOutcome | Promise<AgentTurnOutcome>;\n\tshouldStopBeforeTurn?: () => boolean;\n\tgetContinuationMessages?: (context: GetContinuationMessagesContext, signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tgetContinuationOutcome?: (\n\t\tcontext: GetContinuationMessagesContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentContinuationOutcome>;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\ttoolExecution?: ToolExecutionMode;\n}\n\nclass PendingMessageQueue {\n\tprivate batches: AgentMessage[][] = [];\n\n\tconstructor(public mode: QueueMode) {}\n\n\tenqueue(message: AgentMessage | AgentMessage[]): void {\n\t\tconst batch = Array.isArray(message) ? message.slice() : [message];\n\t\tif (batch.length > 0) {\n\t\t\tthis.batches.push(batch);\n\t\t}\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.batches.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.batches.flat();\n\t\t\tthis.batches = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.batches[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.batches = this.batches.slice(1);\n\t\treturn first;\n\t}\n\n\tclear(): void {\n\t\tthis.batches = [];\n\t}\n\n\tremoveWhere(predicate: (message: AgentMessage) => boolean): AgentMessage[] {\n\t\tconst removed: AgentMessage[] = [];\n\t\tconst retained: AgentMessage[][] = [];\n\t\tfor (const batch of this.batches) {\n\t\t\tif (batch.some(predicate)) {\n\t\t\t\tremoved.push(...batch);\n\t\t\t} else {\n\t\t\t\tretained.push(batch);\n\t\t\t}\n\t\t}\n\t\tthis.batches = retained;\n\t\treturn removed;\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/** Why {@link Agent.continue} refused to start a continuation. */\nexport type AgentContinueErrorCode = \"busy\" | \"nothing-to-continue\";\n\n/** Typed precondition failure from {@link Agent.continue}, so callers classify by code instead of message text. */\nexport class AgentContinueError extends Error {\n\tconstructor(\n\t\treadonly code: AgentContinueErrorCode,\n\t\tmessage: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"AgentContinueError\";\n\t}\n}\n\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tprivate initializationOwner?: () => Promise<void>;\n\tprivate contextOwner?: () => Promise<AgentContextBuildResult>;\n\tprivate requestPreparationRecoveryOwner?: AgentLoopConfig[\"recoverRequestPreparation\"];\n\tprivate providerFailureRecoveryOwner?: {\n\t\trecover: NonNullable<AgentLoopConfig[\"recoverProviderFailure\"]>;\n\t\tsettle?: () => void;\n\t};\n\tprivate outputOwner?: () => AgentOutputPolicy | undefined;\n\tprivate activeOutputPolicy?: AgentOutputPolicy;\n\n\t/** Native sinks join finalized message values; configuration is captured once per invocation. */\n\tbindOutputOwner(owner: () => AgentOutputPolicy | undefined): void {\n\t\tif (this.outputOwner) throw new Error(\"Agent output owner is already bound\");\n\t\tthis.outputOwner = owner;\n\t}\n\n\t/** Finish native initialization before capturing context or emitting loop events. */\n\tbindInitializationOwner(owner: () => Promise<void>): void {\n\t\tif (this.initializationOwner) throw new Error(\"Agent initialization owner is already bound\");\n\t\tthis.initializationOwner = owner;\n\t}\n\n\t/** Native persistence remains ahead of replaceable context callbacks. */\n\tbindContextOwner(owner: () => Promise<AgentContextBuildResult>): void {\n\t\tif (this.contextOwner) throw new Error(\"Agent context owner is already bound\");\n\t\tthis.contextOwner = owner;\n\t}\n\n\tbindRequestPreparationRecoveryOwner(owner: NonNullable<AgentLoopConfig[\"recoverRequestPreparation\"]>): void {\n\t\tif (this.requestPreparationRecoveryOwner)\n\t\t\tthrow new Error(\"Agent request preparation recovery owner is already bound\");\n\t\tthis.requestPreparationRecoveryOwner = owner;\n\t}\n\n\tbindProviderFailureRecoveryOwner(owner: {\n\t\trecover: NonNullable<AgentLoopConfig[\"recoverProviderFailure\"]>;\n\t\tsettle?: () => void;\n\t}): void {\n\t\tif (this.providerFailureRecoveryOwner) throw new Error(\"Agent provider failure recovery owner is already bound\");\n\t\tthis.providerFailureRecoveryOwner = owner;\n\t}\n\n\tprivate configuredStreamFn!: StreamFn;\n\tprivate effectiveStreamFn!: StreamFn;\n\tprivate ownedStreamFn?: AgentOwnedStreamFn;\n\tprivate streamOwner?: (streamFn: StreamFn) => AgentOwnedStreamFn;\n\n\tget streamFn(): StreamFn {\n\t\treturn this.effectiveStreamFn;\n\t}\n\tset streamFn(streamFn: StreamFn) {\n\t\tthis.configuredStreamFn = streamFn;\n\t\tconst ownedStreamFn = this.streamOwner?.(streamFn);\n\t\tthis.ownedStreamFn = ownedStreamFn;\n\t\tthis.effectiveStreamFn = ownedStreamFn ?? streamFn;\n\t}\n\n\t/** A native owner remains in the path when an embedding changes its configured stream. */\n\tbindStreamOwner(owner: (streamFn: StreamFn) => AgentOwnedStreamFn): void {\n\t\tif (this.streamOwner) throw new Error(\"Agent stream owner is already bound\");\n\t\tthis.streamOwner = owner;\n\t\tthis.streamFn = this.configuredStreamFn;\n\t}\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic onToolInvocationStarting?: (invocation: ToolInvocation, signal?: AbortSignal) => void | Promise<void>;\n\tpublic onToolExchangeFinalized?: (exchange: FinalizedToolExchange, signal?: AbortSignal) => void | Promise<void>;\n\tprivate toolExecutionOwner?: Required<Pick<AgentLoopConfig, \"onToolInvocationStarting\" | \"onToolExchangeFinalized\">>;\n\n\t/** Native persistence runs before replaceable caller hooks. */\n\tbindToolExecutionOwner(\n\t\towner: Required<Pick<AgentLoopConfig, \"onToolInvocationStarting\" | \"onToolExchangeFinalized\">>,\n\t): void {\n\t\tif (this.toolExecutionOwner) throw new Error(\"Agent tool execution owner is already bound\");\n\t\tthis.toolExecutionOwner = {\n\t\t\tonToolInvocationStarting: owner.onToolInvocationStarting,\n\t\t\tonToolExchangeFinalized: owner.onToolExchangeFinalized,\n\t\t};\n\t}\n\n\tpublic shouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;\n\tpublic getTurnOutcome?: (\n\t\tcontext: GetTurnOutcomeContext,\n\t\tsignal?: AbortSignal,\n\t) => AgentTurnOutcome | Promise<AgentTurnOutcome>;\n\tpublic shouldStopBeforeTurn?: () => boolean;\n\tpublic getContinuationMessages?: (\n\t\tcontext: GetContinuationMessagesContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentMessage[]>;\n\tpublic getContinuationOutcome?: (\n\t\tcontext: GetContinuationMessagesContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentContinuationOutcome>;\n\tprivate activeRun?: ActiveRun;\n\tpublic sessionId?: string;\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\tpublic transport: Transport;\n\tpublic maxRetryDelayMs?: number;\n\tpublic toolExecution: ToolExecutionMode;\n\n\tconstructor(options: AgentOptions = {}) {\n\t\tthis._state = createMutableAgentState(options.initialState);\n\t\tthis.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = options.transformContext;\n\t\tthis.streamFn = options.streamFn ?? streamSimple;\n\t\tthis.getApiKey = options.getApiKey;\n\t\tthis.onPayload = options.onPayload;\n\t\tthis.onResponse = options.onResponse;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.onToolInvocationStarting = options.onToolInvocationStarting;\n\t\tthis.onToolExchangeFinalized = options.onToolExchangeFinalized;\n\t\tthis.shouldStopAfterTurn = options.shouldStopAfterTurn;\n\t\tthis.getTurnOutcome = options.getTurnOutcome;\n\t\tthis.shouldStopBeforeTurn = options.shouldStopBeforeTurn;\n\t\tthis.getContinuationMessages = options.getContinuationMessages;\n\t\tthis.getContinuationOutcome = options.getContinuationOutcome;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.toolExecution = options.toolExecution ?? \"parallel\";\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order and are included in\n\t * the current run's settlement. Listeners also receive the active abort\n\t * signal for the current run.\n\t *\n\t * `agent_end` is the final emitted event for a run, but the agent does not\n\t * become idle until all awaited listeners for that event have settled.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message batch to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage | AgentMessage[]): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message batch to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage | AgentMessage[]): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\tremoveQueuedMessages(predicate: (message: AgentMessage) => boolean): AgentMessage[] {\n\t\treturn [...this.steeringQueue.removeWhere(predicate), ...this.followUpQueue.removeWhere(predicate)];\n\t}\n\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** The last message must convert to a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new AgentContinueError(\"busy\", \"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst runQueuedMessages = (): Promise<void> | undefined => {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\treturn this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\treturn this.runPromptMessages(queuedFollowUps);\n\t\t\t}\n\n\t\t\treturn undefined;\n\t\t};\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tconst queuedRun = runQueuedMessages();\n\t\t\tif (queuedRun) {\n\t\t\t\tawait queuedRun;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new AgentContinueError(\"nothing-to-continue\", \"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedRun = runQueuedMessages();\n\t\t\tif (queuedRun) {\n\t\t\t\tawait queuedRun;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new AgentContinueError(\"nothing-to-continue\", \"Cannot continue from message role: assistant\");\n\t\t}\n\n\t\tconst lastMessageRole: string = lastMessage.role;\n\t\tif (lastMessageRole === \"custom\") {\n\t\t\tconst queuedRun = runQueuedMessages();\n\t\t\tif (queuedRun) {\n\t\t\t\tawait queuedRun;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\tconst onToolInvocationStarting = this.onToolInvocationStarting;\n\t\tconst onToolExchangeFinalized = this.onToolExchangeFinalized;\n\t\treturn {\n\t\t\toutputPolicy: this.activeOutputPolicy,\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel,\n\t\t\tserviceTier: this._state.serviceTier,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tonToolInvocationStarting: async (invocation, signal, tool, execute, assistantMessage) => {\n\t\t\t\tconst owner = await this.toolExecutionOwner?.onToolInvocationStarting(\n\t\t\t\t\tinvocation,\n\t\t\t\t\tsignal,\n\t\t\t\t\ttool,\n\t\t\t\t\texecute,\n\t\t\t\t\tassistantMessage,\n\t\t\t\t);\n\t\t\t\tawait onToolInvocationStarting?.(invocation, signal);\n\t\t\t\treturn owner || undefined;\n\t\t\t},\n\t\t\tonToolExchangeFinalized: async (exchange, signal, owner) => {\n\t\t\t\tif (owner) await owner.finalize(exchange, signal);\n\t\t\t\telse await this.toolExecutionOwner?.onToolExchangeFinalized(exchange, signal);\n\t\t\t\tawait onToolExchangeFinalized?.(exchange, signal);\n\t\t\t},\n\t\t\tshouldStopAfterTurn: async (context) => this.shouldStopAfterTurn?.(context) ?? false,\n\t\t\tgetTurnOutcome: this.getTurnOutcome?.bind(this),\n\t\t\tshouldStopBeforeTurn: () => this.shouldStopBeforeTurn?.() ?? false,\n\t\t\tbeforeContextBuild: async () => this.contextOwner?.(),\n\t\t\trecoverRequestPreparation: this.requestPreparationRecoveryOwner,\n\t\t\trecoverProviderFailure: this.providerFailureRecoveryOwner?.recover,\n\t\t\tonContextAdopted: (messages) => {\n\t\t\t\tthis._state.messages = messages;\n\t\t\t},\n\t\t\townedStreamFn: this.ownedStreamFn,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetSystemPrompt: () => this._state.systemPrompt,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t\tgetContinuationMessages: async (context, signal) => this.getContinuationMessages?.(context, signal) ?? [],\n\t\t\tgetContinuationOutcome: this.getContinuationOutcome?.bind(this),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tconst outputPolicy = this.outputOwner?.();\n\t\t\tthis.activeOutputPolicy = outputPolicy\n\t\t\t\t? {\n\t\t\t\t\t\tlimits: { ...outputPolicy.limits },\n\t\t\t\t\t\tsnapshot: outputPolicy.snapshot.bind(outputPolicy),\n\t\t\t\t\t\tbindUpdates: outputPolicy.bindUpdates?.bind(outputPolicy),\n\t\t\t\t\t\tsettleUpdates: outputPolicy.settleUpdates?.bind(outputPolicy),\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\t\t\tif (this.initializationOwner) {\n\t\t\t\tawait this.initializationOwner();\n\t\t\t\tabortController.signal.throwIfAborted();\n\t\t\t}\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tif (error instanceof AgentOutputLimitError || isRequestTokenBudgetFailure(error)) {\n\t\t\t\tthis._state.errorMessage = error.message;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tawait this.handleRunFailure(error, abortController.signal.aborted);\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tthis.providerFailureRecoveryOwner?.settle?.();\n\t\t\t} finally {\n\t\t\t\tthis.finishRun();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\tconst failureMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\t\tapi: this._state.model.api,\n\t\t\tprovider: this._state.model.provider,\n\t\t\tmodel: this._state.model.id,\n\t\t\tusage: EMPTY_USAGE,\n\t\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\tdiagnostics: aborted\n\t\t\t\t? undefined\n\t\t\t\t: [createAssistantMessageDiagnostic(\"agent_lifecycle_failure\", error, { source: \"run_with_lifecycle\" })],\n\t\t\ttimestamp: Date.now(),\n\t\t} satisfies AgentMessage;\n\t\tthis._state.errorMessage = failureMessage.errorMessage;\n\t\tawait this.processEvents({ type: \"message_start\", message: failureMessage }).catch(() => undefined);\n\t\tawait this.processEvents({ type: \"message_end\", message: failureMessage }).catch(() => undefined);\n\t\tawait this.processEvents({ type: \"agent_end\", messages: [failureMessage] }).catch(() => undefined);\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis.activeOutputPolicy = undefined;\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/**\n\t * Reduce internal state for a loop event, then await listeners.\n\t *\n\t * `agent_end` only means no further loop events will be emitted. The run is\n\t * considered idle later, after all awaited listeners for `agent_end` finish\n\t * and `finishRun()` clears runtime-owned state.\n\t */\n\tprivate async processEvents(event: AgentEvent): Promise<void> {\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.add(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tif (event.refusal) this._state.errorMessage = new AgentOutputLimitError(event.refusal).message;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tfor (const listener of this.listeners) {\n\t\t\tawait listener(event, signal);\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,gCAAgC,EAEhC,8BAA8B,EAE9B,uBAAuB,EAEvB,YAAY,GAIZ,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACrE,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AA0B/D,oHAAoH;AACpH,SAAS,2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AAC,KAAK,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC;gBAC/F,MAAM;QACR,CAAC;QAED,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,EAAE,eAAe,CAAC,MAAM,CAAC;QACtD,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;QAC9D,CAAC;QACD,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACvC,MAAM,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAC/B,CAAC;IAAA,CACD;CACD","sourcesContent":["import {\n\tcreateAssistantMessageDiagnostic,\n\ttype ImageContent,\n\tisLocalRequestPreparationError,\n\ttype Message,\n\tRequestTokenBudgetError,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"@ponythewhite/base-context-ai\";\nimport { runAgentLoop, runAgentLoopContinue } from \"./agent-loop.js\";\nimport { AgentOutputLimitError } from \"./invocation-output.js\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentContextBuildResult,\n\tAgentContinuationOutcome,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentOutputPolicy,\n\tAgentOwnedStreamFn,\n\tAgentState,\n\tAgentTool,\n\tAgentTurnOutcome,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tFinalizedToolExchange,\n\tGetContinuationMessagesContext,\n\tGetTurnOutcomeContext,\n\tShouldStopAfterTurnContext,\n\tStreamFn,\n\tToolExecutionMode,\n\tToolInvocation,\n} from \"./types.js\";\n\n/** Preserve actual local request preparation failures and primary cleanup chains without inventing an assistant. */\nfunction isRequestTokenBudgetFailure(error: unknown): error is Error {\n\treturn (\n\t\terror instanceof RequestTokenBudgetError ||\n\t\tisLocalRequestPreparationError(error) ||\n\t\t(error instanceof AggregateError && isRequestTokenBudgetFailure(error.errors[0]))\n\t);\n}\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) => message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\",\n\t);\n}\n\nconst EMPTY_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\ntype QueueMode = \"all\" | \"one-at-a-time\";\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\nfunction createMutableAgentState(\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>,\n): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\n\treturn {\n\t\tsystemPrompt: initialState?.systemPrompt ?? \"\",\n\t\tmodel: initialState?.model,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tserviceTier: initialState?.serviceTier ?? \"default\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tonToolInvocationStarting?: (invocation: ToolInvocation, signal?: AbortSignal) => void | Promise<void>;\n\tonToolExchangeFinalized?: (exchange: FinalizedToolExchange, signal?: AbortSignal) => void | Promise<void>;\n\tshouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;\n\tgetTurnOutcome?: (\n\t\tcontext: GetTurnOutcomeContext,\n\t\tsignal?: AbortSignal,\n\t) => AgentTurnOutcome | Promise<AgentTurnOutcome>;\n\tshouldStopBeforeTurn?: () => boolean;\n\tgetContinuationMessages?: (context: GetContinuationMessagesContext, signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tgetContinuationOutcome?: (\n\t\tcontext: GetContinuationMessagesContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentContinuationOutcome>;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\ttoolExecution?: ToolExecutionMode;\n}\n\nclass PendingMessageQueue {\n\tprivate batches: AgentMessage[][] = [];\n\n\tconstructor(public mode: QueueMode) {}\n\n\tenqueue(message: AgentMessage | AgentMessage[]): void {\n\t\tconst batch = Array.isArray(message) ? message.slice() : [message];\n\t\tif (batch.length > 0) {\n\t\t\tthis.batches.push(batch);\n\t\t}\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.batches.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.batches.flat();\n\t\t\tthis.batches = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.batches[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.batches = this.batches.slice(1);\n\t\treturn first;\n\t}\n\n\tclear(): void {\n\t\tthis.batches = [];\n\t}\n\n\tremoveWhere(predicate: (message: AgentMessage) => boolean): AgentMessage[] {\n\t\tconst removed: AgentMessage[] = [];\n\t\tconst retained: AgentMessage[][] = [];\n\t\tfor (const batch of this.batches) {\n\t\t\tif (batch.some(predicate)) {\n\t\t\t\tremoved.push(...batch);\n\t\t\t} else {\n\t\t\t\tretained.push(batch);\n\t\t\t}\n\t\t}\n\t\tthis.batches = retained;\n\t\treturn removed;\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/** Why {@link Agent.continue} refused to start a continuation. */\nexport type AgentContinueErrorCode = \"busy\" | \"nothing-to-continue\";\n\n/** Typed precondition failure from {@link Agent.continue}, so callers classify by code instead of message text. */\nexport class AgentContinueError extends Error {\n\tconstructor(\n\t\treadonly code: AgentContinueErrorCode,\n\t\tmessage: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"AgentContinueError\";\n\t}\n}\n\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tprivate initializationOwner?: () => Promise<void>;\n\tprivate contextOwner?: () => Promise<AgentContextBuildResult>;\n\tprivate requestPreparationRecoveryOwner?: AgentLoopConfig[\"recoverRequestPreparation\"];\n\tprivate providerFailureRecoveryOwner?: {\n\t\trecover: NonNullable<AgentLoopConfig[\"recoverProviderFailure\"]>;\n\t\tsettle?: () => void;\n\t};\n\tprivate outputOwner?: () => AgentOutputPolicy | undefined;\n\tprivate activeOutputPolicy?: AgentOutputPolicy;\n\n\t/** Native sinks join finalized message values; configuration is captured once per invocation. */\n\tbindOutputOwner(owner: () => AgentOutputPolicy | undefined): void {\n\t\tif (this.outputOwner) throw new Error(\"Agent output owner is already bound\");\n\t\tthis.outputOwner = owner;\n\t}\n\n\t/** Finish native initialization before capturing context or emitting loop events. */\n\tbindInitializationOwner(owner: () => Promise<void>): void {\n\t\tif (this.initializationOwner) throw new Error(\"Agent initialization owner is already bound\");\n\t\tthis.initializationOwner = owner;\n\t}\n\n\t/** Native persistence remains ahead of replaceable context callbacks. */\n\tbindContextOwner(owner: () => Promise<AgentContextBuildResult>): void {\n\t\tif (this.contextOwner) throw new Error(\"Agent context owner is already bound\");\n\t\tthis.contextOwner = owner;\n\t}\n\n\tbindRequestPreparationRecoveryOwner(owner: NonNullable<AgentLoopConfig[\"recoverRequestPreparation\"]>): void {\n\t\tif (this.requestPreparationRecoveryOwner)\n\t\t\tthrow new Error(\"Agent request preparation recovery owner is already bound\");\n\t\tthis.requestPreparationRecoveryOwner = owner;\n\t}\n\n\tbindProviderFailureRecoveryOwner(owner: {\n\t\trecover: NonNullable<AgentLoopConfig[\"recoverProviderFailure\"]>;\n\t\tsettle?: () => void;\n\t}): void {\n\t\tif (this.providerFailureRecoveryOwner) throw new Error(\"Agent provider failure recovery owner is already bound\");\n\t\tthis.providerFailureRecoveryOwner = owner;\n\t}\n\n\tprivate configuredStreamFn!: StreamFn;\n\tprivate effectiveStreamFn!: StreamFn;\n\tprivate ownedStreamFn?: AgentOwnedStreamFn;\n\tprivate streamOwner?: (streamFn: StreamFn) => AgentOwnedStreamFn;\n\n\tget streamFn(): StreamFn {\n\t\treturn this.effectiveStreamFn;\n\t}\n\tset streamFn(streamFn: StreamFn) {\n\t\tthis.configuredStreamFn = streamFn;\n\t\tconst ownedStreamFn = this.streamOwner?.(streamFn);\n\t\tthis.ownedStreamFn = ownedStreamFn;\n\t\tthis.effectiveStreamFn = ownedStreamFn ?? streamFn;\n\t}\n\n\t/** A native owner remains in the path when an embedding changes its configured stream. */\n\tbindStreamOwner(owner: (streamFn: StreamFn) => AgentOwnedStreamFn): void {\n\t\tif (this.streamOwner) throw new Error(\"Agent stream owner is already bound\");\n\t\tthis.streamOwner = owner;\n\t\tthis.streamFn = this.configuredStreamFn;\n\t}\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic onToolInvocationStarting?: (invocation: ToolInvocation, signal?: AbortSignal) => void | Promise<void>;\n\tpublic onToolExchangeFinalized?: (exchange: FinalizedToolExchange, signal?: AbortSignal) => void | Promise<void>;\n\tprivate toolExecutionOwner?: Required<Pick<AgentLoopConfig, \"onToolInvocationStarting\" | \"onToolExchangeFinalized\">>;\n\n\t/** Native persistence runs before replaceable caller hooks. */\n\tbindToolExecutionOwner(\n\t\towner: Required<Pick<AgentLoopConfig, \"onToolInvocationStarting\" | \"onToolExchangeFinalized\">>,\n\t): void {\n\t\tif (this.toolExecutionOwner) throw new Error(\"Agent tool execution owner is already bound\");\n\t\tthis.toolExecutionOwner = {\n\t\t\tonToolInvocationStarting: owner.onToolInvocationStarting,\n\t\t\tonToolExchangeFinalized: owner.onToolExchangeFinalized,\n\t\t};\n\t}\n\n\tpublic shouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;\n\tpublic getTurnOutcome?: (\n\t\tcontext: GetTurnOutcomeContext,\n\t\tsignal?: AbortSignal,\n\t) => AgentTurnOutcome | Promise<AgentTurnOutcome>;\n\tpublic shouldStopBeforeTurn?: () => boolean;\n\tpublic getContinuationMessages?: (\n\t\tcontext: GetContinuationMessagesContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentMessage[]>;\n\tpublic getContinuationOutcome?: (\n\t\tcontext: GetContinuationMessagesContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentContinuationOutcome>;\n\tprivate activeRun?: ActiveRun;\n\tpublic sessionId?: string;\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\tpublic transport: Transport;\n\tpublic maxRetryDelayMs?: number;\n\tpublic toolExecution: ToolExecutionMode;\n\n\tconstructor(options: AgentOptions = {}) {\n\t\tthis._state = createMutableAgentState(options.initialState);\n\t\tthis.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = options.transformContext;\n\t\tthis.streamFn = options.streamFn ?? streamSimple;\n\t\tthis.getApiKey = options.getApiKey;\n\t\tthis.onPayload = options.onPayload;\n\t\tthis.onResponse = options.onResponse;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.onToolInvocationStarting = options.onToolInvocationStarting;\n\t\tthis.onToolExchangeFinalized = options.onToolExchangeFinalized;\n\t\tthis.shouldStopAfterTurn = options.shouldStopAfterTurn;\n\t\tthis.getTurnOutcome = options.getTurnOutcome;\n\t\tthis.shouldStopBeforeTurn = options.shouldStopBeforeTurn;\n\t\tthis.getContinuationMessages = options.getContinuationMessages;\n\t\tthis.getContinuationOutcome = options.getContinuationOutcome;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.toolExecution = options.toolExecution ?? \"parallel\";\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order and are included in\n\t * the current run's settlement. Listeners also receive the active abort\n\t * signal for the current run.\n\t *\n\t * `agent_end` is the final emitted event for a run, but the agent does not\n\t * become idle until all awaited listeners for that event have settled.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message batch to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage | AgentMessage[]): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message batch to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage | AgentMessage[]): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\tremoveQueuedMessages(predicate: (message: AgentMessage) => boolean): AgentMessage[] {\n\t\treturn [...this.steeringQueue.removeWhere(predicate), ...this.followUpQueue.removeWhere(predicate)];\n\t}\n\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** The last message must convert to a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new AgentContinueError(\"busy\", \"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst runQueuedMessages = (): Promise<void> | undefined => {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\treturn this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\treturn this.runPromptMessages(queuedFollowUps);\n\t\t\t}\n\n\t\t\treturn undefined;\n\t\t};\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tconst queuedRun = runQueuedMessages();\n\t\t\tif (queuedRun) {\n\t\t\t\tawait queuedRun;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new AgentContinueError(\"nothing-to-continue\", \"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedRun = runQueuedMessages();\n\t\t\tif (queuedRun) {\n\t\t\t\tawait queuedRun;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new AgentContinueError(\"nothing-to-continue\", \"Cannot continue from message role: assistant\");\n\t\t}\n\n\t\tconst lastMessageRole: string = lastMessage.role;\n\t\tif (lastMessageRole === \"custom\") {\n\t\t\tconst queuedRun = runQueuedMessages();\n\t\t\tif (queuedRun) {\n\t\t\t\tawait queuedRun;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tif (!this._state.model)\n\t\t\tthrow new Error(\"No model selected. Select a provider and model before starting the agent.\");\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\tconst onToolInvocationStarting = this.onToolInvocationStarting;\n\t\tconst onToolExchangeFinalized = this.onToolExchangeFinalized;\n\t\treturn {\n\t\t\toutputPolicy: this.activeOutputPolicy,\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel,\n\t\t\tserviceTier: this._state.serviceTier,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tonToolInvocationStarting: async (invocation, signal, tool, execute, assistantMessage) => {\n\t\t\t\tconst owner = await this.toolExecutionOwner?.onToolInvocationStarting(\n\t\t\t\t\tinvocation,\n\t\t\t\t\tsignal,\n\t\t\t\t\ttool,\n\t\t\t\t\texecute,\n\t\t\t\t\tassistantMessage,\n\t\t\t\t);\n\t\t\t\tawait onToolInvocationStarting?.(invocation, signal);\n\t\t\t\treturn owner || undefined;\n\t\t\t},\n\t\t\tonToolExchangeFinalized: async (exchange, signal, owner) => {\n\t\t\t\tif (owner) await owner.finalize(exchange, signal);\n\t\t\t\telse await this.toolExecutionOwner?.onToolExchangeFinalized(exchange, signal);\n\t\t\t\tawait onToolExchangeFinalized?.(exchange, signal);\n\t\t\t},\n\t\t\tshouldStopAfterTurn: async (context) => this.shouldStopAfterTurn?.(context) ?? false,\n\t\t\tgetTurnOutcome: this.getTurnOutcome?.bind(this),\n\t\t\tshouldStopBeforeTurn: () => this.shouldStopBeforeTurn?.() ?? false,\n\t\t\tbeforeContextBuild: async () => this.contextOwner?.(),\n\t\t\trecoverRequestPreparation: this.requestPreparationRecoveryOwner,\n\t\t\trecoverProviderFailure: this.providerFailureRecoveryOwner?.recover,\n\t\t\tonContextAdopted: (messages) => {\n\t\t\t\tthis._state.messages = messages;\n\t\t\t},\n\t\t\townedStreamFn: this.ownedStreamFn,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetSystemPrompt: () => this._state.systemPrompt,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t\tgetContinuationMessages: async (context, signal) => this.getContinuationMessages?.(context, signal) ?? [],\n\t\t\tgetContinuationOutcome: this.getContinuationOutcome?.bind(this),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\t\tif (!this._state.model)\n\t\t\tthrow new Error(\"No model selected. Select a provider and model before starting the agent.\");\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tconst outputPolicy = this.outputOwner?.();\n\t\t\tthis.activeOutputPolicy = outputPolicy\n\t\t\t\t? {\n\t\t\t\t\t\tlimits: { ...outputPolicy.limits },\n\t\t\t\t\t\tsnapshot: outputPolicy.snapshot.bind(outputPolicy),\n\t\t\t\t\t\tbindUpdates: outputPolicy.bindUpdates?.bind(outputPolicy),\n\t\t\t\t\t\tsettleUpdates: outputPolicy.settleUpdates?.bind(outputPolicy),\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\t\t\tif (this.initializationOwner) {\n\t\t\t\tawait this.initializationOwner();\n\t\t\t\tabortController.signal.throwIfAborted();\n\t\t\t}\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tif (error instanceof AgentOutputLimitError || isRequestTokenBudgetFailure(error)) {\n\t\t\t\tthis._state.errorMessage = error.message;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tawait this.handleRunFailure(error, abortController.signal.aborted);\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tthis.providerFailureRecoveryOwner?.settle?.();\n\t\t\t} finally {\n\t\t\t\tthis.finishRun();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\tif (!this._state.model) throw error;\n\t\tconst failureMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\t\tapi: this._state.model.api,\n\t\t\tprovider: this._state.model.provider,\n\t\t\tmodel: this._state.model.id,\n\t\t\tusage: EMPTY_USAGE,\n\t\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\tdiagnostics: aborted\n\t\t\t\t? undefined\n\t\t\t\t: [createAssistantMessageDiagnostic(\"agent_lifecycle_failure\", error, { source: \"run_with_lifecycle\" })],\n\t\t\ttimestamp: Date.now(),\n\t\t} satisfies AgentMessage;\n\t\tthis._state.errorMessage = failureMessage.errorMessage;\n\t\tawait this.processEvents({ type: \"message_start\", message: failureMessage }).catch(() => undefined);\n\t\tawait this.processEvents({ type: \"message_end\", message: failureMessage }).catch(() => undefined);\n\t\tawait this.processEvents({ type: \"agent_end\", messages: [failureMessage] }).catch(() => undefined);\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis.activeOutputPolicy = undefined;\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/**\n\t * Reduce internal state for a loop event, then await listeners.\n\t *\n\t * `agent_end` only means no further loop events will be emitted. The run is\n\t * considered idle later, after all awaited listeners for `agent_end` finish\n\t * and `finishRun()` clears runtime-owned state.\n\t */\n\tprivate async processEvents(event: AgentEvent): Promise<void> {\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.add(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tif (event.refusal) this._state.errorMessage = new AgentOutputLimitError(event.refusal).message;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tfor (const listener of this.listeners) {\n\t\t\tawait listener(event, signal);\n\t\t}\n\t}\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  {
2
- "sourceCommit": "3b6e414e5d955f03bdebf866f39b85853a896d13",
2
+ "sourceCommit": "4192025d919683d61a402b666b4790e26118df53",
3
3
  "sourceDirty": false,
4
4
  "buildHost": {
5
5
  "platform": "linux",
package/dist/types.d.ts CHANGED
@@ -379,7 +379,7 @@ export interface AgentState {
379
379
  /** System prompt sent with each model request. */
380
380
  systemPrompt: string;
381
381
  /** Model used for future turns. */
382
- model: Model<any>;
382
+ model: Model<any> | undefined;
383
383
  /** Requested reasoning level for future turns. */
384
384
  thinkingLevel: ThinkingLevel;
385
385
  /** Requested provider service tier for future turns. */
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/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ageEvent,\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 an unsent request's projection has been released. */\n\trecoverRequestPreparation?: (error: unknown, signal?: AbortSignal) => Promise<boolean>;\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>;\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,OAA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C;IACtB,WAAW,EAAE,iBAAiB,EAAE,CAAC;IACjC,oFAAoF;IACpF,aAAa,CAAC,EAAE,iBAAiB,CAAC;IAClC,sFAAsF;IACtF,SAAS,CAAC,EAAE,SAAS,qBAAqB,EAAE,CAAC;CAC5C;AACH,sEAAsE;GACpE;IAAE,IAAI,EAAE,eAAe,CAAC;IAAC,OAAO,EAAE,YAAY,CAAA;CAAE;AAClD,4DAA4D;GAC1D;IAAE,IAAI,EAAE,gBAAgB,CAAC;IAAC,OAAO,EAAE,YAAY,CAAC;IAAC,qBAAqB,EAAE,qBAAqB,CAAA;CAAE,GAC/F;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC,OAAO,EAAE,YAAY,CAAA;CAAE;AAChD,4FAA4F;GAC1F;IAAE,IAAI,EAAE,sBAAsB,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,GAAG,CAAA;CAAE,GACjF;IAAE,IAAI,EAAE,uBAAuB,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,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 an unsent request's projection has been released. */\n\trecoverRequestPreparation?: (error: unknown, signal?: AbortSignal) => Promise<boolean>;\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"]}
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 an unsent request's projection has been released. */\n\trecoverRequestPreparation?: (error: unknown, signal?: AbortSignal) => Promise<boolean>;\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>;\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 an unsent request's projection has been released. */\n\trecoverRequestPreparation?: (error: unknown, signal?: AbortSignal) => Promise<boolean>;\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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ponythewhite/base-context-agent",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
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.0",
22
+ "@ponythewhite/base-context-ai": "1.0.2",
23
23
  "typebox": "^1.3.9"
24
24
  },
25
25
  "keywords": [