@leanandmean/agent 0.74.1-scramjet.10 → 0.74.1-scramjet.12

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/dist/agent.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { type ImageContent, type Message, type SimpleStreamOptions, type ThinkingBudgets, type Transport } from "@leanandmean/ai";
2
2
  import type { AfterToolCallContext, AfterToolCallResult, AgentEvent, AgentLoopTurnUpdate, AgentMessage, AgentState, AgentTool, BeforeToolBatchContext, BeforeToolCallContext, BeforeToolCallResult, PrepareNextTurnContext, QueueMode, StreamFn, ToolExecutionMode } from "./types.js";
3
3
  export type { QueueMode } from "./types.js";
4
+ export declare function generateHarnessToolCallId(): string;
4
5
  /** Options for constructing an {@link Agent}. */
5
6
  export interface AgentOptions {
6
7
  initialState?: Partial<Omit<AgentState, "pendingToolCalls" | "isStreaming" | "streamingMessage" | "errorMessage">>;
@@ -44,8 +45,15 @@ export declare class Agent {
44
45
  afterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;
45
46
  prepareNextTurn?: (ctx: PrepareNextTurnContext, signal?: AbortSignal) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;
46
47
  private activeRun?;
47
- /** Harness tool calls queued while a run is active, drained at the next turn boundary. */
48
+ /** Harness tool invocations queued while a run is active, drained at the next turn boundary. */
48
49
  private readonly harnessToolQueue;
50
+ /**
51
+ * Every harness-tool invocation whose public promise has not yet settled — queued, shifted and
52
+ * draining, or transient. Reset/teardown rejects this set; each invocation is removed as it
53
+ * settles. Queue length is not a proxy for this: a draining call has left the queue but is still
54
+ * unsettled (#341).
55
+ */
56
+ private readonly unsettledHarnessTools;
49
57
  /**
50
58
  * Markers for in-flight transient (idle) harness-tool runs; each resolves when its run settles.
51
59
  * A set (not a single field) keeps nested and overlapping transient runs valid, and lets a new
@@ -139,10 +147,35 @@ export declare class Agent {
139
147
  * When idle, the call executes immediately in a transient run scope. When a run is active, it is
140
148
  * queued and drained at the next turn boundary — before the next intra-run LLM call — with an
141
149
  * end-of-run flush for calls queued during the run's final turn, so a queued call is never stranded.
150
+ *
151
+ * **Settlement (#341).** The returned promise resolves only after the call's full Agent-core
152
+ * pipeline finishes: the synthetic assistant tool-call message, tool prepare/execute/finalize, the
153
+ * tool-result message, Agent state reduction, and every awaited listener for those events. A queued
154
+ * call therefore does not resolve at enqueue time — it resolves when the drain executes it. The
155
+ * promise rejects when reset or session teardown revokes an unsettled invocation, when an
156
+ * infrastructure/listener/hook failure escapes the pipeline, or when a failed final drain leaves a
157
+ * later queued call unable to execute. A tool's own `execute()` throwing is **not** a rejection: it
158
+ * becomes a normal `isError: true` tool result, so the promise resolves after that error-result
159
+ * pipeline completes. Rejection means the promised pipeline did not complete — it does not prove
160
+ * artifact absence (state and persistence may have partially completed), so callers must not blindly
161
+ * retry.
162
+ *
163
+ * This settles Agent-core execution only. It does **not** prove AgentSession persistence;
164
+ * `AgentSession.invokeHarnessTool` layers the persisted-settlement boundary on top of it.
165
+ *
166
+ * **Reentrancy.** Do not `await` this from work whose return is required for the Agent to reach the
167
+ * drain point (a model-callable `execute`, `beforeToolBatch`/`beforeToolCall`/`afterToolCall`/
168
+ * `prepareNextTurn`, or an awaited listener), or the queued call can never execute and the await
169
+ * deadlocks. Start/capture the promise, return from the gating callback, and await it from an
170
+ * independent continuation.
142
171
  */
143
172
  runHarnessTool(tool: AgentTool<any>, args: unknown, options?: {
144
173
  toolCallId?: string;
145
174
  }): Promise<void>;
175
+ private createHarnessInvocation;
176
+ private settleHarnessInvocation;
177
+ private executeHarnessInvocation;
178
+ rejectUnsettledHarnessTools(reason: Error): void;
146
179
  private drainHarnessToolQueue;
147
180
  private emitHarnessToolCall;
148
181
  private createHarnessAssistantMessage;
@@ -1 +1 @@
1
- {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,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AgBjB,eAAe;IAY7B,OAAO,CAAC,qBAAqB;IAQ7B,OAAO,CAAC,gBAAgB;YAqCV,gBAAgB;YAqChB,gBAAgB;IAkB9B,OAAO,CAAC,SAAS;YAeH,aAAa;IAsD3B;;;;;;;;;;;;;OAaG;IACG,cAAc,CAAC,IAAI,EAAE,SAAS,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,GAAE;QAAE,UAAU,CAAC,EAAE,MAAM,CAAA;KAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAmB9G;YAGa,qBAAqB;YAgBrB,mBAAmB;IAqCjC,OAAO,CAAC,6BAA6B;CAYrC","sourcesContent":["import {\n\ttype AssistantMessage,\n\ttype ImageContent,\n\ttype Message,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"@leanandmean/ai\";\nimport { executeHarnessToolCall, runAgentLoop, runAgentLoopContinue } from \"./agent-loop.js\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tAgentToolCall,\n\tBeforeToolBatchContext,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tPrepareNextTurnContext,\n\tQueueMode,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.js\";\n\nexport type { QueueMode } from \"./types.js\";\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\n// SCRAMJET-DIVERGENCE: provider-safe tool-call id generation for harness-originated calls (#244).\n// The id must satisfy every provider's constraint (Anthropic's `^[a-zA-Z0-9_-]+$`, bounded length)\n// and must never embed raw model ids. A random suffix (not a bare counter) avoids collisions with\n// ids already present in a resumed transcript.\nfunction generateHarnessToolCallId(): string {\n\tconst uuid = globalThis.crypto?.randomUUID?.();\n\tconst suffix = uuid\n\t\t? uuid.replace(/-/g, \"\")\n\t\t: `${Date.now().toString(36)}${Math.floor(Math.random() * 1e9).toString(36)}`;\n\treturn `harness-tool-${suffix}`.slice(0, 64);\n}\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\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolBatch?: (context: BeforeToolBatchContext, signal?: AbortSignal) => Promise<void>;\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\t// SCRAMJET-DIVERGENCE: prepareNextTurn receives the live turn context (previously the loop\n\t// context it passes was discarded by the Agent adapter) (#244).\n\tprepareNextTurn?: (\n\t\tctx: PrepareNextTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\ttoolExecution?: ToolExecutionMode;\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\n\tconstructor(public mode: QueueMode) {}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.messages.slice();\n\t\t\tthis.messages = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.messages[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.messages = this.messages.slice(1);\n\t\treturn [first];\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFn: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\t// SCRAMJET-DIVERGENCE: beforeToolBatch hook — async message_end mutations must settle before tool-call extraction\n\tpublic beforeToolBatch?: (context: BeforeToolBatchContext, signal?: AbortSignal) => Promise<void>;\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic prepareNextTurn?: (\n\t\tctx: PrepareNextTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t// SCRAMJET-DIVERGENCE: harness-tool-invocation primitive state (#244).\n\t/** Harness tool calls queued while a run is active, drained at the next turn boundary. */\n\tprivate readonly harnessToolQueue: Array<{ tool: AgentTool<any>; args: unknown; toolCallId: string }> = [];\n\t/**\n\t * Markers for in-flight transient (idle) harness-tool runs; each resolves when its run settles.\n\t * A set (not a single field) keeps nested and overlapping transient runs valid, and lets a new\n\t * real run wait for transient work to finish before emitting its own events.\n\t */\n\tprivate readonly transientRuns = new Set<Promise<void>>();\n\t/** Shared, never-aborted signal delivered to listeners during transient harness-tool runs. */\n\tprivate readonly transientRunAbort = new AbortController();\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\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.beforeToolBatch = options.beforeToolBatch;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.prepareNextTurn = options.prepareNextTurn;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.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\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear transcript state, runtime state, and queued messages. */\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t\t// SCRAMJET-DIVERGENCE: harness-tool-invocation primitive (#244). Queued harness\n\t\t// tool calls are dropped on reset; surface it so a lost record row is diagnosable.\n\t\tif (this.harnessToolQueue.length > 0) {\n\t\t\tconst names = this.harnessToolQueue.map((item) => item.tool.name).join(\", \");\n\t\t\tconsole.warn(`Agent.reset() discarded ${this.harnessToolQueue.length} queued harness tool call(s): ${names}`);\n\t\t}\n\t\tthis.harnessToolQueue.length = 0;\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new Error(\"Cannot continue from message role: assistant\");\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\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\tbeforeToolBatch: this.beforeToolBatch,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\t// SCRAMJET-DIVERGENCE: always run prepareNextTurn so mid-run harness tool calls drain\n\t\t\t// into the live turn context before the next intra-run LLM call, and so the next call\n\t\t\t// self-heals onto the current model (routing after a mid-run switch) (#244).\n\t\t\tprepareNextTurn: async (ctx) => {\n\t\t\t\tawait this.drainHarnessToolQueue(ctx, this.signal);\n\t\t\t\tconst update = await this.prepareNextTurn?.(ctx, this.signal);\n\t\t\t\treturn { ...update, model: update?.model ?? this._state.model };\n\t\t\t},\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\t// Wait for in-flight transient harness-tool runs so their events do not interleave\n\t\t\t// with this run's transcript.\n\t\t\twhile (this.transientRuns.size > 0) {\n\t\t\t\tawait Promise.all(this.transientRuns);\n\t\t\t}\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tawait this.handleRunFailure(error, abortController.signal.aborted);\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\t// Flush harness tool calls queued during the run's final turn — including failed or\n\t\t\t\t// aborted runs — after the last prepareNextTurn drain point, so a queued call is\n\t\t\t\t// never stranded. Emits messages/tool events but no run framing.\n\t\t\t\tawait this.drainHarnessToolQueue(undefined, abortController.signal);\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\ttimestamp: Date.now(),\n\t\t} satisfies AgentMessage;\n\t\tawait this.processEvents({ type: \"message_start\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"message_end\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"turn_end\", message: failureMessage, toolResults: [] });\n\t\tawait this.processEvents({ type: \"agent_end\", messages: [failureMessage] });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/**\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\tbreak;\n\t\t}\n\n\t\t// SCRAMJET-DIVERGENCE: fall back to the shared transient-run signal while transient\n\t\t// harness-tool work (which intentionally has no `activeRun`) is in flight (#244).\n\t\tconst signal =\n\t\t\tthis.activeRun?.abortController.signal ??\n\t\t\t(this.transientRuns.size > 0 ? this.transientRunAbort.signal : undefined);\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\t// SCRAMJET-DIVERGENCE: harness-tool-invocation primitive (#244).\n\t/**\n\t * Execute a harness-originated tool call through the real execution pipeline.\n\t *\n\t * The tool object is supplied directly, so it need not appear in `state.tools` — this is what\n\t * lets LLM-invisible harness tools execute. The call produces the same `tool_execution_*` and\n\t * message events, persisted messages, and `beforeToolCall`/`afterToolCall` invocations as a\n\t * normal tool execution, but emits **no** run/turn framing events (`agent_start`, `turn_start`,\n\t * `turn_end`, `agent_end`). It is therefore intentionally invisible to every `agent_end`-keyed\n\t * consumer (probe scheduling, compaction bookkeeping).\n\t *\n\t * When idle, the call executes immediately in a transient run scope. When a run is active, it is\n\t * queued and drained at the next turn boundary — before the next intra-run LLM call — with an\n\t * end-of-run flush for calls queued during the run's final turn, so a queued call is never stranded.\n\t */\n\tasync runHarnessTool(tool: AgentTool<any>, args: unknown, options: { toolCallId?: string } = {}): Promise<void> {\n\t\tconst toolCallId = options.toolCallId ?? generateHarnessToolCallId();\n\t\tif (this.activeRun) {\n\t\t\tthis.harnessToolQueue.push({ tool, args, toolCallId });\n\t\t\treturn;\n\t\t}\n\t\t// Register the marker before the first event so processEvents sees transient work in\n\t\t// flight from the start, including for nested calls (a harness tool invoking another).\n\t\tlet settle!: () => void;\n\t\tconst marker = new Promise<void>((resolve) => {\n\t\t\tsettle = resolve;\n\t\t});\n\t\tthis.transientRuns.add(marker);\n\t\ttry {\n\t\t\tawait this.emitHarnessToolCall(tool, args, toolCallId, this.transientRunAbort.signal, undefined);\n\t\t} finally {\n\t\t\tthis.transientRuns.delete(marker);\n\t\t\tsettle();\n\t\t}\n\t}\n\n\t/** Drain all queued harness tool calls, splicing them into `ctx` when draining mid-run. */\n\tprivate async drainHarnessToolQueue(\n\t\tctx: PrepareNextTurnContext | undefined,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<void> {\n\t\twhile (this.harnessToolQueue.length > 0) {\n\t\t\tconst item = this.harnessToolQueue.shift()!;\n\t\t\tawait this.emitHarnessToolCall(item.tool, item.args, item.toolCallId, signal, ctx);\n\t\t}\n\t}\n\n\t/**\n\t * Emit the full event sequence for one harness tool call: a synthetic single-toolCall assistant\n\t * message, then the tool execution and its result message. When `ctx` is provided (mid-run drain),\n\t * the synthetic messages are also spliced into the live turn context and returned-message set so\n\t * the next intra-run LLM call includes them.\n\t */\n\tprivate async emitHarnessToolCall(\n\t\ttool: AgentTool<any>,\n\t\targs: unknown,\n\t\ttoolCallId: string,\n\t\tsignal: AbortSignal | undefined,\n\t\tctx: PrepareNextTurnContext | undefined,\n\t): Promise<void> {\n\t\tconst toolCall: AgentToolCall = {\n\t\t\ttype: \"toolCall\",\n\t\t\tid: toolCallId,\n\t\t\tname: tool.name,\n\t\t\targuments: (args ?? {}) as Record<string, any>,\n\t\t};\n\t\tconst assistantMessage = this.createHarnessAssistantMessage(toolCall);\n\t\tawait this.processEvents({ type: \"message_start\", message: assistantMessage });\n\t\tawait this.processEvents({ type: \"message_end\", message: assistantMessage });\n\t\tif (ctx) {\n\t\t\tctx.context.messages.push(assistantMessage);\n\t\t\tctx.newMessages.push(assistantMessage);\n\t\t}\n\n\t\tconst hookContext = ctx?.context ?? this.createContextSnapshot();\n\t\tconst toolResultMessage = await executeHarnessToolCall(\n\t\t\ttool,\n\t\t\ttoolCall,\n\t\t\thookContext,\n\t\t\tassistantMessage,\n\t\t\t{ beforeToolCall: this.beforeToolCall, afterToolCall: this.afterToolCall },\n\t\t\tsignal,\n\t\t\t(event) => this.processEvents(event),\n\t\t);\n\t\tif (ctx) {\n\t\t\tctx.context.messages.push(toolResultMessage);\n\t\t\tctx.newMessages.push(toolResultMessage);\n\t\t}\n\t}\n\n\tprivate createHarnessAssistantMessage(toolCall: AgentToolCall): AssistantMessage {\n\t\treturn {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [toolCall],\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: \"toolUse\",\n\t\t\ttimestamp: Date.now(),\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,EACjB,KAAK,OAAO,EAEZ,KAAK,mBAAmB,EAGxB,KAAK,eAAe,EACpB,KAAK,SAAS,EACd,MAAM,iBAAiB,CAAC;AAEzB,OAAO,KAAK,EACX,oBAAoB,EACpB,mBAAmB,EAEnB,UAAU,EAEV,mBAAmB,EACnB,YAAY,EACZ,UAAU,EACV,SAAS,EAET,sBAAsB,EACtB,qBAAqB,EACrB,oBAAoB,EACpB,sBAAsB,EACtB,SAAS,EACT,QAAQ,EACR,iBAAiB,EACjB,MAAM,YAAY,CAAC;AAEpB,YAAY,EAAE,SAAS,EAAE,MAAM,YAAY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,OAAO,GAAE;QAAE,UAAU,CAAC,EAAE,MAAM,CAAA;KAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CA4B9G;IAID,OAAO,CAAC,uBAAuB;IAgB/B,OAAO,CAAC,uBAAuB;YASjB,wBAAwB;IAgBtC,2BAA2B,CAAC,MAAM,EAAE,KAAK,GAAG,IAAI,CAK/C;YAGa,qBAAqB;YAgBrB,mBAAmB;IAqCjC,OAAO,CAAC,6BAA6B;CAYrC","sourcesContent":["import {\n\ttype AssistantMessage,\n\ttype ImageContent,\n\ttype Message,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"@leanandmean/ai\";\nimport { executeHarnessToolCall, runAgentLoop, runAgentLoopContinue } from \"./agent-loop.js\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tAgentToolCall,\n\tBeforeToolBatchContext,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tPrepareNextTurnContext,\n\tQueueMode,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.js\";\n\nexport type { QueueMode } from \"./types.js\";\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\n// SCRAMJET-DIVERGENCE: provider-safe tool-call id generation for harness-originated calls (#244).\n// The id must satisfy every provider's constraint (Anthropic's `^[a-zA-Z0-9_-]+$`, bounded length)\n// and must never embed raw model ids. A random suffix (not a bare counter) avoids collisions with\n// ids already present in a resumed transcript.\nexport function generateHarnessToolCallId(): string {\n\tconst uuid = globalThis.crypto?.randomUUID?.();\n\tconst suffix = uuid\n\t\t? uuid.replace(/-/g, \"\")\n\t\t: `${Date.now().toString(36)}${Math.floor(Math.random() * 1e9).toString(36)}`;\n\treturn `harness-tool-${suffix}`.slice(0, 64);\n}\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\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolBatch?: (context: BeforeToolBatchContext, signal?: AbortSignal) => Promise<void>;\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\t// SCRAMJET-DIVERGENCE: prepareNextTurn receives the live turn context (previously the loop\n\t// context it passes was discarded by the Agent adapter) (#244).\n\tprepareNextTurn?: (\n\t\tctx: PrepareNextTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\ttoolExecution?: ToolExecutionMode;\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\n\tconstructor(public mode: QueueMode) {}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.messages.slice();\n\t\t\tthis.messages = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.messages[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.messages = this.messages.slice(1);\n\t\treturn [first];\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n// SCRAMJET-DIVERGENCE: harness-tool-invocation settlement records (#341).\n/**\n * One harness-tool invocation and the deferred promise that `runHarnessTool` returns for it. The\n * promise settles only when the invocation's Agent-core pipeline completes (resolve) or when\n * reset/teardown revokes the invocation or an infrastructure failure escapes the pipeline (reject).\n */\ntype HarnessToolInvocation = {\n\ttool: AgentTool<any>;\n\targs: unknown;\n\ttoolCallId: string;\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\treject: (reason: Error) => void;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFn: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\t// SCRAMJET-DIVERGENCE: beforeToolBatch hook — async message_end mutations must settle before tool-call extraction\n\tpublic beforeToolBatch?: (context: BeforeToolBatchContext, signal?: AbortSignal) => Promise<void>;\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic prepareNextTurn?: (\n\t\tctx: PrepareNextTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t// SCRAMJET-DIVERGENCE: harness-tool-invocation primitive state (#244, settlement #341).\n\t/** Harness tool invocations queued while a run is active, drained at the next turn boundary. */\n\tprivate readonly harnessToolQueue: HarnessToolInvocation[] = [];\n\t/**\n\t * Every harness-tool invocation whose public promise has not yet settled — queued, shifted and\n\t * draining, or transient. Reset/teardown rejects this set; each invocation is removed as it\n\t * settles. Queue length is not a proxy for this: a draining call has left the queue but is still\n\t * unsettled (#341).\n\t */\n\tprivate readonly unsettledHarnessTools = new Set<HarnessToolInvocation>();\n\t/**\n\t * Markers for in-flight transient (idle) harness-tool runs; each resolves when its run settles.\n\t * A set (not a single field) keeps nested and overlapping transient runs valid, and lets a new\n\t * real run wait for transient work to finish before emitting its own events.\n\t */\n\tprivate readonly transientRuns = new Set<Promise<void>>();\n\t/** Shared, never-aborted signal delivered to listeners during transient harness-tool runs. */\n\tprivate readonly transientRunAbort = new AbortController();\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\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.beforeToolBatch = options.beforeToolBatch;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.prepareNextTurn = options.prepareNextTurn;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.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\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear transcript state, runtime state, and queued messages. */\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t\t// SCRAMJET-DIVERGENCE: harness-tool-invocation primitive (#244, settlement #341). reset()\n\t\t// rejects the public promise of every unsettled harness invocation so awaiting callers stop\n\t\t// waiting. The effect on the record row differs by kind: a queued (not-yet-draining) call loses\n\t\t// its row entirely, while a transient in-flight call keeps running — reset() does not abort\n\t\t// transientRunAbort — so its row is still emitted and persisted; only its promise is rejected.\n\t\t// The warning surfaces the rejection so a lost queued row is diagnosable.\n\t\tif (this.unsettledHarnessTools.size > 0) {\n\t\t\tconst names = [...this.unsettledHarnessTools].map((record) => record.tool.name).join(\", \");\n\t\t\tconsole.warn(\n\t\t\t\t`Agent.reset() rejected ${this.unsettledHarnessTools.size} unsettled harness tool call(s): ${names}`,\n\t\t\t);\n\t\t}\n\t\tthis.rejectUnsettledHarnessTools(new Error(\"Agent.reset() discarded unsettled harness tool call\"));\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new Error(\"Cannot continue from message role: assistant\");\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\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\tbeforeToolBatch: this.beforeToolBatch,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\t// SCRAMJET-DIVERGENCE: always run prepareNextTurn so mid-run harness tool calls drain\n\t\t\t// into the live turn context before the next intra-run LLM call, and so the next call\n\t\t\t// self-heals onto the current model (routing after a mid-run switch) (#244).\n\t\t\tprepareNextTurn: async (ctx) => {\n\t\t\t\tawait this.drainHarnessToolQueue(ctx, this.signal);\n\t\t\t\tconst update = await this.prepareNextTurn?.(ctx, this.signal);\n\t\t\t\treturn { ...update, model: update?.model ?? this._state.model };\n\t\t\t},\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\t// SCRAMJET-DIVERGENCE (#341): a failed final flush leaves later queued calls unable to execute.\n\t\t// Capture it (rejecting remnants below) and re-throw after finishRun so the error propagates out\n\t\t// of prompt()/continue() — not activeRun.promise, which finishRun always resolves — without a\n\t\t// lint-flagged throw inside a finally block. The { error } wrapper (not a bare `unknown` field)\n\t\t// is deliberate: it distinguishes \"no drain error\" from a falsy throw (e.g. `throw undefined`),\n\t\t// which a `!== undefined` check on a bare field would silently swallow.\n\t\tlet finalDrainError: { error: unknown } | undefined;\n\t\ttry {\n\t\t\t// Wait for in-flight transient harness-tool runs so their events do not interleave\n\t\t\t// with this run's transcript.\n\t\t\twhile (this.transientRuns.size > 0) {\n\t\t\t\tawait Promise.all(this.transientRuns);\n\t\t\t}\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tawait this.handleRunFailure(error, abortController.signal.aborted);\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\t// Flush harness tool calls queued during the run's final turn — including failed or\n\t\t\t\t// aborted runs — after the last prepareNextTurn drain point, so a queued call is\n\t\t\t\t// never stranded. Emits messages/tool events but no run framing.\n\t\t\t\tawait this.drainHarnessToolQueue(undefined, abortController.signal);\n\t\t\t} catch (drainError) {\n\t\t\t\t// The failing call was already rejected by executeHarnessInvocation; reject the\n\t\t\t\t// remnants too so their promises settle.\n\t\t\t\tthis.rejectUnsettledHarnessTools(drainError instanceof Error ? drainError : new Error(String(drainError)));\n\t\t\t\tfinalDrainError = { error: drainError };\n\t\t\t} finally {\n\t\t\t\tthis.finishRun();\n\t\t\t}\n\t\t}\n\t\tif (finalDrainError) {\n\t\t\tthrow finalDrainError.error;\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\ttimestamp: Date.now(),\n\t\t} satisfies AgentMessage;\n\t\tawait this.processEvents({ type: \"message_start\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"message_end\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"turn_end\", message: failureMessage, toolResults: [] });\n\t\tawait this.processEvents({ type: \"agent_end\", messages: [failureMessage] });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/**\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\tbreak;\n\t\t}\n\n\t\t// SCRAMJET-DIVERGENCE: fall back to the shared transient-run signal while transient\n\t\t// harness-tool work (which intentionally has no `activeRun`) is in flight (#244).\n\t\tconst signal =\n\t\t\tthis.activeRun?.abortController.signal ??\n\t\t\t(this.transientRuns.size > 0 ? this.transientRunAbort.signal : undefined);\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\t// SCRAMJET-DIVERGENCE: harness-tool-invocation primitive (#244, execution settlement #341).\n\t/**\n\t * Execute a harness-originated tool call through the real execution pipeline.\n\t *\n\t * The tool object is supplied directly, so it need not appear in `state.tools` — this is what\n\t * lets LLM-invisible harness tools execute. The call produces the same `tool_execution_*` and\n\t * message events, persisted messages, and `beforeToolCall`/`afterToolCall` invocations as a\n\t * normal tool execution, but emits **no** run/turn framing events (`agent_start`, `turn_start`,\n\t * `turn_end`, `agent_end`). It is therefore intentionally invisible to every `agent_end`-keyed\n\t * consumer (probe scheduling, compaction bookkeeping).\n\t *\n\t * When idle, the call executes immediately in a transient run scope. When a run is active, it is\n\t * queued and drained at the next turn boundary — before the next intra-run LLM call — with an\n\t * end-of-run flush for calls queued during the run's final turn, so a queued call is never stranded.\n\t *\n\t * **Settlement (#341).** The returned promise resolves only after the call's full Agent-core\n\t * pipeline finishes: the synthetic assistant tool-call message, tool prepare/execute/finalize, the\n\t * tool-result message, Agent state reduction, and every awaited listener for those events. A queued\n\t * call therefore does not resolve at enqueue time — it resolves when the drain executes it. The\n\t * promise rejects when reset or session teardown revokes an unsettled invocation, when an\n\t * infrastructure/listener/hook failure escapes the pipeline, or when a failed final drain leaves a\n\t * later queued call unable to execute. A tool's own `execute()` throwing is **not** a rejection: it\n\t * becomes a normal `isError: true` tool result, so the promise resolves after that error-result\n\t * pipeline completes. Rejection means the promised pipeline did not complete — it does not prove\n\t * artifact absence (state and persistence may have partially completed), so callers must not blindly\n\t * retry.\n\t *\n\t * This settles Agent-core execution only. It does **not** prove AgentSession persistence;\n\t * `AgentSession.invokeHarnessTool` layers the persisted-settlement boundary on top of it.\n\t *\n\t * **Reentrancy.** Do not `await` this from work whose return is required for the Agent to reach the\n\t * drain point (a model-callable `execute`, `beforeToolBatch`/`beforeToolCall`/`afterToolCall`/\n\t * `prepareNextTurn`, or an awaited listener), or the queued call can never execute and the await\n\t * deadlocks. Start/capture the promise, return from the gating callback, and await it from an\n\t * independent continuation.\n\t */\n\tasync runHarnessTool(tool: AgentTool<any>, args: unknown, options: { toolCallId?: string } = {}): Promise<void> {\n\t\tconst toolCallId = options.toolCallId ?? generateHarnessToolCallId();\n\t\tconst record = this.createHarnessInvocation(tool, args, toolCallId);\n\t\tif (this.activeRun) {\n\t\t\tthis.harnessToolQueue.push(record);\n\t\t\treturn record.promise;\n\t\t}\n\t\t// Register the marker before the first event so processEvents sees transient work in\n\t\t// flight from the start, including for nested calls (a harness tool invoking another). The\n\t\t// marker tracks the underlying work even if reset/teardown rejects the public promise first,\n\t\t// so a later prompt still waits for the transient events to finish before emitting its own.\n\t\tlet settleMarker!: () => void;\n\t\tconst marker = new Promise<void>((resolve) => {\n\t\t\tsettleMarker = resolve;\n\t\t});\n\t\tthis.transientRuns.add(marker);\n\t\tvoid (async () => {\n\t\t\ttry {\n\t\t\t\tawait this.executeHarnessInvocation(record, this.transientRunAbort.signal, undefined);\n\t\t\t} catch {\n\t\t\t\t// The rejection is already recorded on record.promise; a transient run has no run-failure\n\t\t\t\t// path to propagate into, so nothing escapes here.\n\t\t\t} finally {\n\t\t\t\tthis.transientRuns.delete(marker);\n\t\t\t\tsettleMarker();\n\t\t\t}\n\t\t})();\n\t\treturn record.promise;\n\t}\n\n\t// SCRAMJET-DIVERGENCE (#341): back a harness-tool invocation with a deferred promise and track it\n\t// as unsettled until it resolves or is rejected.\n\tprivate createHarnessInvocation(tool: AgentTool<any>, args: unknown, toolCallId: string): HarnessToolInvocation {\n\t\tlet resolve!: () => void;\n\t\tlet reject!: (reason: Error) => void;\n\t\tconst promise = new Promise<void>((res, rej) => {\n\t\t\tresolve = res;\n\t\t\treject = rej;\n\t\t});\n\t\tconst record: HarnessToolInvocation = { tool, args, toolCallId, promise, resolve, reject };\n\t\tthis.unsettledHarnessTools.add(record);\n\t\treturn record;\n\t}\n\n\t// SCRAMJET-DIVERGENCE (#341): settle a harness invocation exactly once. Set membership is the\n\t// settled flag: unsettledHarnessTools.delete() returns false when the record was already removed\n\t// (e.g. underlying transient work finishing after reset already rejected it), so a later attempt\n\t// is a no-op.\n\tprivate settleHarnessInvocation(record: HarnessToolInvocation, error?: Error): void {\n\t\tif (!this.unsettledHarnessTools.delete(record)) return;\n\t\tif (error) record.reject(error);\n\t\telse record.resolve();\n\t}\n\n\t// SCRAMJET-DIVERGENCE (#341): run one invocation's pipeline and settle its record. Infrastructure\n\t// failures reject the record and rethrow so the drain path preserves current run-failure behavior;\n\t// a tool's own execute() error is not seen here (it resolves as an isError tool result).\n\tprivate async executeHarnessInvocation(\n\t\trecord: HarnessToolInvocation,\n\t\tsignal: AbortSignal | undefined,\n\t\tctx: PrepareNextTurnContext | undefined,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tawait this.emitHarnessToolCall(record.tool, record.args, record.toolCallId, signal, ctx);\n\t\t} catch (error) {\n\t\t\tthis.settleHarnessInvocation(record, error instanceof Error ? error : new Error(String(error)));\n\t\t\tthrow error;\n\t\t}\n\t\tthis.settleHarnessInvocation(record);\n\t}\n\n\t// SCRAMJET-DIVERGENCE (#341): idempotently clear the queue and reject every still-unsettled\n\t// invocation (queued, draining, or transient). Used by reset() and by the final-drain failure path.\n\trejectUnsettledHarnessTools(reason: Error): void {\n\t\tthis.harnessToolQueue.length = 0;\n\t\tfor (const record of [...this.unsettledHarnessTools]) {\n\t\t\tthis.settleHarnessInvocation(record, reason);\n\t\t}\n\t}\n\n\t/** Drain all queued harness tool calls, splicing them into `ctx` when draining mid-run. */\n\tprivate async drainHarnessToolQueue(\n\t\tctx: PrepareNextTurnContext | undefined,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<void> {\n\t\twhile (this.harnessToolQueue.length > 0) {\n\t\t\tconst record = this.harnessToolQueue.shift()!;\n\t\t\tawait this.executeHarnessInvocation(record, signal, ctx);\n\t\t}\n\t}\n\n\t/**\n\t * Emit the full event sequence for one harness tool call: a synthetic single-toolCall assistant\n\t * message, then the tool execution and its result message. When `ctx` is provided (mid-run drain),\n\t * the synthetic messages are also spliced into the live turn context and returned-message set so\n\t * the next intra-run LLM call includes them.\n\t */\n\tprivate async emitHarnessToolCall(\n\t\ttool: AgentTool<any>,\n\t\targs: unknown,\n\t\ttoolCallId: string,\n\t\tsignal: AbortSignal | undefined,\n\t\tctx: PrepareNextTurnContext | undefined,\n\t): Promise<void> {\n\t\tconst toolCall: AgentToolCall = {\n\t\t\ttype: \"toolCall\",\n\t\t\tid: toolCallId,\n\t\t\tname: tool.name,\n\t\t\targuments: (args ?? {}) as Record<string, any>,\n\t\t};\n\t\tconst assistantMessage = this.createHarnessAssistantMessage(toolCall);\n\t\tawait this.processEvents({ type: \"message_start\", message: assistantMessage });\n\t\tawait this.processEvents({ type: \"message_end\", message: assistantMessage });\n\t\tif (ctx) {\n\t\t\tctx.context.messages.push(assistantMessage);\n\t\t\tctx.newMessages.push(assistantMessage);\n\t\t}\n\n\t\tconst hookContext = ctx?.context ?? this.createContextSnapshot();\n\t\tconst toolResultMessage = await executeHarnessToolCall(\n\t\t\ttool,\n\t\t\ttoolCall,\n\t\t\thookContext,\n\t\t\tassistantMessage,\n\t\t\t{ beforeToolCall: this.beforeToolCall, afterToolCall: this.afterToolCall },\n\t\t\tsignal,\n\t\t\t(event) => this.processEvents(event),\n\t\t);\n\t\tif (ctx) {\n\t\t\tctx.context.messages.push(toolResultMessage);\n\t\t\tctx.newMessages.push(toolResultMessage);\n\t\t}\n\t}\n\n\tprivate createHarnessAssistantMessage(toolCall: AgentToolCall): AssistantMessage {\n\t\treturn {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [toolCall],\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: \"toolUse\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\t}\n}\n"]}
package/dist/agent.js CHANGED
@@ -27,7 +27,7 @@ const DEFAULT_MODEL = {
27
27
  // The id must satisfy every provider's constraint (Anthropic's `^[a-zA-Z0-9_-]+$`, bounded length)
28
28
  // and must never embed raw model ids. A random suffix (not a bare counter) avoids collisions with
29
29
  // ids already present in a resumed transcript.
30
- function generateHarnessToolCallId() {
30
+ export function generateHarnessToolCallId() {
31
31
  const uuid = globalThis.crypto?.randomUUID?.();
32
32
  const suffix = uuid
33
33
  ? uuid.replace(/-/g, "")
@@ -111,9 +111,16 @@ export class Agent {
111
111
  afterToolCall;
112
112
  prepareNextTurn;
113
113
  activeRun;
114
- // SCRAMJET-DIVERGENCE: harness-tool-invocation primitive state (#244).
115
- /** Harness tool calls queued while a run is active, drained at the next turn boundary. */
114
+ // SCRAMJET-DIVERGENCE: harness-tool-invocation primitive state (#244, settlement #341).
115
+ /** Harness tool invocations queued while a run is active, drained at the next turn boundary. */
116
116
  harnessToolQueue = [];
117
+ /**
118
+ * Every harness-tool invocation whose public promise has not yet settled — queued, shifted and
119
+ * draining, or transient. Reset/teardown rejects this set; each invocation is removed as it
120
+ * settles. Queue length is not a proxy for this: a draining call has left the queue but is still
121
+ * unsettled (#341).
122
+ */
123
+ unsettledHarnessTools = new Set();
117
124
  /**
118
125
  * Markers for in-flight transient (idle) harness-tool runs; each resolves when its run settles.
119
126
  * A set (not a single field) keeps nested and overlapping transient runs valid, and lets a new
@@ -238,13 +245,17 @@ export class Agent {
238
245
  this._state.errorMessage = undefined;
239
246
  this.clearFollowUpQueue();
240
247
  this.clearSteeringQueue();
241
- // SCRAMJET-DIVERGENCE: harness-tool-invocation primitive (#244). Queued harness
242
- // tool calls are dropped on reset; surface it so a lost record row is diagnosable.
243
- if (this.harnessToolQueue.length > 0) {
244
- const names = this.harnessToolQueue.map((item) => item.tool.name).join(", ");
245
- console.warn(`Agent.reset() discarded ${this.harnessToolQueue.length} queued harness tool call(s): ${names}`);
248
+ // SCRAMJET-DIVERGENCE: harness-tool-invocation primitive (#244, settlement #341). reset()
249
+ // rejects the public promise of every unsettled harness invocation so awaiting callers stop
250
+ // waiting. The effect on the record row differs by kind: a queued (not-yet-draining) call loses
251
+ // its row entirely, while a transient in-flight call keeps running — reset() does not abort
252
+ // transientRunAbort — so its row is still emitted and persisted; only its promise is rejected.
253
+ // The warning surfaces the rejection so a lost queued row is diagnosable.
254
+ if (this.unsettledHarnessTools.size > 0) {
255
+ const names = [...this.unsettledHarnessTools].map((record) => record.tool.name).join(", ");
256
+ console.warn(`Agent.reset() rejected ${this.unsettledHarnessTools.size} unsettled harness tool call(s): ${names}`);
246
257
  }
247
- this.harnessToolQueue.length = 0;
258
+ this.rejectUnsettledHarnessTools(new Error("Agent.reset() discarded unsettled harness tool call"));
248
259
  }
249
260
  async prompt(input, images) {
250
261
  if (this.activeRun) {
@@ -356,6 +367,13 @@ export class Agent {
356
367
  this._state.isStreaming = true;
357
368
  this._state.streamingMessage = undefined;
358
369
  this._state.errorMessage = undefined;
370
+ // SCRAMJET-DIVERGENCE (#341): a failed final flush leaves later queued calls unable to execute.
371
+ // Capture it (rejecting remnants below) and re-throw after finishRun so the error propagates out
372
+ // of prompt()/continue() — not activeRun.promise, which finishRun always resolves — without a
373
+ // lint-flagged throw inside a finally block. The { error } wrapper (not a bare `unknown` field)
374
+ // is deliberate: it distinguishes "no drain error" from a falsy throw (e.g. `throw undefined`),
375
+ // which a `!== undefined` check on a bare field would silently swallow.
376
+ let finalDrainError;
359
377
  try {
360
378
  // Wait for in-flight transient harness-tool runs so their events do not interleave
361
379
  // with this run's transcript.
@@ -374,10 +392,19 @@ export class Agent {
374
392
  // never stranded. Emits messages/tool events but no run framing.
375
393
  await this.drainHarnessToolQueue(undefined, abortController.signal);
376
394
  }
395
+ catch (drainError) {
396
+ // The failing call was already rejected by executeHarnessInvocation; reject the
397
+ // remnants too so their promises settle.
398
+ this.rejectUnsettledHarnessTools(drainError instanceof Error ? drainError : new Error(String(drainError)));
399
+ finalDrainError = { error: drainError };
400
+ }
377
401
  finally {
378
402
  this.finishRun();
379
403
  }
380
404
  }
405
+ if (finalDrainError) {
406
+ throw finalDrainError.error;
407
+ }
381
408
  }
382
409
  async handleRunFailure(error, aborted) {
383
410
  const failureMessage = {
@@ -454,7 +481,7 @@ export class Agent {
454
481
  await listener(event, signal);
455
482
  }
456
483
  }
457
- // SCRAMJET-DIVERGENCE: harness-tool-invocation primitive (#244).
484
+ // SCRAMJET-DIVERGENCE: harness-tool-invocation primitive (#244, execution settlement #341).
458
485
  /**
459
486
  * Execute a harness-originated tool call through the real execution pipeline.
460
487
  *
@@ -468,33 +495,110 @@ export class Agent {
468
495
  * When idle, the call executes immediately in a transient run scope. When a run is active, it is
469
496
  * queued and drained at the next turn boundary — before the next intra-run LLM call — with an
470
497
  * end-of-run flush for calls queued during the run's final turn, so a queued call is never stranded.
498
+ *
499
+ * **Settlement (#341).** The returned promise resolves only after the call's full Agent-core
500
+ * pipeline finishes: the synthetic assistant tool-call message, tool prepare/execute/finalize, the
501
+ * tool-result message, Agent state reduction, and every awaited listener for those events. A queued
502
+ * call therefore does not resolve at enqueue time — it resolves when the drain executes it. The
503
+ * promise rejects when reset or session teardown revokes an unsettled invocation, when an
504
+ * infrastructure/listener/hook failure escapes the pipeline, or when a failed final drain leaves a
505
+ * later queued call unable to execute. A tool's own `execute()` throwing is **not** a rejection: it
506
+ * becomes a normal `isError: true` tool result, so the promise resolves after that error-result
507
+ * pipeline completes. Rejection means the promised pipeline did not complete — it does not prove
508
+ * artifact absence (state and persistence may have partially completed), so callers must not blindly
509
+ * retry.
510
+ *
511
+ * This settles Agent-core execution only. It does **not** prove AgentSession persistence;
512
+ * `AgentSession.invokeHarnessTool` layers the persisted-settlement boundary on top of it.
513
+ *
514
+ * **Reentrancy.** Do not `await` this from work whose return is required for the Agent to reach the
515
+ * drain point (a model-callable `execute`, `beforeToolBatch`/`beforeToolCall`/`afterToolCall`/
516
+ * `prepareNextTurn`, or an awaited listener), or the queued call can never execute and the await
517
+ * deadlocks. Start/capture the promise, return from the gating callback, and await it from an
518
+ * independent continuation.
471
519
  */
472
520
  async runHarnessTool(tool, args, options = {}) {
473
521
  const toolCallId = options.toolCallId ?? generateHarnessToolCallId();
522
+ const record = this.createHarnessInvocation(tool, args, toolCallId);
474
523
  if (this.activeRun) {
475
- this.harnessToolQueue.push({ tool, args, toolCallId });
476
- return;
524
+ this.harnessToolQueue.push(record);
525
+ return record.promise;
477
526
  }
478
527
  // Register the marker before the first event so processEvents sees transient work in
479
- // flight from the start, including for nested calls (a harness tool invoking another).
480
- let settle;
528
+ // flight from the start, including for nested calls (a harness tool invoking another). The
529
+ // marker tracks the underlying work even if reset/teardown rejects the public promise first,
530
+ // so a later prompt still waits for the transient events to finish before emitting its own.
531
+ let settleMarker;
481
532
  const marker = new Promise((resolve) => {
482
- settle = resolve;
533
+ settleMarker = resolve;
483
534
  });
484
535
  this.transientRuns.add(marker);
536
+ void (async () => {
537
+ try {
538
+ await this.executeHarnessInvocation(record, this.transientRunAbort.signal, undefined);
539
+ }
540
+ catch {
541
+ // The rejection is already recorded on record.promise; a transient run has no run-failure
542
+ // path to propagate into, so nothing escapes here.
543
+ }
544
+ finally {
545
+ this.transientRuns.delete(marker);
546
+ settleMarker();
547
+ }
548
+ })();
549
+ return record.promise;
550
+ }
551
+ // SCRAMJET-DIVERGENCE (#341): back a harness-tool invocation with a deferred promise and track it
552
+ // as unsettled until it resolves or is rejected.
553
+ createHarnessInvocation(tool, args, toolCallId) {
554
+ let resolve;
555
+ let reject;
556
+ const promise = new Promise((res, rej) => {
557
+ resolve = res;
558
+ reject = rej;
559
+ });
560
+ const record = { tool, args, toolCallId, promise, resolve, reject };
561
+ this.unsettledHarnessTools.add(record);
562
+ return record;
563
+ }
564
+ // SCRAMJET-DIVERGENCE (#341): settle a harness invocation exactly once. Set membership is the
565
+ // settled flag: unsettledHarnessTools.delete() returns false when the record was already removed
566
+ // (e.g. underlying transient work finishing after reset already rejected it), so a later attempt
567
+ // is a no-op.
568
+ settleHarnessInvocation(record, error) {
569
+ if (!this.unsettledHarnessTools.delete(record))
570
+ return;
571
+ if (error)
572
+ record.reject(error);
573
+ else
574
+ record.resolve();
575
+ }
576
+ // SCRAMJET-DIVERGENCE (#341): run one invocation's pipeline and settle its record. Infrastructure
577
+ // failures reject the record and rethrow so the drain path preserves current run-failure behavior;
578
+ // a tool's own execute() error is not seen here (it resolves as an isError tool result).
579
+ async executeHarnessInvocation(record, signal, ctx) {
485
580
  try {
486
- await this.emitHarnessToolCall(tool, args, toolCallId, this.transientRunAbort.signal, undefined);
581
+ await this.emitHarnessToolCall(record.tool, record.args, record.toolCallId, signal, ctx);
487
582
  }
488
- finally {
489
- this.transientRuns.delete(marker);
490
- settle();
583
+ catch (error) {
584
+ this.settleHarnessInvocation(record, error instanceof Error ? error : new Error(String(error)));
585
+ throw error;
586
+ }
587
+ this.settleHarnessInvocation(record);
588
+ }
589
+ // SCRAMJET-DIVERGENCE (#341): idempotently clear the queue and reject every still-unsettled
590
+ // invocation (queued, draining, or transient). Used by reset() and by the final-drain failure path.
591
+ rejectUnsettledHarnessTools(reason) {
592
+ this.harnessToolQueue.length = 0;
593
+ for (const record of [...this.unsettledHarnessTools]) {
594
+ this.settleHarnessInvocation(record, reason);
491
595
  }
492
596
  }
493
597
  /** Drain all queued harness tool calls, splicing them into `ctx` when draining mid-run. */
494
598
  async drainHarnessToolQueue(ctx, signal) {
495
599
  while (this.harnessToolQueue.length > 0) {
496
- const item = this.harnessToolQueue.shift();
497
- await this.emitHarnessToolCall(item.tool, item.args, item.toolCallId, signal, ctx);
600
+ const record = this.harnessToolQueue.shift();
601
+ await this.executeHarnessInvocation(record, signal, ctx);
498
602
  }
499
603
  }
500
604
  /**
package/dist/agent.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAMN,YAAY,GAIZ,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,sBAAsB,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAuB7F,SAAS,mBAAmB,CAAC,QAAwB,EAAa;IACjE,OAAO,QAAQ,CAAC,MAAM,CACrB,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW,IAAI,OAAO,CAAC,IAAI,KAAK,YAAY,CACrG,CAAC;AAAA,CACF;AAED,MAAM,WAAW,GAAG;IACnB,KAAK,EAAE,CAAC;IACR,MAAM,EAAE,CAAC;IACT,SAAS,EAAE,CAAC;IACZ,UAAU,EAAE,CAAC;IACb,WAAW,EAAE,CAAC;IACd,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE;CACpE,CAAC;AAEF,MAAM,aAAa,GAAG;IACrB,EAAE,EAAE,SAAS;IACb,IAAI,EAAE,SAAS;IACf,GAAG,EAAE,SAAS;IACd,QAAQ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ACD;IAEO,6BAA6B,CAAC,QAAuB,EAAoB;QAChF,OAAO;YACN,IAAI,EAAE,WAAW;YACjB,OAAO,EAAE,CAAC,QAAQ,CAAC;YACnB,GAAG,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG;YAC1B,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ;YACpC,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE;YAC3B,KAAK,EAAE,WAAW;YAClB,UAAU,EAAE,SAAS;YACrB,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;SACrB,CAAC;IAAA,CACF;CACD","sourcesContent":["import {\n\ttype AssistantMessage,\n\ttype ImageContent,\n\ttype Message,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"@leanandmean/ai\";\nimport { executeHarnessToolCall, runAgentLoop, runAgentLoopContinue } from \"./agent-loop.js\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tAgentToolCall,\n\tBeforeToolBatchContext,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tPrepareNextTurnContext,\n\tQueueMode,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.js\";\n\nexport type { QueueMode } from \"./types.js\";\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\n// SCRAMJET-DIVERGENCE: provider-safe tool-call id generation for harness-originated calls (#244).\n// The id must satisfy every provider's constraint (Anthropic's `^[a-zA-Z0-9_-]+$`, bounded length)\n// and must never embed raw model ids. A random suffix (not a bare counter) avoids collisions with\n// ids already present in a resumed transcript.\nfunction generateHarnessToolCallId(): string {\n\tconst uuid = globalThis.crypto?.randomUUID?.();\n\tconst suffix = uuid\n\t\t? uuid.replace(/-/g, \"\")\n\t\t: `${Date.now().toString(36)}${Math.floor(Math.random() * 1e9).toString(36)}`;\n\treturn `harness-tool-${suffix}`.slice(0, 64);\n}\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\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolBatch?: (context: BeforeToolBatchContext, signal?: AbortSignal) => Promise<void>;\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\t// SCRAMJET-DIVERGENCE: prepareNextTurn receives the live turn context (previously the loop\n\t// context it passes was discarded by the Agent adapter) (#244).\n\tprepareNextTurn?: (\n\t\tctx: PrepareNextTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\ttoolExecution?: ToolExecutionMode;\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\n\tconstructor(public mode: QueueMode) {}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.messages.slice();\n\t\t\tthis.messages = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.messages[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.messages = this.messages.slice(1);\n\t\treturn [first];\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFn: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\t// SCRAMJET-DIVERGENCE: beforeToolBatch hook — async message_end mutations must settle before tool-call extraction\n\tpublic beforeToolBatch?: (context: BeforeToolBatchContext, signal?: AbortSignal) => Promise<void>;\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic prepareNextTurn?: (\n\t\tctx: PrepareNextTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t// SCRAMJET-DIVERGENCE: harness-tool-invocation primitive state (#244).\n\t/** Harness tool calls queued while a run is active, drained at the next turn boundary. */\n\tprivate readonly harnessToolQueue: Array<{ tool: AgentTool<any>; args: unknown; toolCallId: string }> = [];\n\t/**\n\t * Markers for in-flight transient (idle) harness-tool runs; each resolves when its run settles.\n\t * A set (not a single field) keeps nested and overlapping transient runs valid, and lets a new\n\t * real run wait for transient work to finish before emitting its own events.\n\t */\n\tprivate readonly transientRuns = new Set<Promise<void>>();\n\t/** Shared, never-aborted signal delivered to listeners during transient harness-tool runs. */\n\tprivate readonly transientRunAbort = new AbortController();\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\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.beforeToolBatch = options.beforeToolBatch;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.prepareNextTurn = options.prepareNextTurn;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.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\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear transcript state, runtime state, and queued messages. */\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t\t// SCRAMJET-DIVERGENCE: harness-tool-invocation primitive (#244). Queued harness\n\t\t// tool calls are dropped on reset; surface it so a lost record row is diagnosable.\n\t\tif (this.harnessToolQueue.length > 0) {\n\t\t\tconst names = this.harnessToolQueue.map((item) => item.tool.name).join(\", \");\n\t\t\tconsole.warn(`Agent.reset() discarded ${this.harnessToolQueue.length} queued harness tool call(s): ${names}`);\n\t\t}\n\t\tthis.harnessToolQueue.length = 0;\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new Error(\"Cannot continue from message role: assistant\");\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\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\tbeforeToolBatch: this.beforeToolBatch,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\t// SCRAMJET-DIVERGENCE: always run prepareNextTurn so mid-run harness tool calls drain\n\t\t\t// into the live turn context before the next intra-run LLM call, and so the next call\n\t\t\t// self-heals onto the current model (routing after a mid-run switch) (#244).\n\t\t\tprepareNextTurn: async (ctx) => {\n\t\t\t\tawait this.drainHarnessToolQueue(ctx, this.signal);\n\t\t\t\tconst update = await this.prepareNextTurn?.(ctx, this.signal);\n\t\t\t\treturn { ...update, model: update?.model ?? this._state.model };\n\t\t\t},\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\t// Wait for in-flight transient harness-tool runs so their events do not interleave\n\t\t\t// with this run's transcript.\n\t\t\twhile (this.transientRuns.size > 0) {\n\t\t\t\tawait Promise.all(this.transientRuns);\n\t\t\t}\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tawait this.handleRunFailure(error, abortController.signal.aborted);\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\t// Flush harness tool calls queued during the run's final turn — including failed or\n\t\t\t\t// aborted runs — after the last prepareNextTurn drain point, so a queued call is\n\t\t\t\t// never stranded. Emits messages/tool events but no run framing.\n\t\t\t\tawait this.drainHarnessToolQueue(undefined, abortController.signal);\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\ttimestamp: Date.now(),\n\t\t} satisfies AgentMessage;\n\t\tawait this.processEvents({ type: \"message_start\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"message_end\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"turn_end\", message: failureMessage, toolResults: [] });\n\t\tawait this.processEvents({ type: \"agent_end\", messages: [failureMessage] });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/**\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\tbreak;\n\t\t}\n\n\t\t// SCRAMJET-DIVERGENCE: fall back to the shared transient-run signal while transient\n\t\t// harness-tool work (which intentionally has no `activeRun`) is in flight (#244).\n\t\tconst signal =\n\t\t\tthis.activeRun?.abortController.signal ??\n\t\t\t(this.transientRuns.size > 0 ? this.transientRunAbort.signal : undefined);\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\t// SCRAMJET-DIVERGENCE: harness-tool-invocation primitive (#244).\n\t/**\n\t * Execute a harness-originated tool call through the real execution pipeline.\n\t *\n\t * The tool object is supplied directly, so it need not appear in `state.tools` — this is what\n\t * lets LLM-invisible harness tools execute. The call produces the same `tool_execution_*` and\n\t * message events, persisted messages, and `beforeToolCall`/`afterToolCall` invocations as a\n\t * normal tool execution, but emits **no** run/turn framing events (`agent_start`, `turn_start`,\n\t * `turn_end`, `agent_end`). It is therefore intentionally invisible to every `agent_end`-keyed\n\t * consumer (probe scheduling, compaction bookkeeping).\n\t *\n\t * When idle, the call executes immediately in a transient run scope. When a run is active, it is\n\t * queued and drained at the next turn boundary — before the next intra-run LLM call — with an\n\t * end-of-run flush for calls queued during the run's final turn, so a queued call is never stranded.\n\t */\n\tasync runHarnessTool(tool: AgentTool<any>, args: unknown, options: { toolCallId?: string } = {}): Promise<void> {\n\t\tconst toolCallId = options.toolCallId ?? generateHarnessToolCallId();\n\t\tif (this.activeRun) {\n\t\t\tthis.harnessToolQueue.push({ tool, args, toolCallId });\n\t\t\treturn;\n\t\t}\n\t\t// Register the marker before the first event so processEvents sees transient work in\n\t\t// flight from the start, including for nested calls (a harness tool invoking another).\n\t\tlet settle!: () => void;\n\t\tconst marker = new Promise<void>((resolve) => {\n\t\t\tsettle = resolve;\n\t\t});\n\t\tthis.transientRuns.add(marker);\n\t\ttry {\n\t\t\tawait this.emitHarnessToolCall(tool, args, toolCallId, this.transientRunAbort.signal, undefined);\n\t\t} finally {\n\t\t\tthis.transientRuns.delete(marker);\n\t\t\tsettle();\n\t\t}\n\t}\n\n\t/** Drain all queued harness tool calls, splicing them into `ctx` when draining mid-run. */\n\tprivate async drainHarnessToolQueue(\n\t\tctx: PrepareNextTurnContext | undefined,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<void> {\n\t\twhile (this.harnessToolQueue.length > 0) {\n\t\t\tconst item = this.harnessToolQueue.shift()!;\n\t\t\tawait this.emitHarnessToolCall(item.tool, item.args, item.toolCallId, signal, ctx);\n\t\t}\n\t}\n\n\t/**\n\t * Emit the full event sequence for one harness tool call: a synthetic single-toolCall assistant\n\t * message, then the tool execution and its result message. When `ctx` is provided (mid-run drain),\n\t * the synthetic messages are also spliced into the live turn context and returned-message set so\n\t * the next intra-run LLM call includes them.\n\t */\n\tprivate async emitHarnessToolCall(\n\t\ttool: AgentTool<any>,\n\t\targs: unknown,\n\t\ttoolCallId: string,\n\t\tsignal: AbortSignal | undefined,\n\t\tctx: PrepareNextTurnContext | undefined,\n\t): Promise<void> {\n\t\tconst toolCall: AgentToolCall = {\n\t\t\ttype: \"toolCall\",\n\t\t\tid: toolCallId,\n\t\t\tname: tool.name,\n\t\t\targuments: (args ?? {}) as Record<string, any>,\n\t\t};\n\t\tconst assistantMessage = this.createHarnessAssistantMessage(toolCall);\n\t\tawait this.processEvents({ type: \"message_start\", message: assistantMessage });\n\t\tawait this.processEvents({ type: \"message_end\", message: assistantMessage });\n\t\tif (ctx) {\n\t\t\tctx.context.messages.push(assistantMessage);\n\t\t\tctx.newMessages.push(assistantMessage);\n\t\t}\n\n\t\tconst hookContext = ctx?.context ?? this.createContextSnapshot();\n\t\tconst toolResultMessage = await executeHarnessToolCall(\n\t\t\ttool,\n\t\t\ttoolCall,\n\t\t\thookContext,\n\t\t\tassistantMessage,\n\t\t\t{ beforeToolCall: this.beforeToolCall, afterToolCall: this.afterToolCall },\n\t\t\tsignal,\n\t\t\t(event) => this.processEvents(event),\n\t\t);\n\t\tif (ctx) {\n\t\t\tctx.context.messages.push(toolResultMessage);\n\t\t\tctx.newMessages.push(toolResultMessage);\n\t\t}\n\t}\n\n\tprivate createHarnessAssistantMessage(toolCall: AgentToolCall): AssistantMessage {\n\t\treturn {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [toolCall],\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: \"toolUse\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\t}\n}\n"]}
1
+ {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAMN,YAAY,GAIZ,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,sBAAsB,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAuB7F,SAAS,mBAAmB,CAAC,QAAwB,EAAa;IACjE,OAAO,QAAQ,CAAC,MAAM,CACrB,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW,IAAI,OAAO,CAAC,IAAI,KAAK,YAAY,CACrG,CAAC;AAAA,CACF;AAED,MAAM,WAAW,GAAG;IACnB,KAAK,EA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,MAAM,iBAAiB,GAAG,MAAM,sBAAsB,CACrD,IAAI,EACJ,QAAQ,EACR,WAAW,EACX,gBAAgB,EAChB,EAAE,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,aAAa,EAAE,IAAI,CAAC,aAAa,EAAE,EAC1E,MAAM,EACN,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,CACpC,CAAC;QACF,IAAI,GAAG,EAAE,CAAC;YACT,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC;YAC7C,GAAG,CAAC,WAAW,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC;QACzC,CAAC;IAAA,CACD;IAEO,6BAA6B,CAAC,QAAuB,EAAoB;QAChF,OAAO;YACN,IAAI,EAAE,WAAW;YACjB,OAAO,EAAE,CAAC,QAAQ,CAAC;YACnB,GAAG,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG;YAC1B,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ;YACpC,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE;YAC3B,KAAK,EAAE,WAAW;YAClB,UAAU,EAAE,SAAS;YACrB,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;SACrB,CAAC;IAAA,CACF;CACD","sourcesContent":["import {\n\ttype AssistantMessage,\n\ttype ImageContent,\n\ttype Message,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"@leanandmean/ai\";\nimport { executeHarnessToolCall, runAgentLoop, runAgentLoopContinue } from \"./agent-loop.js\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tAgentToolCall,\n\tBeforeToolBatchContext,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tPrepareNextTurnContext,\n\tQueueMode,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.js\";\n\nexport type { QueueMode } from \"./types.js\";\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\n// SCRAMJET-DIVERGENCE: provider-safe tool-call id generation for harness-originated calls (#244).\n// The id must satisfy every provider's constraint (Anthropic's `^[a-zA-Z0-9_-]+$`, bounded length)\n// and must never embed raw model ids. A random suffix (not a bare counter) avoids collisions with\n// ids already present in a resumed transcript.\nexport function generateHarnessToolCallId(): string {\n\tconst uuid = globalThis.crypto?.randomUUID?.();\n\tconst suffix = uuid\n\t\t? uuid.replace(/-/g, \"\")\n\t\t: `${Date.now().toString(36)}${Math.floor(Math.random() * 1e9).toString(36)}`;\n\treturn `harness-tool-${suffix}`.slice(0, 64);\n}\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\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolBatch?: (context: BeforeToolBatchContext, signal?: AbortSignal) => Promise<void>;\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\t// SCRAMJET-DIVERGENCE: prepareNextTurn receives the live turn context (previously the loop\n\t// context it passes was discarded by the Agent adapter) (#244).\n\tprepareNextTurn?: (\n\t\tctx: PrepareNextTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\ttoolExecution?: ToolExecutionMode;\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\n\tconstructor(public mode: QueueMode) {}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.messages.slice();\n\t\t\tthis.messages = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.messages[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.messages = this.messages.slice(1);\n\t\treturn [first];\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n// SCRAMJET-DIVERGENCE: harness-tool-invocation settlement records (#341).\n/**\n * One harness-tool invocation and the deferred promise that `runHarnessTool` returns for it. The\n * promise settles only when the invocation's Agent-core pipeline completes (resolve) or when\n * reset/teardown revokes the invocation or an infrastructure failure escapes the pipeline (reject).\n */\ntype HarnessToolInvocation = {\n\ttool: AgentTool<any>;\n\targs: unknown;\n\ttoolCallId: string;\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\treject: (reason: Error) => void;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFn: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\t// SCRAMJET-DIVERGENCE: beforeToolBatch hook — async message_end mutations must settle before tool-call extraction\n\tpublic beforeToolBatch?: (context: BeforeToolBatchContext, signal?: AbortSignal) => Promise<void>;\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic prepareNextTurn?: (\n\t\tctx: PrepareNextTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t// SCRAMJET-DIVERGENCE: harness-tool-invocation primitive state (#244, settlement #341).\n\t/** Harness tool invocations queued while a run is active, drained at the next turn boundary. */\n\tprivate readonly harnessToolQueue: HarnessToolInvocation[] = [];\n\t/**\n\t * Every harness-tool invocation whose public promise has not yet settled — queued, shifted and\n\t * draining, or transient. Reset/teardown rejects this set; each invocation is removed as it\n\t * settles. Queue length is not a proxy for this: a draining call has left the queue but is still\n\t * unsettled (#341).\n\t */\n\tprivate readonly unsettledHarnessTools = new Set<HarnessToolInvocation>();\n\t/**\n\t * Markers for in-flight transient (idle) harness-tool runs; each resolves when its run settles.\n\t * A set (not a single field) keeps nested and overlapping transient runs valid, and lets a new\n\t * real run wait for transient work to finish before emitting its own events.\n\t */\n\tprivate readonly transientRuns = new Set<Promise<void>>();\n\t/** Shared, never-aborted signal delivered to listeners during transient harness-tool runs. */\n\tprivate readonly transientRunAbort = new AbortController();\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\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.beforeToolBatch = options.beforeToolBatch;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.prepareNextTurn = options.prepareNextTurn;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.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\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear transcript state, runtime state, and queued messages. */\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t\t// SCRAMJET-DIVERGENCE: harness-tool-invocation primitive (#244, settlement #341). reset()\n\t\t// rejects the public promise of every unsettled harness invocation so awaiting callers stop\n\t\t// waiting. The effect on the record row differs by kind: a queued (not-yet-draining) call loses\n\t\t// its row entirely, while a transient in-flight call keeps running — reset() does not abort\n\t\t// transientRunAbort — so its row is still emitted and persisted; only its promise is rejected.\n\t\t// The warning surfaces the rejection so a lost queued row is diagnosable.\n\t\tif (this.unsettledHarnessTools.size > 0) {\n\t\t\tconst names = [...this.unsettledHarnessTools].map((record) => record.tool.name).join(\", \");\n\t\t\tconsole.warn(\n\t\t\t\t`Agent.reset() rejected ${this.unsettledHarnessTools.size} unsettled harness tool call(s): ${names}`,\n\t\t\t);\n\t\t}\n\t\tthis.rejectUnsettledHarnessTools(new Error(\"Agent.reset() discarded unsettled harness tool call\"));\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new Error(\"Cannot continue from message role: assistant\");\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\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\tbeforeToolBatch: this.beforeToolBatch,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\t// SCRAMJET-DIVERGENCE: always run prepareNextTurn so mid-run harness tool calls drain\n\t\t\t// into the live turn context before the next intra-run LLM call, and so the next call\n\t\t\t// self-heals onto the current model (routing after a mid-run switch) (#244).\n\t\t\tprepareNextTurn: async (ctx) => {\n\t\t\t\tawait this.drainHarnessToolQueue(ctx, this.signal);\n\t\t\t\tconst update = await this.prepareNextTurn?.(ctx, this.signal);\n\t\t\t\treturn { ...update, model: update?.model ?? this._state.model };\n\t\t\t},\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\t// SCRAMJET-DIVERGENCE (#341): a failed final flush leaves later queued calls unable to execute.\n\t\t// Capture it (rejecting remnants below) and re-throw after finishRun so the error propagates out\n\t\t// of prompt()/continue() — not activeRun.promise, which finishRun always resolves — without a\n\t\t// lint-flagged throw inside a finally block. The { error } wrapper (not a bare `unknown` field)\n\t\t// is deliberate: it distinguishes \"no drain error\" from a falsy throw (e.g. `throw undefined`),\n\t\t// which a `!== undefined` check on a bare field would silently swallow.\n\t\tlet finalDrainError: { error: unknown } | undefined;\n\t\ttry {\n\t\t\t// Wait for in-flight transient harness-tool runs so their events do not interleave\n\t\t\t// with this run's transcript.\n\t\t\twhile (this.transientRuns.size > 0) {\n\t\t\t\tawait Promise.all(this.transientRuns);\n\t\t\t}\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tawait this.handleRunFailure(error, abortController.signal.aborted);\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\t// Flush harness tool calls queued during the run's final turn — including failed or\n\t\t\t\t// aborted runs — after the last prepareNextTurn drain point, so a queued call is\n\t\t\t\t// never stranded. Emits messages/tool events but no run framing.\n\t\t\t\tawait this.drainHarnessToolQueue(undefined, abortController.signal);\n\t\t\t} catch (drainError) {\n\t\t\t\t// The failing call was already rejected by executeHarnessInvocation; reject the\n\t\t\t\t// remnants too so their promises settle.\n\t\t\t\tthis.rejectUnsettledHarnessTools(drainError instanceof Error ? drainError : new Error(String(drainError)));\n\t\t\t\tfinalDrainError = { error: drainError };\n\t\t\t} finally {\n\t\t\t\tthis.finishRun();\n\t\t\t}\n\t\t}\n\t\tif (finalDrainError) {\n\t\t\tthrow finalDrainError.error;\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\ttimestamp: Date.now(),\n\t\t} satisfies AgentMessage;\n\t\tawait this.processEvents({ type: \"message_start\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"message_end\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"turn_end\", message: failureMessage, toolResults: [] });\n\t\tawait this.processEvents({ type: \"agent_end\", messages: [failureMessage] });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/**\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\tbreak;\n\t\t}\n\n\t\t// SCRAMJET-DIVERGENCE: fall back to the shared transient-run signal while transient\n\t\t// harness-tool work (which intentionally has no `activeRun`) is in flight (#244).\n\t\tconst signal =\n\t\t\tthis.activeRun?.abortController.signal ??\n\t\t\t(this.transientRuns.size > 0 ? this.transientRunAbort.signal : undefined);\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\t// SCRAMJET-DIVERGENCE: harness-tool-invocation primitive (#244, execution settlement #341).\n\t/**\n\t * Execute a harness-originated tool call through the real execution pipeline.\n\t *\n\t * The tool object is supplied directly, so it need not appear in `state.tools` — this is what\n\t * lets LLM-invisible harness tools execute. The call produces the same `tool_execution_*` and\n\t * message events, persisted messages, and `beforeToolCall`/`afterToolCall` invocations as a\n\t * normal tool execution, but emits **no** run/turn framing events (`agent_start`, `turn_start`,\n\t * `turn_end`, `agent_end`). It is therefore intentionally invisible to every `agent_end`-keyed\n\t * consumer (probe scheduling, compaction bookkeeping).\n\t *\n\t * When idle, the call executes immediately in a transient run scope. When a run is active, it is\n\t * queued and drained at the next turn boundary — before the next intra-run LLM call — with an\n\t * end-of-run flush for calls queued during the run's final turn, so a queued call is never stranded.\n\t *\n\t * **Settlement (#341).** The returned promise resolves only after the call's full Agent-core\n\t * pipeline finishes: the synthetic assistant tool-call message, tool prepare/execute/finalize, the\n\t * tool-result message, Agent state reduction, and every awaited listener for those events. A queued\n\t * call therefore does not resolve at enqueue time — it resolves when the drain executes it. The\n\t * promise rejects when reset or session teardown revokes an unsettled invocation, when an\n\t * infrastructure/listener/hook failure escapes the pipeline, or when a failed final drain leaves a\n\t * later queued call unable to execute. A tool's own `execute()` throwing is **not** a rejection: it\n\t * becomes a normal `isError: true` tool result, so the promise resolves after that error-result\n\t * pipeline completes. Rejection means the promised pipeline did not complete — it does not prove\n\t * artifact absence (state and persistence may have partially completed), so callers must not blindly\n\t * retry.\n\t *\n\t * This settles Agent-core execution only. It does **not** prove AgentSession persistence;\n\t * `AgentSession.invokeHarnessTool` layers the persisted-settlement boundary on top of it.\n\t *\n\t * **Reentrancy.** Do not `await` this from work whose return is required for the Agent to reach the\n\t * drain point (a model-callable `execute`, `beforeToolBatch`/`beforeToolCall`/`afterToolCall`/\n\t * `prepareNextTurn`, or an awaited listener), or the queued call can never execute and the await\n\t * deadlocks. Start/capture the promise, return from the gating callback, and await it from an\n\t * independent continuation.\n\t */\n\tasync runHarnessTool(tool: AgentTool<any>, args: unknown, options: { toolCallId?: string } = {}): Promise<void> {\n\t\tconst toolCallId = options.toolCallId ?? generateHarnessToolCallId();\n\t\tconst record = this.createHarnessInvocation(tool, args, toolCallId);\n\t\tif (this.activeRun) {\n\t\t\tthis.harnessToolQueue.push(record);\n\t\t\treturn record.promise;\n\t\t}\n\t\t// Register the marker before the first event so processEvents sees transient work in\n\t\t// flight from the start, including for nested calls (a harness tool invoking another). The\n\t\t// marker tracks the underlying work even if reset/teardown rejects the public promise first,\n\t\t// so a later prompt still waits for the transient events to finish before emitting its own.\n\t\tlet settleMarker!: () => void;\n\t\tconst marker = new Promise<void>((resolve) => {\n\t\t\tsettleMarker = resolve;\n\t\t});\n\t\tthis.transientRuns.add(marker);\n\t\tvoid (async () => {\n\t\t\ttry {\n\t\t\t\tawait this.executeHarnessInvocation(record, this.transientRunAbort.signal, undefined);\n\t\t\t} catch {\n\t\t\t\t// The rejection is already recorded on record.promise; a transient run has no run-failure\n\t\t\t\t// path to propagate into, so nothing escapes here.\n\t\t\t} finally {\n\t\t\t\tthis.transientRuns.delete(marker);\n\t\t\t\tsettleMarker();\n\t\t\t}\n\t\t})();\n\t\treturn record.promise;\n\t}\n\n\t// SCRAMJET-DIVERGENCE (#341): back a harness-tool invocation with a deferred promise and track it\n\t// as unsettled until it resolves or is rejected.\n\tprivate createHarnessInvocation(tool: AgentTool<any>, args: unknown, toolCallId: string): HarnessToolInvocation {\n\t\tlet resolve!: () => void;\n\t\tlet reject!: (reason: Error) => void;\n\t\tconst promise = new Promise<void>((res, rej) => {\n\t\t\tresolve = res;\n\t\t\treject = rej;\n\t\t});\n\t\tconst record: HarnessToolInvocation = { tool, args, toolCallId, promise, resolve, reject };\n\t\tthis.unsettledHarnessTools.add(record);\n\t\treturn record;\n\t}\n\n\t// SCRAMJET-DIVERGENCE (#341): settle a harness invocation exactly once. Set membership is the\n\t// settled flag: unsettledHarnessTools.delete() returns false when the record was already removed\n\t// (e.g. underlying transient work finishing after reset already rejected it), so a later attempt\n\t// is a no-op.\n\tprivate settleHarnessInvocation(record: HarnessToolInvocation, error?: Error): void {\n\t\tif (!this.unsettledHarnessTools.delete(record)) return;\n\t\tif (error) record.reject(error);\n\t\telse record.resolve();\n\t}\n\n\t// SCRAMJET-DIVERGENCE (#341): run one invocation's pipeline and settle its record. Infrastructure\n\t// failures reject the record and rethrow so the drain path preserves current run-failure behavior;\n\t// a tool's own execute() error is not seen here (it resolves as an isError tool result).\n\tprivate async executeHarnessInvocation(\n\t\trecord: HarnessToolInvocation,\n\t\tsignal: AbortSignal | undefined,\n\t\tctx: PrepareNextTurnContext | undefined,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tawait this.emitHarnessToolCall(record.tool, record.args, record.toolCallId, signal, ctx);\n\t\t} catch (error) {\n\t\t\tthis.settleHarnessInvocation(record, error instanceof Error ? error : new Error(String(error)));\n\t\t\tthrow error;\n\t\t}\n\t\tthis.settleHarnessInvocation(record);\n\t}\n\n\t// SCRAMJET-DIVERGENCE (#341): idempotently clear the queue and reject every still-unsettled\n\t// invocation (queued, draining, or transient). Used by reset() and by the final-drain failure path.\n\trejectUnsettledHarnessTools(reason: Error): void {\n\t\tthis.harnessToolQueue.length = 0;\n\t\tfor (const record of [...this.unsettledHarnessTools]) {\n\t\t\tthis.settleHarnessInvocation(record, reason);\n\t\t}\n\t}\n\n\t/** Drain all queued harness tool calls, splicing them into `ctx` when draining mid-run. */\n\tprivate async drainHarnessToolQueue(\n\t\tctx: PrepareNextTurnContext | undefined,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<void> {\n\t\twhile (this.harnessToolQueue.length > 0) {\n\t\t\tconst record = this.harnessToolQueue.shift()!;\n\t\t\tawait this.executeHarnessInvocation(record, signal, ctx);\n\t\t}\n\t}\n\n\t/**\n\t * Emit the full event sequence for one harness tool call: a synthetic single-toolCall assistant\n\t * message, then the tool execution and its result message. When `ctx` is provided (mid-run drain),\n\t * the synthetic messages are also spliced into the live turn context and returned-message set so\n\t * the next intra-run LLM call includes them.\n\t */\n\tprivate async emitHarnessToolCall(\n\t\ttool: AgentTool<any>,\n\t\targs: unknown,\n\t\ttoolCallId: string,\n\t\tsignal: AbortSignal | undefined,\n\t\tctx: PrepareNextTurnContext | undefined,\n\t): Promise<void> {\n\t\tconst toolCall: AgentToolCall = {\n\t\t\ttype: \"toolCall\",\n\t\t\tid: toolCallId,\n\t\t\tname: tool.name,\n\t\t\targuments: (args ?? {}) as Record<string, any>,\n\t\t};\n\t\tconst assistantMessage = this.createHarnessAssistantMessage(toolCall);\n\t\tawait this.processEvents({ type: \"message_start\", message: assistantMessage });\n\t\tawait this.processEvents({ type: \"message_end\", message: assistantMessage });\n\t\tif (ctx) {\n\t\t\tctx.context.messages.push(assistantMessage);\n\t\t\tctx.newMessages.push(assistantMessage);\n\t\t}\n\n\t\tconst hookContext = ctx?.context ?? this.createContextSnapshot();\n\t\tconst toolResultMessage = await executeHarnessToolCall(\n\t\t\ttool,\n\t\t\ttoolCall,\n\t\t\thookContext,\n\t\t\tassistantMessage,\n\t\t\t{ beforeToolCall: this.beforeToolCall, afterToolCall: this.afterToolCall },\n\t\t\tsignal,\n\t\t\t(event) => this.processEvents(event),\n\t\t);\n\t\tif (ctx) {\n\t\t\tctx.context.messages.push(toolResultMessage);\n\t\t\tctx.newMessages.push(toolResultMessage);\n\t\t}\n\t}\n\n\tprivate createHarnessAssistantMessage(toolCall: AgentToolCall): AssistantMessage {\n\t\treturn {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [toolCall],\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: \"toolUse\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\t}\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leanandmean/agent",
3
- "version": "0.74.1-scramjet.10",
3
+ "version": "0.74.1-scramjet.12",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -28,7 +28,7 @@
28
28
  "test": "vitest --run --passWithNoTests"
29
29
  },
30
30
  "dependencies": {
31
- "@leanandmean/ai": "0.74.1-scramjet.8",
31
+ "@leanandmean/ai": "0.74.1-scramjet.9",
32
32
  "ignore": "^7.0.5",
33
33
  "typebox": "^1.1.24",
34
34
  "yaml": "^2.8.2"