@anvia/core 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/agent/tool-state.ts","../src/hooks/control.ts","../src/agent/vector-context.ts","../src/internal/agent-runtime/run-options.ts","../src/agent/lifecycle.ts","../src/agent/output-schema.ts","../src/internal/async-queue.ts","../src/internal/rag-text.ts","../src/internal/agent-runtime/continuation-state.ts","../src/internal/agent-runtime/interaction-suspension.ts","../src/internal/agent-runtime/memory.ts","../src/internal/agent-runtime/memory-scope.ts","../src/internal/agent-runtime/retrieval.ts","../src/internal/agent-runtime/run-validation.ts","../src/internal/agent-runtime/stream-events.ts","../src/internal/agent-runtime/structured-output.ts","../src/internal/agent-runtime/tool-execution.ts","../src/internal/agent-runtime/agent-run.ts","../src/agent/agent-stream.ts","../src/agent/agent-tool.ts","../src/agent/ids.ts","../src/agent/resolve-options.ts","../src/agent/snapshot.ts","../src/agent/tool-catalog.ts","../src/agent/agent.ts"],"sourcesContent":["import type { ProviderTool } from \"../completion\";\nimport type { ToolIndex } from \"../tool/dynamic-tools\";\nimport type { AnyTool } from \"../tool/tool\";\n\nexport type AgentToolState = {\n configuredTools: readonly AnyTool[];\n staticTools: readonly AnyTool[];\n providerTools: readonly ProviderTool[];\n toolIndexes: readonly ToolIndex[];\n};\n\ntype StoredAgentToolState = {\n publicState: AgentToolState;\n toolsByName: Map<string, AnyTool>;\n};\n\nconst agentToolStates = new WeakMap<object, StoredAgentToolState>();\n\nexport function registerAgentToolState(\n agent: object,\n publicState: AgentToolState,\n toolsByName: Map<string, AnyTool>,\n): void {\n agentToolStates.set(agent, { publicState, toolsByName });\n}\n\nexport function getAgentToolState(agent: object): AgentToolState {\n return getStoredAgentToolState(agent).publicState;\n}\n\nexport function getRegisteredAgentTool(agent: object, toolName: string): AnyTool | undefined {\n return getStoredAgentToolState(agent).toolsByName.get(toolName);\n}\n\nfunction getStoredAgentToolState(agent: object): StoredAgentToolState {\n const state = agentToolStates.get(agent);\n if (state === undefined) {\n throw new TypeError(\"Agent tool state is unavailable.\");\n }\n return state;\n}\n","import type {\n AgentHook,\n HookAction,\n RunControl,\n ToolApprovalRequestOptions,\n ToolCallControl,\n ToolCallHookAction,\n} from \"./types\";\n\nexport function createHook<RawResponse = unknown>(\n hook: AgentHook<RawResponse>,\n): AgentHook<RawResponse> {\n return hook;\n}\n\nexport function cancelRun(reason: string): HookAction {\n return { type: \"terminate\", reason };\n}\n\nexport function skipTool(reason: string): ToolCallHookAction {\n return { type: \"skip\", reason };\n}\n\nexport function requestToolApproval(options: ToolApprovalRequestOptions = {}): ToolCallHookAction {\n const action: ToolCallHookAction = {\n type: \"approval_request\" as const,\n };\n if (options.reason !== undefined) {\n action.reason = options.reason;\n }\n if (options.rejectMessage !== undefined) {\n action.rejectMessage = options.rejectMessage;\n }\n return action;\n}\n\nexport const runControl: RunControl = {\n continue() {\n return { type: \"continue\" };\n },\n cancel(reason: string) {\n return cancelRun(reason);\n },\n};\n\nexport const toolCallControl: ToolCallControl = {\n run() {\n return { type: \"continue\" };\n },\n skip(reason: string) {\n return skipTool(reason);\n },\n cancel(reason: string) {\n return { type: \"terminate\", reason };\n },\n requestApproval(options) {\n return requestToolApproval(options);\n },\n};\n","import type { Document } from \"../completion\";\nimport type { EmbeddingModel, SparseEmbeddingModel } from \"../embeddings\";\nimport { assertFiniteMinScore, assertPositiveSearchLimit } from \"../internal/vector-search-options\";\nimport type { RetrySetting } from \"../retry\";\nimport type {\n HybridVectorStore,\n VectorFilter,\n VectorFusion,\n VectorSearchResult,\n VectorStore,\n} from \"../vector-store\";\n\nexport type VectorContextBaseOptions<T = unknown> = {\n topK: number;\n minScore?: number | undefined;\n filter?: VectorFilter | undefined;\n retries?: RetrySetting | undefined;\n format?(result: VectorSearchResult<T>): Document;\n};\n\nexport type CreateVectorContextOptions<T = unknown> = VectorContextBaseOptions<T> & {\n store: VectorStore<T>;\n model: EmbeddingModel;\n models?: never;\n};\n\nexport type CreateHybridVectorContextOptions<T = unknown> = VectorContextBaseOptions<T> & {\n store: HybridVectorStore<T>;\n model?: never;\n models: { dense: EmbeddingModel; sparse: SparseEmbeddingModel };\n fusion?: VectorFusion | undefined;\n};\n\nexport type VectorContext<T = unknown> = (\n | CreateVectorContextOptions<T>\n | CreateHybridVectorContextOptions<T>\n) & {\n readonly kind: \"vector-context\";\n};\n\nexport function createVectorContext<T>(options: CreateVectorContextOptions<T>): VectorContext<T>;\nexport function createVectorContext<T>(\n options: CreateHybridVectorContextOptions<T>,\n): VectorContext<T>;\nexport function createVectorContext<T>(\n options: CreateVectorContextOptions<T> | CreateHybridVectorContextOptions<T>,\n): VectorContext<T> {\n const topK = assertPositiveSearchLimit(options.topK);\n const minScore = assertFiniteMinScore(options.minScore);\n let context: VectorContext<T> = {\n ...options,\n topK,\n kind: \"vector-context\" as const,\n };\n if (minScore !== undefined) {\n context = { ...context, minScore };\n }\n return Object.freeze(context);\n}\n\nexport function isVectorContext(value: unknown): value is VectorContext {\n if (typeof value !== \"object\" || value === null) return false;\n const candidate = value as {\n kind?: unknown;\n store?: { search?: unknown };\n model?: unknown;\n models?: { dense?: unknown; sparse?: unknown };\n };\n if (candidate.kind !== \"vector-context\" || typeof candidate.store?.search !== \"function\") {\n return false;\n }\n return (\n candidate.model !== undefined ||\n (candidate.models?.dense !== undefined && candidate.models.sparse !== undefined)\n );\n}\n","import type { Message } from \"../../completion\";\nimport type { AgentHook } from \"../../hooks\";\nimport type { MemoryCompactionInfo } from \"../../memory\";\n\nconst internalAgentRunOptions = Symbol(\"internalAgentRunOptions\");\n\nexport type InternalAgentRunOptions = {\n hook?: AgentHook | undefined;\n onFailure?: ((failure: { error: unknown; messages: readonly Message[] }) => void) | undefined;\n onMemoryCompaction?: ((compaction: MemoryCompactionInfo) => void | Promise<void>) | undefined;\n runId?: string | undefined;\n};\n\ntype AgentRunOptionsWithInternal = {\n [internalAgentRunOptions]?: InternalAgentRunOptions;\n};\n\nexport function withInternalAgentRunOptions<T extends object>(\n options: T,\n internal: InternalAgentRunOptions,\n): T {\n return {\n ...options,\n [internalAgentRunOptions]: internal,\n };\n}\n\nexport function getInternalAgentRunOptions(options: object): InternalAgentRunOptions | undefined {\n return (options as AgentRunOptionsWithInternal)[internalAgentRunOptions];\n}\n","import type { CompletionResponse, Message, Usage } from \"../completion\";\nimport type { DeepReadonly, MaybePromise } from \"../internal/type-utils\";\nimport type { MemoryCompactionInfo } from \"../memory\";\nimport type { AgentInteractionRequest } from \"./interactions\";\n\nexport type AgentLifecycleRunEvent = {\n runId: string;\n};\n\nexport type AgentStartEvent = AgentLifecycleRunEvent & {\n input: DeepReadonly<Message>;\n history: DeepReadonly<Message[]>;\n maxTurns: number;\n};\n\nexport type AgentStepFinishEvent<RawResponse = unknown> = AgentLifecycleRunEvent & {\n step: number;\n response: DeepReadonly<CompletionResponse<RawResponse>>;\n usage: DeepReadonly<Usage>;\n};\n\nexport type AgentToolStartEvent = AgentLifecycleRunEvent & {\n step: number;\n toolName: string;\n toolCallId?: string | undefined;\n input: unknown;\n};\n\ntype AgentToolFinishEventBase = AgentToolStartEvent & {\n durationMs: number;\n};\n\nexport type AgentToolFinishEvent =\n | (AgentToolFinishEventBase & { success: true; output: unknown })\n | (AgentToolFinishEventBase & { success: false; error: unknown });\n\ntype AgentFinishEventBase = AgentLifecycleRunEvent & {\n text: string;\n usage: DeepReadonly<Usage>;\n messages: DeepReadonly<Message[]>;\n memoryCompaction?: DeepReadonly<MemoryCompactionInfo> | undefined;\n};\n\nexport type AgentFinishEvent<Output = string> =\n | (AgentFinishEventBase & {\n status: \"completed\";\n output: DeepReadonly<Output>;\n })\n | (AgentFinishEventBase & {\n status: \"blocked\";\n stage: \"input\" | \"output\";\n })\n | (AgentFinishEventBase & {\n status: \"suspended\";\n interaction: DeepReadonly<AgentInteractionRequest>;\n });\n\nexport type AgentErrorEvent = AgentLifecycleRunEvent & {\n error: unknown;\n usage: DeepReadonly<Usage>;\n messages: DeepReadonly<Message[]>;\n};\n\nexport type AgentLifecycle<Output = string, RawResponse = unknown> = {\n onStart?(event: AgentStartEvent): MaybePromise<void>;\n onStepFinish?(event: AgentStepFinishEvent<RawResponse>): MaybePromise<void>;\n onToolStart?(event: AgentToolStartEvent): MaybePromise<void>;\n onToolFinish?(event: AgentToolFinishEvent): MaybePromise<void>;\n onFinish?(event: AgentFinishEvent<Output>): MaybePromise<void>;\n onError?(event: AgentErrorEvent): MaybePromise<void>;\n};\n\nexport function composeAgentLifecycle<Output = string, RawResponse = unknown>(\n first: AgentLifecycle<Output, RawResponse> | undefined,\n second: AgentLifecycle<Output, RawResponse> | undefined,\n): AgentLifecycle<Output, RawResponse> | undefined {\n if (first === undefined) return second;\n if (second === undefined) return first;\n\n return {\n async onStart(event) {\n await first.onStart?.(lifecycleSnapshot(event));\n await second.onStart?.(lifecycleSnapshot(event));\n },\n async onStepFinish(event) {\n await first.onStepFinish?.(lifecycleSnapshot(event));\n await second.onStepFinish?.(lifecycleSnapshot(event));\n },\n async onToolStart(event) {\n await first.onToolStart?.(lifecycleSnapshot(event));\n await second.onToolStart?.(lifecycleSnapshot(event));\n },\n async onToolFinish(event) {\n await first.onToolFinish?.(lifecycleSnapshot(event));\n await second.onToolFinish?.(lifecycleSnapshot(event));\n },\n async onFinish(event) {\n await first.onFinish?.(lifecycleSnapshot(event));\n await second.onFinish?.(lifecycleSnapshot(event));\n },\n async onError(event) {\n await first.onError?.(lifecycleSnapshot(event));\n await second.onError?.(lifecycleSnapshot(event));\n },\n };\n}\n\nexport function lifecycleSnapshot<T>(value: T): T {\n try {\n return globalThis.structuredClone(value);\n } catch {\n return cloneLifecycleFallback(value, new WeakMap<object, object>());\n }\n}\n\nfunction cloneLifecycleFallback<T>(value: T, seen: WeakMap<object, object>): T {\n if (typeof value !== \"object\" || value === null) {\n return value;\n }\n const existing = seen.get(value);\n if (existing !== undefined) {\n return existing as T;\n }\n if (Array.isArray(value)) {\n const clone: unknown[] = [];\n seen.set(value, clone);\n clone.push(...value.map((item) => cloneLifecycleFallback(item, seen)));\n return clone as T;\n }\n if (Object.getPrototypeOf(value) !== Object.prototype) {\n return value;\n }\n const clone: Record<string, unknown> = {};\n seen.set(value, clone);\n for (const [key, item] of Object.entries(value)) {\n clone[key] = cloneLifecycleFallback(item, seen);\n }\n return clone as T;\n}\n","import type { JsonObject } from \"../completion\";\nimport { toProviderJsonSchema, type ZodSchema } from \"../schema/zod-schema\";\n\nconst providerOutputSchemas = new WeakMap<object, JsonObject>();\n\nexport function registerAgentProviderOutputSchema(\n agent: object,\n schema: ZodSchema | undefined,\n): void {\n if (schema !== undefined) {\n providerOutputSchemas.set(agent, toProviderJsonSchema(schema));\n }\n}\n\nexport function getAgentProviderOutputSchema(agent: object): JsonObject | undefined {\n return providerOutputSchemas.get(agent);\n}\n","type AsyncQueueWaiter<T> = {\n resolve: (result: IteratorResult<T>) => void;\n reject: (error: unknown) => void;\n};\n\nexport type AsyncQueue<T> = AsyncIterable<T> & {\n enqueue(value: T): void;\n close(): void;\n throw(error: unknown): void;\n};\n\nexport function createAsyncQueue<T>(): AsyncQueue<T> {\n const values: T[] = [];\n const waiters: AsyncQueueWaiter<T>[] = [];\n let closed = false;\n let error: unknown;\n\n function flush(): void {\n while (waiters.length > 0 && values.length > 0) {\n const waiter = waiters.shift();\n const value = values.shift() as T;\n if (waiter !== undefined) {\n waiter.resolve({ value, done: false });\n }\n }\n\n if (values.length > 0 || waiters.length === 0 || !closed) {\n return;\n }\n\n while (waiters.length > 0) {\n const waiter = waiters.shift();\n if (waiter === undefined) {\n continue;\n }\n if (error !== undefined) {\n waiter.reject(error);\n } else {\n waiter.resolve({ value: undefined, done: true });\n }\n }\n }\n\n return {\n enqueue(value: T): void {\n if (closed) {\n return;\n }\n values.push(value);\n flush();\n },\n close(): void {\n closed = true;\n flush();\n },\n throw(thrown: unknown): void {\n closed = true;\n error = thrown;\n flush();\n },\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return {\n next(): Promise<IteratorResult<T>> {\n if (values.length > 0) {\n const value = values.shift() as T;\n return Promise.resolve({ value, done: false });\n }\n if (error !== undefined) {\n return Promise.reject(error);\n }\n if (closed) {\n return Promise.resolve({ value: undefined, done: true });\n }\n return new Promise((resolve, reject) => {\n waiters.push({ resolve, reject });\n });\n },\n };\n },\n };\n}\n","import type { Message as MessageType } from \"../completion/index\";\n\nexport function extractRagText(message: MessageType): string | undefined {\n if (message.role === \"user\") {\n if (typeof message.content === \"string\") {\n return message.content;\n }\n return message.content.flatMap((item) => (item.type === \"text\" ? [item.text] : [])).join(\"\\n\");\n }\n\n if (message.role === \"tool\") {\n return message.content\n .flatMap((item) => {\n if (item.type !== \"tool-result\") {\n return [];\n }\n const output = item.output;\n if (output.type === \"text\" || output.type === \"error-text\") {\n return [output.value];\n }\n if (output.type === \"content\") {\n return output.value.flatMap((part) => (part.type === \"text\" ? [part.text] : []));\n }\n return [];\n })\n .join(\"\\n\");\n }\n\n return undefined;\n}\n","import type { AgentInteractionRequest, AgentQuestionAnswer } from \"../../agent/interactions\";\nimport { parseAgentQuestionPrompts } from \"../../agent/interactions\";\nimport {\n isJsonValue,\n type JsonObject,\n type JsonValue,\n type Message,\n parseMessages,\n type ToolCallPart,\n type ToolResultPart,\n} from \"../../completion\";\nimport type { MemoryScope } from \"../../memory\";\nimport type { PendingToolExecution } from \"./interaction-suspension\";\n\nexport type QueuedSteering = {\n id: string;\n messages: Message[];\n};\n\nexport type AgentContinuationState = {\n kind: \"anvia.agent-continuation\";\n history: Message[];\n messages: Message[];\n pending: PendingToolExecution;\n remainingToolCalls: ToolCallPart[];\n steering: QueuedSteering[];\n memoryScope?: MemoryScope;\n};\n\nexport function serializeContinuationState(state: AgentContinuationState): JsonObject {\n const value = structuredClone(state) as unknown;\n if (!isJsonValue(value) || Array.isArray(value) || value === null) {\n throw new TypeError(\"Agent continuation state must be strict JSON.\");\n }\n return value as JsonObject;\n}\n\nexport function parseContinuationState(\n value: JsonObject,\n interaction: AgentInteractionRequest,\n): AgentContinuationState {\n requireOnlyKeys(value, [\n \"kind\",\n \"history\",\n \"messages\",\n \"pending\",\n \"remainingToolCalls\",\n \"steering\",\n \"memoryScope\",\n ]);\n if (value.kind !== \"anvia.agent-continuation\") {\n throw new TypeError(\"Agent continuation has an unsupported internal state.\");\n }\n const history = parseMessages(value.history);\n const messages = parseMessages(value.messages);\n const pending = parsePending(value.pending);\n const remainingToolCalls = parseToolCalls(value.remainingToolCalls);\n const steering = parseSteering(value.steering);\n if (\n pending.toolCall.toolCallId !== interaction.toolCallId ||\n pending.toolCall.toolName !== interaction.toolName ||\n pending.toolCall.callId !== interaction.callId ||\n pending.internalCallId !== interaction.internalCallId\n ) {\n throw new TypeError(\"Agent continuation interaction does not match its pending tool call.\");\n }\n if (interaction.type === \"tool-approval\" && !jsonEqual(interaction.input, pending.input)) {\n throw new TypeError(\"Agent continuation approval input does not match its pending tool input.\");\n }\n if (interaction.type === \"tool-question\") {\n const questions =\n object(pending.input) && \"questions\" in pending.input\n ? parseAgentQuestionPrompts(pending.input.questions)\n : undefined;\n if (questions === undefined || !jsonEqual(interaction.questions, questions)) {\n throw new TypeError(\n \"Agent continuation questions do not match its pending question tool input.\",\n );\n }\n }\n const state: AgentContinuationState = {\n kind: \"anvia.agent-continuation\",\n history,\n messages,\n pending,\n remainingToolCalls,\n steering,\n };\n if (value.memoryScope !== undefined) {\n state.memoryScope = parseOptionalJsonObject(value.memoryScope, \"memoryScope\") as MemoryScope;\n }\n return state;\n}\n\nexport function questionResult(\n answers: readonly AgentQuestionAnswer[],\n): Extract<ToolResultPart[\"output\"], { type: \"json\" }> {\n return { type: \"json\", value: { answers: structuredClone([...answers]) } };\n}\n\nfunction parsePending(value: unknown): PendingToolExecution {\n if (!object(value)) throw new TypeError(\"Agent continuation pending state is invalid.\");\n const [toolCall] = parseToolCalls([value.toolCall]);\n if (toolCall === undefined) throw new TypeError(\"Agent continuation pending tool is missing.\");\n if (typeof value.effectiveArgs !== \"string\" || typeof value.internalCallId !== \"string\") {\n throw new TypeError(\"Agent continuation pending execution metadata is invalid.\");\n }\n const pending: PendingToolExecution = {\n toolCall,\n effectiveArgs: value.effectiveArgs,\n input: parseJsonValue(value.input, \"pending input\"),\n internalCallId: value.internalCallId,\n };\n if (typeof value.rejectMessage === \"string\") {\n pending.rejectMessage = value.rejectMessage;\n }\n return pending;\n}\n\nfunction parseJsonValue(value: unknown, name: string): JsonValue {\n if (!isJsonValue(value)) {\n throw new TypeError(`Agent continuation ${name} is invalid.`);\n }\n return structuredClone(value);\n}\n\nfunction parseToolCalls(value: unknown): ToolCallPart[] {\n if (!Array.isArray(value)) throw new TypeError(\"Agent continuation tool calls must be an array.\");\n const message = parseMessages([{ role: \"assistant\", content: value }])[0];\n if (message?.role !== \"assistant\" || typeof message.content === \"string\") {\n throw new TypeError(\"Agent continuation tool calls are invalid.\");\n }\n if (!message.content.every((part) => part.type === \"tool-call\")) {\n throw new TypeError(\"Agent continuation contains a non-tool-call part.\");\n }\n return message.content as ToolCallPart[];\n}\n\nfunction parseSteering(value: unknown): QueuedSteering[] {\n if (!Array.isArray(value)) throw new TypeError(\"Agent continuation steering state is invalid.\");\n return value.map((item) => {\n if (!object(item) || typeof item.id !== \"string\") {\n throw new TypeError(\"Agent continuation steering entry is invalid.\");\n }\n return { id: item.id, messages: parseMessages(item.messages) };\n });\n}\n\nfunction parseOptionalJsonObject(value: unknown, name: string): JsonObject | undefined {\n if (value === undefined) return undefined;\n if (!object(value) || !isJsonValue(value)) {\n throw new TypeError(`Agent continuation ${name} is invalid.`);\n }\n return structuredClone(value);\n}\n\nfunction object(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction requireOnlyKeys(value: JsonObject, allowed: readonly string[]): void {\n const allowedKeys = new Set(allowed);\n const unknown = Object.keys(value).find((key) => !allowedKeys.has(key));\n if (unknown !== undefined) {\n throw new TypeError(`Agent continuation state contains unknown key \"${unknown}\".`);\n }\n}\n\nfunction jsonEqual(left: unknown, right: unknown): boolean {\n if (Object.is(left, right)) return true;\n if (Array.isArray(left)) {\n return (\n Array.isArray(right) &&\n left.length === right.length &&\n left.every((value, index) => jsonEqual(value, right[index]))\n );\n }\n if (object(left)) {\n if (!object(right)) return false;\n const keys = Object.keys(left);\n return (\n keys.length === Object.keys(right).length &&\n keys.every((key) => key in right && jsonEqual(left[key], right[key]))\n );\n }\n return false;\n}\n","import type { AgentInteractionRequest, AgentToolApprovalRequest } from \"../../agent/interactions\";\nimport {\n isJsonValue,\n type JsonValue,\n type ToolCallPart,\n type ToolResultPart,\n} from \"../../completion\";\n\nexport type PendingToolExecution = {\n toolCall: ToolCallPart;\n effectiveArgs: string;\n input: JsonValue;\n internalCallId: string;\n rejectMessage?: string;\n};\n\nexport class AgentInteractionSignal extends Error {\n constructor(\n readonly interaction: AgentInteractionRequest,\n readonly rejectMessage?: string,\n ) {\n super(\"Agent execution requires a human interaction.\");\n this.name = \"AgentInteractionSignal\";\n }\n}\n\nexport class ToolExecutionSuspension extends Error {\n completedResults: ToolResultPart[] = [];\n remainingToolCalls: ToolCallPart[] = [];\n\n constructor(\n readonly interaction: AgentInteractionRequest,\n readonly pending: PendingToolExecution,\n ) {\n super(\"Tool execution suspended for human interaction.\");\n this.name = \"ToolExecutionSuspension\";\n }\n}\n\nexport function approvalInteraction(request: {\n id: string;\n toolName: string;\n toolCallId?: string;\n callId?: string;\n internalCallId: string;\n args: unknown;\n reason?: string | undefined;\n rejectMessage?: string | undefined;\n}): AgentToolApprovalRequest {\n if (request.toolCallId === undefined) {\n throw new TypeError(\"Tool approval requires a canonical toolCallId.\");\n }\n if (!isJsonValue(request.args)) {\n throw new TypeError(\"Tool approval input must be strict JSON.\");\n }\n let interaction: AgentToolApprovalRequest = {\n type: \"tool-approval\",\n id: request.id,\n toolName: request.toolName,\n toolCallId: request.toolCallId,\n internalCallId: request.internalCallId,\n input: request.args,\n };\n if (request.callId !== undefined) interaction = { ...interaction, callId: request.callId };\n if (request.reason !== undefined) interaction = { ...interaction, reason: request.reason };\n return interaction;\n}\n","import type { Agent } from \"../../agent/agent\";\nimport type { AgentMemory } from \"../../agent/types\";\nimport { type Message as MessageType, Usage } from \"../../completion/index\";\nimport {\n createMemoryCompactionSummary,\n cumulativeCompactedMessageCount,\n} from \"../../memory/compaction\";\nimport { MemoryCompactionConflictError, MemoryCompactionError } from \"../../memory/errors\";\nimport type {\n MemoryCompactionInfo,\n MemoryCompactionResult,\n MemorySavePolicy,\n MemoryScope,\n MemoryTokenCounter,\n} from \"../../memory/types\";\nimport { throwIfAborted } from \"../abort\";\n\nexport type MemoryPreparation = {\n history: MessageType[];\n usage: ReturnType<typeof Usage.empty>;\n compaction?: MemoryCompactionInfo | undefined;\n originalTokenCount?: number | undefined;\n};\n\ntype MemoryAgent = Pick<Agent, \"memory\">;\n\nexport class AgentRunMemory {\n constructor(\n private readonly agent: MemoryAgent,\n private readonly memoryScope: MemoryScope | undefined,\n private readonly initialHistory: MessageType[],\n ) {}\n\n memoryPolicy(): MemorySavePolicy | undefined {\n return this.memory()?.savePolicy;\n }\n\n pendingTurnMessages(newMessages: MessageType[]): MessageType[] {\n return this.memoryPolicy() === \"turn\" ? [...newMessages] : [];\n }\n\n async prepareHistory(\n runId: string,\n incomingMessages: readonly MessageType[],\n abortSignal?: AbortSignal | undefined,\n ): Promise<MemoryPreparation> {\n const memory = this.memory();\n if (memory === undefined || this.memoryScope === undefined) {\n return {\n history: this.initialHistory,\n usage: Usage.empty(),\n };\n }\n\n const preparation = await this.prepareStoredHistory(\n memory,\n runId,\n incomingMessages,\n abortSignal,\n );\n const memoryHistory = preparation.history;\n const chatHistory = [...memoryHistory, ...this.initialHistory];\n return {\n ...preparation,\n history: chatHistory,\n };\n }\n\n async compact(\n runId: string,\n abortSignal?: AbortSignal | undefined,\n ): Promise<MemoryCompactionResult> {\n const memory = this.memory();\n const scope = this.memoryScope;\n if (memory === undefined || scope === undefined) {\n throw new TypeError(\"Manual memory compaction requires an Agent with configured memory.\");\n }\n if (memory.compaction === undefined || memory.store.compaction === undefined) {\n throw new TypeError(\"Manual memory compaction requires a configured compaction policy.\");\n }\n const preparation = await this.prepareStoredHistory(memory, runId, [], abortSignal, true);\n if (preparation.compaction !== undefined) {\n return { type: \"compacted\", ...preparation.compaction };\n }\n return {\n type: \"skipped\",\n reason: \"nothing_to_compact\",\n originalMessageCount: preparation.history.length,\n originalTokenCount:\n preparation.originalTokenCount ??\n (await countTokens(memory.compaction.tokenCounter, preparation.history)),\n };\n }\n\n async commitAcceptedInput(runId: string, messages: MessageType[]): Promise<void> {\n const memory = this.memory();\n if (\n memory === undefined ||\n this.memoryScope === undefined ||\n memory.savePolicy !== \"message\" ||\n messages.length === 0\n ) {\n return;\n }\n\n await memory.store.append({\n scope: this.memoryScope,\n runId,\n turn: 1,\n messages,\n });\n }\n\n async commitMessages(\n runId: string,\n turn: number,\n messages: MessageType[],\n pendingTurnMessages: MessageType[],\n ): Promise<void> {\n const memory = this.memory();\n if (memory === undefined || this.memoryScope === undefined || messages.length === 0) {\n return;\n }\n if (memory.savePolicy === \"message\") {\n await memory.store.append({\n scope: this.memoryScope,\n runId,\n turn,\n messages,\n });\n } else if (memory.savePolicy === \"turn\") {\n pendingTurnMessages.push(...messages);\n }\n }\n\n async commitCompletedTurn(\n runId: string,\n turn: number,\n pendingTurnMessages: MessageType[],\n ): Promise<void> {\n const memory = this.memory();\n if (\n memory === undefined ||\n this.memoryScope === undefined ||\n memory.savePolicy !== \"turn\" ||\n pendingTurnMessages.length === 0\n ) {\n return;\n }\n await memory.store.append({\n scope: this.memoryScope,\n runId,\n turn,\n messages: [...pendingTurnMessages],\n });\n pendingTurnMessages.length = 0;\n }\n\n async commitCompletedRun(\n runId: string,\n turn: number,\n newMessages: MessageType[],\n pendingTurnMessages: MessageType[],\n ): Promise<void> {\n await this.commitCompletedTurn(runId, turn, pendingTurnMessages);\n const memory = this.memory();\n if (memory === undefined || this.memoryScope === undefined || memory.savePolicy !== \"run\") {\n return;\n }\n await memory.store.append({\n scope: this.memoryScope,\n runId,\n turn,\n messages: [...newMessages],\n });\n }\n\n async recordError(runId: string, error: unknown, newMessages: MessageType[]): Promise<void> {\n const memory = this.memory();\n if (memory === undefined || this.memoryScope === undefined) {\n return;\n }\n await memory.store.recordError?.({\n scope: this.memoryScope,\n runId,\n error,\n messages: [...newMessages],\n });\n }\n\n private memory(): AgentMemory | undefined {\n return this.memoryScope === undefined ? undefined : this.agent.memory;\n }\n\n private async prepareStoredHistory(\n memory: AgentMemory,\n runId: string,\n incomingMessages: readonly MessageType[],\n abortSignal?: AbortSignal | undefined,\n force = false,\n ): Promise<MemoryPreparation> {\n const scope = this.memoryScope;\n if (scope === undefined) {\n return { history: [], usage: Usage.empty() };\n }\n const options = memory.compaction;\n const capability = memory.store.compaction;\n if (options === undefined || capability === undefined) {\n return {\n history: await memory.store.load({ scope }),\n usage: Usage.empty(),\n };\n }\n\n let usage = Usage.empty();\n const maxAttempts = options.conflictRetries === false ? 1 : options.conflictRetries.maxAttempts;\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n throwIfAborted(abortSignal);\n const snapshot = await capability.snapshot({ scope });\n throwIfAborted(abortSignal);\n const selection = await selectCompactionPrefix(\n snapshot.messages,\n incomingMessages,\n options.trigger.afterTokens,\n options.retention.recentTokens,\n options.tokenCounter,\n force,\n );\n throwIfAborted(abortSignal);\n const compactedMessageCount = selection.compactedMessageCount;\n if (compactedMessageCount === 0) {\n return {\n history: snapshot.messages,\n usage,\n originalTokenCount: selection.originalTokenCount,\n };\n }\n\n const prefix = snapshot.messages.slice(0, compactedMessageCount);\n let result: Awaited<ReturnType<typeof options.compactor>>;\n try {\n result = await options.compactor({\n scope,\n messages: prefix,\n abortSignal,\n });\n } catch (error) {\n throw remappedCompactorError(error, usage);\n }\n if (result.usage !== undefined) {\n usage = Usage.add(usage, result.usage);\n }\n if (typeof result?.summary !== \"string\") {\n throw new MemoryCompactionError(\"Memory compactor must return a summary string.\", {\n usage,\n });\n }\n const summaryText = result.summary.trim();\n if (summaryText.length === 0) {\n throw new MemoryCompactionError(\"Memory compactor returned an empty summary.\", {\n usage,\n });\n }\n const summary = createMemoryCompactionSummary(\n summaryText,\n cumulativeCompactedMessageCount(prefix),\n );\n const retained = snapshot.messages.slice(compactedMessageCount);\n let resultTokenCount: number;\n try {\n resultTokenCount = await countTokens(options.tokenCounter, [summary, ...retained]);\n } catch (error) {\n throw remappedCompactorError(error, usage);\n }\n throwIfAborted(abortSignal);\n let replacement: Awaited<ReturnType<typeof capability.replacePrefix>>;\n try {\n replacement = await capability.replacePrefix({\n scope,\n revision: snapshot.revision,\n messageCount: compactedMessageCount,\n replacement: summary,\n runId: `memory-compaction:${runId}:${attempt}`,\n });\n } catch (error) {\n throw new MemoryCompactionError(\"Memory compaction prefix replacement failed.\", {\n cause: error,\n usage,\n });\n }\n if (replacement.status === \"committed\") {\n return {\n history: [summary, ...retained],\n usage,\n compaction: {\n originalMessageCount: snapshot.messages.length,\n compactedMessageCount,\n retainedMessageCount: retained.length,\n originalTokenCount: selection.originalTokenCount,\n compactedTokenCount: selection.compactedTokenCount,\n retainedTokenCount: selection.retainedTokenCount,\n resultTokenCount,\n attempts: attempt,\n usage,\n },\n };\n }\n throwIfAborted(abortSignal);\n }\n\n throw new MemoryCompactionConflictError(maxAttempts, usage);\n }\n}\n\ntype CompactionSelection = {\n compactedMessageCount: number;\n originalTokenCount: number;\n compactedTokenCount: number;\n retainedTokenCount: number;\n};\n\nasync function selectCompactionPrefix(\n messages: readonly MessageType[],\n incomingMessages: readonly MessageType[],\n afterTokens: number,\n recentTokens: number,\n tokenCounter: MemoryTokenCounter,\n force: boolean,\n): Promise<CompactionSelection> {\n const originalTokenCount = await countTokens(tokenCounter, messages);\n const incomingTokenCount =\n incomingMessages.length === 0 ? 0 : await countTokens(tokenCounter, incomingMessages);\n const none = {\n compactedMessageCount: 0,\n originalTokenCount,\n compactedTokenCount: 0,\n retainedTokenCount: originalTokenCount,\n };\n if (!force && originalTokenCount + incomingTokenCount <= afterTokens) {\n return none;\n }\n const userMessageIndexes = messages.flatMap((message, index) =>\n message.role === \"user\" ? [index] : [],\n );\n if (userMessageIndexes.length <= 1) {\n return none;\n }\n\n // Retain complete user-led turns. The newest turn is always kept even when it alone exceeds the\n // retention budget. Find the earliest newer turn whose tail fits with logarithmic counter calls.\n const tailTokenCounts = new Map<number, number>();\n const countTail = async (messageIndex: number): Promise<number> => {\n const cached = tailTokenCounts.get(messageIndex);\n if (cached !== undefined) return cached;\n const count = await countTokens(tokenCounter, messages.slice(messageIndex));\n tailTokenCounts.set(messageIndex, count);\n return count;\n };\n let lower = 0;\n let upper = userMessageIndexes.length - 1;\n let retainedBoundary = upper;\n while (lower <= upper) {\n const middle = Math.floor((lower + upper) / 2);\n const candidate = userMessageIndexes[middle] ?? 0;\n if ((await countTail(candidate)) <= recentTokens) {\n retainedBoundary = middle;\n upper = middle - 1;\n } else {\n lower = middle + 1;\n }\n }\n const compactedMessageCount = userMessageIndexes[retainedBoundary] ?? 0;\n if (compactedMessageCount === 0) {\n return none;\n }\n const compactedTokenCount = await countTokens(\n tokenCounter,\n messages.slice(0, compactedMessageCount),\n );\n const retainedTokenCount =\n tailTokenCounts.get(compactedMessageCount) ??\n (await countTokens(tokenCounter, messages.slice(compactedMessageCount)));\n return {\n compactedMessageCount,\n originalTokenCount,\n compactedTokenCount,\n retainedTokenCount,\n };\n}\n\nasync function countTokens(\n tokenCounter: MemoryTokenCounter,\n messages: readonly MessageType[],\n): Promise<number> {\n let count: number;\n try {\n count = await tokenCounter(messages);\n } catch (error) {\n throw new MemoryCompactionError(\"Memory token counter failed.\", { cause: error });\n }\n if (!Number.isSafeInteger(count) || count < 0) {\n throw new MemoryCompactionError(\"Memory token counter must return a nonnegative safe integer.\");\n }\n return count;\n}\n\nfunction remappedCompactorError(error: unknown, usage: ReturnType<typeof Usage.empty>): Error {\n if (error instanceof MemoryCompactionError) {\n const mergedUsage =\n error.usage === undefined\n ? usage\n : isEmptyUsage(usage)\n ? error.usage\n : Usage.add(usage, error.usage);\n if (mergedUsage === error.usage || (error.usage === undefined && isEmptyUsage(usage))) {\n return error;\n }\n return new MemoryCompactionError(error.message, {\n cause: error,\n usage: mergedUsage,\n });\n }\n return new MemoryCompactionError(\"Memory compactor failed.\", {\n cause: error,\n usage,\n });\n}\n\nfunction isEmptyUsage(usage: ReturnType<typeof Usage.empty>): boolean {\n return (\n usage.inputTokens === 0 &&\n usage.outputTokens === 0 &&\n usage.totalTokens === 0 &&\n usage.cachedInputTokens === 0 &&\n usage.cacheCreationInputTokens === 0\n );\n}\n","import { lifecycleSnapshot } from \"../../agent/lifecycle\";\nimport type { MemoryScope } from \"../../memory/types\";\n\nexport function normalizeMemoryScope(scope: MemoryScope, owner = \"Agent\"): MemoryScope {\n if (typeof scope !== \"object\" || scope === null || Array.isArray(scope)) {\n throw new TypeError(`${owner} session must be an object.`);\n }\n if (typeof scope.sessionId !== \"string\" || scope.sessionId.trim().length === 0) {\n throw new TypeError(`${owner} sessionId must be a non-empty string.`);\n }\n const normalized: MemoryScope = {\n sessionId: scope.sessionId.trim(),\n };\n if (scope.userId !== undefined) normalized.userId = scope.userId;\n if (scope.metadata !== undefined) normalized.metadata = scope.metadata;\n return lifecycleSnapshot(normalized);\n}\n","import type { Agent } from \"../../agent/agent\";\nimport { getAgentToolState } from \"../../agent/tool-state\";\nimport { isVectorContext } from \"../../agent/vector-context\";\nimport type { CompletionModel, Document, ToolDefinition } from \"../../completion/index\";\nimport { retrieveDocuments } from \"../../vector-store\";\n\nexport async function fetchContextDocuments<Output, M extends CompletionModel, ContextDocument>(\n agent: Agent<Output, M, ContextDocument>,\n ragText: string | undefined,\n abortSignal?: AbortSignal | undefined,\n): Promise<Document[]> {\n const documents: Document[] = [];\n for (const input of agent.context) {\n if (!isVectorContext(input)) {\n documents.push(input);\n continue;\n }\n if (ragText === undefined || ragText.length === 0) continue;\n const request = {\n query: ragText,\n topK: input.topK,\n minScore: input.minScore,\n filter: input.filter,\n retries: input.retries,\n abortSignal,\n };\n const results =\n \"models\" in input && input.models !== undefined\n ? await retrieveDocuments({\n ...request,\n store: input.store,\n models: input.models,\n fusion: input.fusion,\n })\n : await retrieveDocuments({ ...request, store: input.store, model: input.model });\n for (const result of results) {\n const formatted = input.format?.(result);\n if (formatted !== undefined) {\n documents.push(formatted);\n continue;\n }\n const metadata = formatMetadata(result.metadata);\n const document: Document = {\n id: result.id,\n text:\n typeof result.document === \"string\"\n ? result.document\n : JSON.stringify(result.document, null, 2),\n };\n if (metadata !== undefined) document.additionalProps = metadata;\n documents.push(document);\n }\n }\n return documents;\n}\n\nexport async function fetchToolDefinitions<Output, M extends CompletionModel, ContextDocument>(\n agent: Agent<Output, M, ContextDocument>,\n ragText: string | undefined,\n abortSignal?: AbortSignal | undefined,\n): Promise<ToolDefinition[]> {\n const state = getAgentToolState(agent);\n const staticDefinitions = await Promise.all(\n state.staticTools.map((tool) => tool.definition(ragText ?? \"\")),\n );\n if (ragText === undefined || ragText.length === 0 || state.toolIndexes.length === 0) {\n return staticDefinitions;\n }\n\n const definitions = [...staticDefinitions];\n const names = new Set(staticDefinitions.map((definition) => definition.name));\n for (const index of state.toolIndexes) {\n const results = await index.search({ query: ragText, abortSignal });\n for (const result of results) {\n const toolName = result.document.toolName;\n if (names.has(toolName)) continue;\n const tool = index.tools.find((candidate) => candidate.name === toolName);\n if (tool === undefined) continue;\n names.add(toolName);\n definitions.push(await tool.definition(ragText));\n }\n }\n return definitions;\n}\n\nfunction formatMetadata(\n metadata: Record<string, unknown> | undefined,\n): Record<string, string> | undefined {\n if (metadata === undefined) return undefined;\n return Object.fromEntries(Object.entries(metadata).map(([key, value]) => [key, String(value)]));\n}\n","export function assertNonnegativeSafeInteger(value: number, name: string): number {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new TypeError(`${name} must be a nonnegative safe integer.`);\n }\n return value;\n}\n\nexport function assertPositiveSafeInteger(value: number, name: string): number {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new TypeError(`${name} must be a positive safe integer.`);\n }\n return value;\n}\n","import type {\n AgentDeltaEvent,\n AgentStreamEvent,\n AgentToolCallDeltaEvent,\n} from \"../../agent/run-types\";\nimport type { CompletionModelStreamEvent } from \"../../completion/types\";\n\nexport function addTurn(turn: number, event: AgentDeltaEvent): AgentStreamEvent {\n if (event.type === \"text_delta\") {\n return { type: \"text_delta\", turn, delta: event.delta };\n }\n if (event.type === \"reasoning_delta\") {\n const mapped: AgentStreamEvent = { type: \"reasoning_delta\", turn, delta: event.delta };\n if (event.id !== undefined) mapped.id = event.id;\n if (event.contentType !== undefined) mapped.contentType = event.contentType;\n if (event.signature !== undefined) mapped.signature = event.signature;\n return mapped;\n }\n if (event.type === \"source\") {\n return { type: \"source\", turn, source: event.source };\n }\n if (event.type === \"provider_tool_call\") {\n return { type: \"provider_tool_call\", turn, toolCall: event.toolCall };\n }\n return { type: \"tool_call\", turn, toolCall: event.toolCall };\n}\n\nexport function addTurnToToolCallDelta(\n turn: number,\n event: Extract<CompletionModelStreamEvent, { type: \"tool_call_delta\" }>,\n): AgentToolCallDeltaEvent {\n const mapped: AgentToolCallDeltaEvent = {\n type: \"tool_call_delta\",\n turn,\n id: event.id,\n };\n if (event.callId !== undefined) mapped.callId = event.callId;\n if (event.name !== undefined) mapped.name = event.name;\n if (event.argumentsDelta !== undefined) mapped.argumentsDelta = event.argumentsDelta;\n if (event.argumentsMode !== undefined) mapped.argumentsMode = event.argumentsMode;\n if (event.signature !== undefined) mapped.signature = event.signature;\n return mapped;\n}\n\nexport function isGenerationDeltaEvent(type: string): boolean {\n return (\n type === \"text_delta\" ||\n type === \"reasoning_delta\" ||\n type === \"tool_call_delta\" ||\n type === \"tool_call\" ||\n type === \"source\" ||\n type === \"provider_tool_call\"\n );\n}\n","import type { AgentStructuredOutputFormat } from \"../../agent/errors\";\n\nconst JSON_FENCE_START = \"```json\\n\";\nconst JSON_FENCE_CRLF_START = \"```json\\r\\n\";\nconst UNLABELED_FENCE_START = \"```\\n\";\nconst UNLABELED_FENCE_CRLF_START = \"```\\r\\n\";\nconst FENCE_END = \"\\n```\";\n\nexport const STRUCTURED_OUTPUT_RETRY_PROMPT =\n \"Your previous response was invalid structured output. Return only raw JSON that matches the supplied JSON schema. Do not use Markdown fences or include commentary.\";\n\nexport const STRUCTURED_OUTPUT_TRUNCATED_RETRY_PROMPT =\n \"Your previous response exceeded the provider output limit. Return substantially shorter raw JSON that matches the supplied JSON schema. Do not use Markdown fences or include commentary.\";\n\nconst STRUCTURED_OUTPUT_REPAIR_PREVIEW_MAX_LENGTH = 8_192;\nconst STRUCTURED_OUTPUT_REPAIR_PREVIEW_MARKER = \"\\n...[output omitted]...\\n\";\n\nexport type StructuredOutputRepairPreview = Readonly<{\n text: string;\n includedOutputLength: number;\n}>;\n\nexport function structuredOutputRepairPreview(text: string): StructuredOutputRepairPreview {\n if (text.length <= STRUCTURED_OUTPUT_REPAIR_PREVIEW_MAX_LENGTH) {\n return { text, includedOutputLength: text.length };\n }\n const availableLength =\n STRUCTURED_OUTPUT_REPAIR_PREVIEW_MAX_LENGTH - STRUCTURED_OUTPUT_REPAIR_PREVIEW_MARKER.length;\n const headLength = Math.ceil(availableLength / 2);\n const tailLength = availableLength - headLength;\n return {\n text: `${text.slice(0, headLength)}${STRUCTURED_OUTPUT_REPAIR_PREVIEW_MARKER}${text.slice(-tailLength)}`,\n includedOutputLength: headLength + tailLength,\n };\n}\n\nexport type NormalizedStructuredOutput = Readonly<{\n text: string;\n format: AgentStructuredOutputFormat;\n}>;\n\nexport function normalizeStructuredOutput(text: string): NormalizedStructuredOutput {\n const trimmed = text.trim();\n const opening = fenceOpening(trimmed);\n if (opening === undefined || !trimmed.endsWith(FENCE_END)) {\n return { text: trimmed, format: \"raw\" };\n }\n\n const closingStart = trimmed.length - 3;\n const precedingNewline = closingStart - 1;\n const contentEnd =\n trimmed[precedingNewline - 1] === \"\\r\" ? precedingNewline - 1 : precedingNewline;\n return {\n text: trimmed.slice(opening.length, contentEnd).trim(),\n format: opening.format,\n };\n}\n\nfunction fenceOpening(\n text: string,\n): Readonly<{ length: number; format: Exclude<AgentStructuredOutputFormat, \"raw\"> }> | undefined {\n if (text.startsWith(JSON_FENCE_START)) {\n return { length: JSON_FENCE_START.length, format: \"json-fence\" };\n }\n if (text.startsWith(JSON_FENCE_CRLF_START)) {\n return { length: JSON_FENCE_CRLF_START.length, format: \"json-fence\" };\n }\n if (text.startsWith(UNLABELED_FENCE_START)) {\n return { length: UNLABELED_FENCE_START.length, format: \"unlabeled-fence\" };\n }\n if (text.startsWith(UNLABELED_FENCE_CRLF_START)) {\n return { length: UNLABELED_FENCE_CRLF_START.length, format: \"unlabeled-fence\" };\n }\n return undefined;\n}\n","import type { Agent } from \"../../agent/agent\";\nimport { parseAgentQuestionPrompts } from \"../../agent/interactions\";\nimport { type AgentLifecycle, lifecycleSnapshot } from \"../../agent/lifecycle\";\nimport type { AgentChildStreamEvent } from \"../../agent/run-types\";\nimport type {\n JsonObject,\n ToolCallPart,\n ToolDefinition,\n ToolResultContentPart,\n ToolResultOutput,\n ToolResultPart,\n} from \"../../completion\";\nimport { isJsonValue, Usage } from \"../../completion\";\nimport { assertCompletionResponseIntegrity } from \"../../completion/provider-output-error\";\nimport type { AgentHook, ToolApprovalRequestOptions, ToolHookArgs } from \"../../hooks\";\nimport { runControl, toolCallControl } from \"../../hooks\";\nimport { isMcpTool } from \"../../mcp\";\nimport type { ActiveAgentRunObservers, ActiveToolObservers } from \"../../observability/group\";\nimport type {\n AgentToolEndArgs,\n AgentToolErrorArgs,\n AgentToolStartArgs,\n AgentToolStreamEventArgs,\n AgentToolSuspendedArgs,\n} from \"../../observability/types\";\nimport type {\n AnyTool,\n NormalizedToolOutput,\n ToolApprovalContext,\n ToolApprovalRunContext,\n ToolCallContext,\n ToolCallStreamEvent,\n ToolRequiresApproval,\n} from \"../../tool\";\nimport {\n normalizeToolResultOutput,\n parseToolArgs,\n ToolOutput,\n toolResultContentToText,\n} from \"../../tool\";\nimport type {\n AgentMiddleware,\n ToolOutputMiddlewareArgs,\n ToolOutputMiddlewareResult,\n} from \"../../tool/middleware\";\nimport { isQuestionTool } from \"../../tool/question-tool\";\nimport { isSkillTool } from \"../../tool/skill-tool-marker\";\nimport { throwIfAborted } from \"../abort\";\nimport { mapWithConcurrency } from \"../concurrency\";\nimport type { ToolApprovalRequest } from \"./approval-request\";\nimport { assertToolApprovalRequirement, toolMayRequireApproval } from \"./approval-requirement\";\nimport {\n AgentInteractionSignal,\n type PendingToolExecution,\n ToolExecutionSuspension,\n} from \"./interaction-suspension\";\nimport {\n type PreparedToolCall,\n prepareToolCall as prepareRegisteredToolCall,\n prepareToolCallFromInput,\n} from \"./prepared-tool-call\";\n\nexport type ToolResultEventPayload = {\n type: \"tool_result\";\n toolName: string;\n toolCallId: string;\n callId?: string;\n internalCallId: string;\n args: string;\n output: ToolResultOutput;\n result: string;\n structuredResult?: readonly ToolResultContentPart[] | undefined;\n};\n\nexport type AgentToolEventPayload = {\n type: \"agent_tool_event\";\n toolName: string;\n toolCallId?: string;\n internalCallId: string;\n agentId: string;\n agentName?: string;\n event: AgentChildStreamEvent<unknown, unknown>;\n};\n\nexport type ToolExecutionEventPayload = ToolResultEventPayload | AgentToolEventPayload;\n\nexport type ToolExecutionObservation = {\n turn: number;\n runObservers: ActiveAgentRunObservers;\n toolDefinitions?: ToolDefinition[];\n};\n\nexport type ToolExecutionRunContext = {\n runId: string;\n sessionId?: string | undefined;\n metadata?: JsonObject | undefined;\n};\n\nexport type ToolApprovalDecision =\n | { approved: true; reason?: string }\n | { approved: false; reason?: string };\n\nexport type ToolApprovalHandler = (request: ToolApprovalRequest) => Promise<ToolApprovalDecision>;\n\ntype ToolExecutionAgent = Pick<Agent, \"id\" | \"getTool\" | \"callTool\" | \"middlewares\">;\ntype ToolExecutionLifecycle = Pick<AgentLifecycle, \"onToolStart\" | \"onToolFinish\">;\n\nexport class ToolCallExecutor {\n constructor(\n private readonly agent: ToolExecutionAgent,\n private readonly activeHook: AgentHook | undefined,\n private readonly approvalHandler: ToolApprovalHandler,\n private readonly lifecycle: ToolExecutionLifecycle | undefined,\n private readonly runContext: ToolExecutionRunContext,\n private readonly concurrency: number,\n private readonly requestMiddlewares: readonly AgentMiddleware[],\n private readonly abortSignal: AbortSignal,\n private readonly cancel: (reason: string) => Error,\n ) {}\n\n async execute(\n toolCalls: readonly ToolCallPart[],\n onResult?: (result: ToolResultEventPayload) => void,\n onStreamEvent?: (event: AgentToolEventPayload) => void,\n observation?: ToolExecutionObservation,\n ): Promise<ToolResultPart[]> {\n assertCompletionResponseIntegrity({\n response: {\n choice: [...toolCalls],\n usage: Usage.empty(),\n rawResponse: undefined,\n },\n });\n\n const executeOne = async (toolCall: ToolCallPart): Promise<ToolResultPart> => {\n throwIfAborted(this.abortSignal);\n const args = JSON.stringify(toolCall.input);\n const internalCallId = globalThis.crypto.randomUUID();\n const hookArgs: ToolHookArgs = {\n toolName: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n internalCallId,\n args,\n };\n if (toolCall.callId !== undefined) {\n hookArgs.callId = toolCall.callId;\n }\n const tool = this.agent.getTool(toolCall.toolName);\n const toolDefinition = observation?.toolDefinitions?.find(\n (definition) => definition.name === toolCall.toolName,\n );\n const toolMetadata = toolTraceMetadata(tool);\n\n let toolStartArgs: AgentToolStartArgs = {\n turn: observation?.turn ?? 0,\n toolCall,\n toolName: toolCall.toolName,\n internalCallId,\n args,\n };\n if (toolCall.callId !== undefined) {\n toolStartArgs = { ...toolStartArgs, toolCallId: toolCall.callId };\n }\n if (toolDefinition !== undefined) toolStartArgs = { ...toolStartArgs, toolDefinition };\n if (toolMetadata !== undefined) toolStartArgs = { ...toolStartArgs, toolMetadata };\n const toolObservers = await observation?.runObservers.startTool(toolStartArgs);\n const toolObservation = new ToolObserverScope(toolObservers);\n\n let output: NormalizedToolOutput | undefined;\n let skipped = false;\n let toolExecutionFailed = false;\n let effectiveArgs = args;\n\n try {\n const callAction = await this.activeHook?.onToolCall?.({\n ...hookArgs,\n tool: toolCallControl,\n });\n if (callAction?.type === \"terminate\") {\n throw this.cancel(callAction.reason);\n }\n if (callAction?.type === \"skip\") {\n output = { type: \"text\", value: callAction.reason };\n skipped = true;\n } else {\n try {\n effectiveArgs = await this.runToolInputMiddlewares({\n ...hookArgs,\n turn: observation?.turn ?? 0,\n originalArgs: args,\n });\n hookArgs.args = effectiveArgs;\n\n let prepared: PreparedToolCall | undefined;\n try {\n prepared = this.prepareToolCall(tool, toolCall.toolName, effectiveArgs);\n } catch (error) {\n const outcome = await this.handleToolError(\n toolCall,\n hookArgs,\n effectiveArgs,\n error,\n toolObservation,\n observation,\n );\n output = outcome.output;\n toolExecutionFailed = outcome.failed;\n }\n if (prepared !== undefined && isQuestionTool(tool)) {\n try {\n const questions = parseAgentQuestionPrompts(\n (prepared.input as { questions?: unknown }).questions,\n );\n const interaction = {\n type: \"tool-question\",\n id: globalThis.crypto.randomUUID(),\n toolName: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n internalCallId,\n questions,\n } as const;\n if (toolCall.callId !== undefined) {\n Object.assign(interaction, { callId: toolCall.callId });\n }\n throw new AgentInteractionSignal(interaction);\n } catch (error) {\n if (error instanceof AgentInteractionSignal) throw error;\n const outcome = await this.handleToolError(\n toolCall,\n hookArgs,\n effectiveArgs,\n error,\n toolObservation,\n observation,\n );\n output = outcome.output;\n toolExecutionFailed = outcome.failed;\n prepared = undefined;\n }\n }\n if (prepared !== undefined) {\n const approvalContext = createApprovalContext(\n prepared.input,\n hookArgs,\n this.agent,\n this.runContext,\n );\n const approvalDecision =\n callAction?.type === \"approval_request\"\n ? await this.requestApproval(approvalContext, callAction, observation)\n : ((await this.evaluateToolApproval(tool, approvalContext, observation)) ?? {\n approved: true as const,\n });\n if (!approvalDecision.approved) {\n output = { type: \"execution-denied\", reason: approvalDecision.result };\n skipped = true;\n } else {\n const step = observation?.turn ?? 0;\n const lifecycleEvent = {\n runId: this.runContext.runId,\n step,\n toolName: toolCall.toolName,\n input: lifecycleSnapshot(prepared.input),\n };\n if (toolCall.callId !== undefined) {\n Object.assign(lifecycleEvent, { toolCallId: toolCall.callId });\n }\n await this.lifecycle?.onToolStart?.(lifecycleEvent);\n const startedAt = Date.now();\n const outcome = await this.runApprovedToolCall(\n prepared,\n toolCall,\n hookArgs,\n effectiveArgs,\n toolObservation,\n observation,\n onStreamEvent,\n );\n output = outcome.output;\n toolExecutionFailed = outcome.failed;\n const durationMs = Date.now() - startedAt;\n await this.lifecycle?.onToolFinish?.(\n outcome.failed\n ? {\n ...lifecycleEvent,\n durationMs,\n success: false,\n error: lifecycleSnapshot(outcome.error),\n }\n : {\n ...lifecycleEvent,\n durationMs,\n success: true,\n output: lifecycleSnapshot(output),\n },\n );\n }\n }\n } catch (error) {\n if (error instanceof AgentInteractionSignal) {\n await toolObservation.suspend({\n ...toolStartArgs,\n interaction: error.interaction,\n });\n throw error;\n }\n await toolObservation.error(\n toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error),\n );\n throw error;\n }\n }\n\n if (output === undefined) {\n throw new Error(`Tool \"${toolCall.toolName}\" did not produce an execution result.`);\n }\n let result = toolOutputToText(output);\n let structuredResult = toolOutputToStructuredResult(output);\n if (!isSkillTool(tool)) {\n const middlewareReplacement = await this.runToolResultMiddlewares({\n ...hookArgs,\n args: effectiveArgs,\n result,\n originalResult: result,\n structuredResult,\n originalStructuredResult: structuredResult,\n turn: observation?.turn ?? 0,\n });\n if (middlewareReplacement !== undefined) {\n output = middlewareReplacement;\n result = toolOutputToText(middlewareReplacement);\n structuredResult = toolOutputToStructuredResult(middlewareReplacement);\n }\n }\n\n const resultAction = await this.activeHook?.onToolResult?.({\n ...hookArgs,\n args: effectiveArgs,\n result,\n structuredResult,\n run: runControl,\n });\n if (!toolExecutionFailed) {\n await toolObservation.end({\n turn: observation?.turn ?? 0,\n toolCall,\n toolName: toolCall.toolName,\n internalCallId,\n args: effectiveArgs,\n result,\n structuredResult,\n skipped,\n toolCallId: toolCall.callId,\n });\n }\n if (resultAction?.type === \"terminate\") {\n throw this.cancel(resultAction.reason);\n }\n\n const resultPayload: ToolResultEventPayload = {\n type: \"tool_result\",\n toolName: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n internalCallId,\n args: effectiveArgs,\n output,\n result,\n structuredResult,\n };\n if (toolCall.callId !== undefined) resultPayload.callId = toolCall.callId;\n onResult?.(resultPayload);\n let resultPart: ToolResultPart = {\n type: \"tool-result\" as const,\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n output,\n };\n if (toolCall.callId !== undefined) {\n resultPart = { ...resultPart, callId: toolCall.callId };\n }\n return resultPart;\n } catch (error) {\n if (error instanceof AgentInteractionSignal) {\n const pending: PendingToolExecution = {\n toolCall,\n effectiveArgs,\n input:\n error.interaction.type === \"tool-approval\"\n ? error.interaction.input\n : parseToolArgs(effectiveArgs),\n internalCallId,\n };\n if (error.rejectMessage !== undefined) pending.rejectMessage = error.rejectMessage;\n throw new ToolExecutionSuspension(error.interaction, pending);\n }\n await toolObservation.error(\n toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error),\n );\n throw error;\n }\n };\n\n if (this.concurrency === 1) {\n const results: ToolResultPart[] = [];\n for (const toolCall of toolCalls) {\n try {\n results.push(await executeOne(toolCall));\n } catch (error) {\n if (error instanceof ToolExecutionSuspension) {\n error.completedResults = [...results];\n error.remainingToolCalls = toolCalls.slice(results.length + 1);\n }\n throw error;\n }\n }\n return results;\n }\n return mapWithConcurrency(toolCalls, this.concurrency, executeOne);\n }\n\n async executeResumed(\n pending: PendingToolExecution,\n onResult?: (result: ToolResultEventPayload) => void,\n onStreamEvent?: (event: AgentToolEventPayload) => void,\n observation?: ToolExecutionObservation,\n ): Promise<ToolResultPart> {\n throwIfAborted(this.abortSignal);\n const { toolCall, internalCallId, effectiveArgs } = pending;\n const tool = this.agent.getTool(toolCall.toolName);\n if (tool === undefined) {\n throw new Error(\n `Cannot resume tool interaction because tool \"${toolCall.toolName}\" is no longer registered.`,\n );\n }\n if (isQuestionTool(tool)) {\n throw new TypeError(\"Question interactions are resolved from their submitted answers.\");\n }\n\n const hookArgs: ToolHookArgs = {\n toolName: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n internalCallId,\n args: effectiveArgs,\n };\n if (toolCall.callId !== undefined) hookArgs.callId = toolCall.callId;\n const toolDefinition = observation?.toolDefinitions?.find(\n (definition) => definition.name === toolCall.toolName,\n );\n const toolMetadata = toolTraceMetadata(tool);\n let toolStartArgs: AgentToolStartArgs = {\n turn: observation?.turn ?? 0,\n toolCall,\n toolName: toolCall.toolName,\n internalCallId,\n args: effectiveArgs,\n };\n if (toolCall.callId !== undefined) {\n toolStartArgs = { ...toolStartArgs, toolCallId: toolCall.callId };\n }\n if (toolDefinition !== undefined) toolStartArgs = { ...toolStartArgs, toolDefinition };\n if (toolMetadata !== undefined) toolStartArgs = { ...toolStartArgs, toolMetadata };\n const observers = await observation?.runObservers.startTool(toolStartArgs);\n const toolObservation = new ToolObserverScope(observers);\n let output: NormalizedToolOutput;\n let failed = false;\n\n try {\n const prepared = prepareToolCallFromInput(tool, pending.input);\n const step = observation?.turn ?? 0;\n const lifecycleEvent = {\n runId: this.runContext.runId,\n step,\n toolName: toolCall.toolName,\n input: lifecycleSnapshot(prepared.input),\n };\n if (toolCall.callId !== undefined) {\n Object.assign(lifecycleEvent, { toolCallId: toolCall.callId });\n }\n await this.lifecycle?.onToolStart?.(lifecycleEvent);\n const startedAt = Date.now();\n const outcome = await this.runApprovedToolCall(\n prepared,\n toolCall,\n hookArgs,\n effectiveArgs,\n toolObservation,\n observation,\n onStreamEvent,\n );\n output = outcome.output;\n failed = outcome.failed;\n const durationMs = Date.now() - startedAt;\n await this.lifecycle?.onToolFinish?.(\n outcome.failed\n ? {\n ...lifecycleEvent,\n durationMs,\n success: false,\n error: lifecycleSnapshot(outcome.error),\n }\n : {\n ...lifecycleEvent,\n durationMs,\n success: true,\n output: lifecycleSnapshot(output),\n },\n );\n\n let result = toolOutputToText(output);\n let structuredResult = toolOutputToStructuredResult(output);\n if (!isSkillTool(tool)) {\n const replacement = await this.runToolResultMiddlewares({\n ...hookArgs,\n args: effectiveArgs,\n result,\n originalResult: result,\n structuredResult,\n originalStructuredResult: structuredResult,\n turn: step,\n });\n if (replacement !== undefined) {\n output = replacement;\n result = toolOutputToText(replacement);\n structuredResult = toolOutputToStructuredResult(replacement);\n }\n }\n const resultAction = await this.activeHook?.onToolResult?.({\n ...hookArgs,\n result,\n structuredResult,\n run: runControl,\n });\n if (!failed) {\n await toolObservation.end({\n turn: step,\n toolCall,\n toolName: toolCall.toolName,\n internalCallId,\n args: effectiveArgs,\n result,\n structuredResult,\n skipped: false,\n toolCallId: toolCall.callId,\n });\n }\n if (resultAction?.type === \"terminate\") {\n throw this.cancel(resultAction.reason);\n }\n const resultPayload: ToolResultEventPayload = {\n type: \"tool_result\",\n toolName: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n internalCallId,\n args: effectiveArgs,\n output,\n result,\n structuredResult,\n };\n if (toolCall.callId !== undefined) resultPayload.callId = toolCall.callId;\n onResult?.(resultPayload);\n let resultPart: ToolResultPart = {\n type: \"tool-result\",\n toolName: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n output,\n };\n if (toolCall.callId !== undefined) resultPart = { ...resultPart, callId: toolCall.callId };\n return resultPart;\n } catch (error) {\n await toolObservation.error(\n toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error),\n );\n throw error;\n }\n }\n\n async resolveResumed(\n pending: PendingToolExecution,\n initialOutput: NormalizedToolOutput,\n onResult?: (result: ToolResultEventPayload) => void,\n observation?: ToolExecutionObservation,\n ): Promise<ToolResultPart> {\n throwIfAborted(this.abortSignal);\n const { toolCall, internalCallId, effectiveArgs } = pending;\n const tool = this.agent.getTool(toolCall.toolName);\n if (tool === undefined) {\n throw new Error(\n `Cannot resume tool interaction because tool \"${toolCall.toolName}\" is no longer registered.`,\n );\n }\n\n const hookArgs: ToolHookArgs = {\n toolName: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n internalCallId,\n args: effectiveArgs,\n };\n if (toolCall.callId !== undefined) hookArgs.callId = toolCall.callId;\n const toolDefinition = observation?.toolDefinitions?.find(\n (definition) => definition.name === toolCall.toolName,\n );\n const toolMetadata = toolTraceMetadata(tool);\n let toolStartArgs: AgentToolStartArgs = {\n turn: observation?.turn ?? 0,\n toolCall,\n toolName: toolCall.toolName,\n internalCallId,\n args: effectiveArgs,\n };\n if (toolCall.callId !== undefined) {\n toolStartArgs = { ...toolStartArgs, toolCallId: toolCall.callId };\n }\n if (toolDefinition !== undefined) toolStartArgs = { ...toolStartArgs, toolDefinition };\n if (toolMetadata !== undefined) toolStartArgs = { ...toolStartArgs, toolMetadata };\n const observers = await observation?.runObservers.startTool(toolStartArgs);\n const toolObservation = new ToolObserverScope(observers);\n\n try {\n let output = initialOutput;\n let result = toolOutputToText(output);\n let structuredResult = toolOutputToStructuredResult(output);\n if (!isSkillTool(tool)) {\n const replacement = await this.runToolResultMiddlewares({\n ...hookArgs,\n args: effectiveArgs,\n result,\n originalResult: result,\n structuredResult,\n originalStructuredResult: structuredResult,\n turn: observation?.turn ?? 0,\n });\n if (replacement !== undefined) {\n output = replacement;\n result = toolOutputToText(replacement);\n structuredResult = toolOutputToStructuredResult(replacement);\n }\n }\n const resultAction = await this.activeHook?.onToolResult?.({\n ...hookArgs,\n result,\n structuredResult,\n run: runControl,\n });\n await toolObservation.end({\n turn: observation?.turn ?? 0,\n toolCall,\n toolName: toolCall.toolName,\n internalCallId,\n args: effectiveArgs,\n result,\n structuredResult,\n skipped: true,\n toolCallId: toolCall.callId,\n });\n if (resultAction?.type === \"terminate\") {\n throw this.cancel(resultAction.reason);\n }\n const resultPayload: ToolResultEventPayload = {\n type: \"tool_result\",\n toolName: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n internalCallId,\n args: effectiveArgs,\n output,\n result,\n structuredResult,\n };\n if (toolCall.callId !== undefined) resultPayload.callId = toolCall.callId;\n onResult?.(resultPayload);\n let resultPart: ToolResultPart = {\n type: \"tool-result\",\n toolName: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n output,\n };\n if (toolCall.callId !== undefined) resultPart = { ...resultPart, callId: toolCall.callId };\n return resultPart;\n } catch (error) {\n await toolObservation.error(\n toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error),\n );\n throw error;\n }\n }\n\n private async runApprovedToolCall(\n prepared: PreparedToolCall,\n toolCall: ToolCallPart,\n hookArgs: ToolHookArgs,\n effectiveArgs: string,\n toolObservation: ToolObserverScope,\n observation: ToolExecutionObservation | undefined,\n onStreamEvent?: (event: AgentToolEventPayload) => void,\n ): Promise<\n | { output: NormalizedToolOutput; failed: false }\n | { output: NormalizedToolOutput; failed: true; error: unknown }\n > {\n try {\n const toolContext: ToolCallContext = {\n abortSignal: this.abortSignal,\n emitStreamEvent: async (event) => {\n let streamEventArgs: AgentToolStreamEventArgs = {\n turn: observation?.turn ?? 0,\n toolCall,\n toolName: toolCall.toolName,\n internalCallId: hookArgs.internalCallId,\n args: effectiveArgs,\n event,\n };\n if (toolCall.callId !== undefined) {\n streamEventArgs = { ...streamEventArgs, toolCallId: toolCall.callId };\n }\n await toolObservation.streamEvent(streamEventArgs);\n const payload = agentToolEventPayload(toolCall, hookArgs.internalCallId, event);\n if (payload !== undefined) {\n onStreamEvent?.(payload);\n }\n },\n };\n return {\n output: await prepared.call(toolContext),\n failed: false,\n };\n } catch (error) {\n return this.handleToolError(\n toolCall,\n hookArgs,\n effectiveArgs,\n error,\n toolObservation,\n observation,\n );\n }\n }\n\n private prepareToolCall(\n tool: AnyTool | undefined,\n toolName: string,\n args: string,\n ): PreparedToolCall {\n if (tool !== undefined) {\n return prepareRegisteredToolCall(tool, args);\n }\n const input = parseToolArgs(args);\n return {\n input,\n call: (context) => this.agent.callTool(toolName, args, context),\n };\n }\n\n private async handleToolError(\n toolCall: ToolCallPart,\n hookArgs: ToolHookArgs,\n args: string,\n error: unknown,\n toolObservation: ToolObserverScope,\n observation: ToolExecutionObservation | undefined,\n ): Promise<{ output: NormalizedToolOutput; failed: true; error: unknown }> {\n const errorAction = await this.activeHook?.onToolError?.({\n ...hookArgs,\n args,\n error,\n run: runControl,\n });\n await toolObservation.error(\n toolErrorArgs(observation?.turn ?? 0, toolCall, hookArgs.internalCallId, args, error),\n );\n if (errorAction?.type === \"terminate\") {\n throw this.cancel(errorAction.reason);\n }\n return {\n output: {\n type: \"error-text\",\n value: error instanceof Error ? error.toString() : String(error),\n },\n failed: true,\n error,\n };\n }\n\n private async runToolResultMiddlewares(\n args: ToolOutputMiddlewareArgs,\n ): Promise<NormalizedToolOutput | undefined> {\n let result = args.result;\n let structuredResult = args.structuredResult;\n let replaced = false;\n for (const middleware of this.activeMiddlewares()) {\n const outputReplacement = await middleware.onToolOutput?.({\n ...args,\n result,\n structuredResult,\n });\n if (outputReplacement !== undefined) {\n const normalized = normalizeToolOutputMiddlewareResult(outputReplacement);\n if (normalized.result !== undefined) {\n result = normalized.result;\n structuredResult = undefined;\n }\n if (normalized.structuredResult !== undefined) {\n structuredResult = normalized.structuredResult;\n result = toolResultContentToText(normalized.structuredResult);\n }\n replaced = true;\n }\n }\n return replaced\n ? structuredResult === undefined\n ? { type: \"text\", value: result }\n : { type: \"content\", value: structuredResult }\n : undefined;\n }\n\n private async runToolInputMiddlewares(\n args: ToolHookArgs & { turn: number; originalArgs: string },\n ): Promise<string> {\n let current = args.args;\n for (const middleware of this.activeMiddlewares()) {\n const replacement = await middleware.onToolInput?.({\n ...args,\n args: current,\n });\n if (replacement?.args !== undefined) {\n if (typeof replacement.args === \"string\") {\n current = replacement.args;\n } else {\n if (!isJsonValue(replacement.args)) {\n throw new TypeError(\"Tool input middleware args must be a strict JSON value.\");\n }\n current = JSON.stringify(replacement.args);\n }\n }\n }\n return current;\n }\n\n private activeMiddlewares(): AgentMiddleware[] {\n return [...this.agent.middlewares, ...this.requestMiddlewares];\n }\n\n private async evaluateToolApproval(\n tool: AnyTool | undefined,\n context: ToolApprovalContext,\n observation: ToolExecutionObservation | undefined,\n ): Promise<{ approved: true } | { approved: false; result: string } | undefined> {\n const requirement = tool?.requiresApproval as ToolRequiresApproval<unknown> | undefined;\n if (requirement === undefined) return undefined;\n const resolved =\n typeof requirement === \"function\" ? await requirement(context.args, context) : requirement;\n assertToolApprovalRequirement(resolved, { allowFunction: false });\n if (resolved === false) return { approved: true };\n const reason = resolved === true ? undefined : resolved.reason;\n return this.requestApproval(context, reason === undefined ? {} : { reason }, observation);\n }\n\n private async requestApproval(\n context: ToolApprovalContext,\n options: ToolApprovalRequestOptions,\n observation: ToolExecutionObservation | undefined,\n ): Promise<{ approved: true } | { approved: false; result: string }> {\n const request: ToolApprovalRequest = {\n ...context,\n id: globalThis.crypto.randomUUID(),\n };\n if (options.reason !== undefined) {\n request.reason = options.reason;\n }\n if (options.rejectMessage !== undefined) {\n request.rejectMessage = options.rejectMessage;\n }\n await observation?.runObservers.event({\n name: \"tool.approval_requested\",\n attributes: approvalEventAttributes(request, observation.turn),\n });\n let decision: ToolApprovalDecision;\n try {\n decision = await this.approvalHandler(request);\n } catch (error) {\n if (error instanceof AgentInteractionSignal) {\n throw error;\n }\n await observation?.runObservers.event({\n name: \"tool.approval_failed\",\n level: \"ERROR\",\n attributes: {\n ...approvalEventAttributes(request, observation.turn),\n errorName: error instanceof Error ? error.name : typeof error,\n },\n });\n throw error;\n }\n const attributes: JsonObject = {\n ...approvalEventAttributes(request, observation?.turn ?? 0),\n approved: decision.approved,\n };\n if (decision.reason !== undefined) attributes.decisionReason = decision.reason;\n await observation?.runObservers.event({\n name: \"tool.approval_resolved\",\n attributes,\n });\n if (decision.approved) {\n return { approved: true };\n }\n return {\n approved: false,\n result: decision.reason ?? request.rejectMessage ?? \"Tool approval was rejected.\",\n };\n }\n}\n\nfunction createApprovalContext(\n input: unknown,\n hookArgs: ToolHookArgs,\n agent: Pick<Agent, \"id\">,\n run: ToolExecutionRunContext,\n): ToolApprovalContext {\n const approvalRun: ToolApprovalRunContext = {\n agentId: agent.id,\n runId: run.runId,\n };\n if (run.sessionId !== undefined) {\n approvalRun.sessionId = run.sessionId;\n }\n if (run.metadata !== undefined) {\n approvalRun.metadata = run.metadata;\n }\n const context: ToolApprovalContext = {\n toolName: hookArgs.toolName,\n args: lifecycleSnapshot(input),\n rawArgs: hookArgs.args,\n toolCallId: hookArgs.toolCallId,\n internalCallId: hookArgs.internalCallId,\n run: approvalRun,\n };\n if (hookArgs.callId !== undefined) {\n context.callId = hookArgs.callId;\n }\n return context;\n}\n\nfunction approvalEventAttributes(request: ToolApprovalRequest, turn: number): JsonObject {\n const attributes: JsonObject = {\n turn,\n approvalId: request.id,\n toolName: request.toolName,\n internalCallId: request.internalCallId,\n };\n if (request.toolCallId !== undefined) attributes.toolCallId = request.toolCallId;\n if (request.reason !== undefined) attributes.reason = request.reason;\n return attributes;\n}\n\nfunction normalizeToolOutputMiddlewareResult(result: ToolOutputMiddlewareResult): {\n result?: string | undefined;\n structuredResult?: readonly ToolResultContentPart[] | undefined;\n} {\n if (typeof result === \"string\") {\n return { result };\n }\n if (typeof result !== \"object\" || result === null) {\n throw new TypeError(\"Tool output middleware must return text or structured content.\");\n }\n const prototype = Object.getPrototypeOf(result);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new TypeError(\"Tool output middleware must return text or structured content.\");\n }\n const keys = Reflect.ownKeys(result);\n const hasResult = keys.includes(\"result\");\n const hasStructuredResult = keys.includes(\"structuredResult\");\n if (\n hasResult === hasStructuredResult ||\n keys.some((key) => key !== \"result\" && key !== \"structuredResult\")\n ) {\n throw new TypeError(\n \"Tool output middleware must return exactly one of result or structuredResult.\",\n );\n }\n if (hasResult) {\n const descriptor = Object.getOwnPropertyDescriptor(result, \"result\");\n if (\n descriptor === undefined ||\n !(\"value\" in descriptor) ||\n typeof descriptor.value !== \"string\"\n ) {\n throw new TypeError(\"Tool output middleware result must be a string.\");\n }\n return { result: descriptor.value };\n }\n const descriptor = Object.getOwnPropertyDescriptor(result, \"structuredResult\");\n if (descriptor === undefined || !(\"value\" in descriptor)) {\n throw new TypeError(\"Tool output middleware structuredResult must be valid tool content.\");\n }\n const normalized = normalizeToolResultOutput(ToolOutput.content(descriptor.value as never));\n if (normalized.type !== \"content\") {\n throw new TypeError(\"Tool output middleware structuredResult must be valid tool content.\");\n }\n return { structuredResult: normalized.value };\n}\n\nfunction toolTraceMetadata(tool: AnyTool | undefined): JsonObject | undefined {\n if (tool === undefined) {\n return undefined;\n }\n const result: JsonObject = {\n approvalRequired: toolMayRequireApproval(tool.requiresApproval),\n };\n if (isMcpTool(tool)) {\n result.mcpServerName = tool.mcp.serverName;\n result.mcpRemoteName = tool.mcp.remoteName;\n }\n return result;\n}\n\nfunction toolErrorArgs(\n turn: number,\n toolCall: ToolCallPart,\n internalCallId: string,\n args: string,\n error: unknown,\n): AgentToolErrorArgs {\n let observerArgs: AgentToolErrorArgs = {\n turn,\n toolCall,\n toolName: toolCall.toolName,\n internalCallId,\n args,\n error,\n };\n if (toolCall.callId !== undefined) {\n observerArgs = { ...observerArgs, toolCallId: toolCall.callId };\n }\n return observerArgs;\n}\n\nclass ToolObserverScope {\n private terminal = false;\n\n constructor(private readonly observers: ActiveToolObservers | undefined) {}\n\n streamEvent(args: AgentToolStreamEventArgs): Promise<void> | undefined {\n return this.observers?.streamEvent(args);\n }\n\n async end(args: AgentToolEndArgs): Promise<void> {\n if (this.terminal) return;\n this.terminal = true;\n await this.observers?.end(args);\n }\n\n async suspend(args: AgentToolSuspendedArgs): Promise<void> {\n if (this.terminal) return;\n this.terminal = true;\n await this.observers?.suspend(args);\n }\n\n async error(args: AgentToolErrorArgs): Promise<void> {\n if (this.terminal) return;\n this.terminal = true;\n await this.observers?.error(args);\n }\n}\n\nfunction toolOutputToText(output: NormalizedToolOutput): string {\n switch (output.type) {\n case \"text\":\n case \"error-text\":\n return output.value;\n case \"json\":\n case \"error-json\":\n return JSON.stringify(output.value);\n case \"content\":\n return toolResultContentToText(output.value);\n case \"execution-denied\":\n return output.reason ?? \"Tool execution was denied.\";\n }\n}\n\nfunction toolOutputToStructuredResult(\n output: NormalizedToolOutput,\n): readonly ToolResultContentPart[] | undefined {\n return output.type === \"content\" ? output.value : undefined;\n}\n\nfunction agentToolEventPayload(\n toolCall: ToolCallPart,\n internalCallId: string,\n event: ToolCallStreamEvent,\n): AgentToolEventPayload | undefined {\n if (typeof event.agentId !== \"string\" || event.agentId.length === 0) {\n return undefined;\n }\n const payload: AgentToolEventPayload = {\n type: \"agent_tool_event\" as const,\n toolName: toolCall.toolName,\n internalCallId,\n agentId: event.agentId,\n event: event.event as AgentChildStreamEvent<unknown, unknown>,\n };\n if (toolCall.callId !== undefined) {\n payload.toolCallId = toolCall.callId;\n }\n if (event.agentName !== undefined) {\n payload.agentName = event.agentName;\n }\n return payload;\n}\n","import type { Agent } from \"../../agent/agent\";\nimport {\n AgentRunCancelledError,\n AgentStreamClosedError,\n AgentStructuredOutputError,\n MaxTurnsError,\n} from \"../../agent/errors\";\nimport {\n type AgentInteractionResponse,\n assertAgentInteractionResponse,\n parseAgentContinuation,\n parseAgentInteractionResponse,\n} from \"../../agent/interactions\";\nimport {\n type AgentFinishEvent,\n type AgentLifecycle,\n composeAgentLifecycle,\n lifecycleSnapshot,\n} from \"../../agent/lifecycle\";\nimport { getAgentProviderOutputSchema } from \"../../agent/output-schema\";\nimport type {\n AgentBlockedOutcome,\n AgentInput,\n AgentInteractionOutcome,\n AgentOutcome,\n AgentResponse,\n AgentRunOptions,\n AgentRunSettings,\n AgentSteerInput,\n AgentSteerReceipt,\n AgentStreamEvent,\n} from \"../../agent/run-types\";\nimport { getAgentToolState } from \"../../agent/tool-state\";\nimport { isStreamingCompletionModel } from \"../../completion/generate-completion\";\nimport {\n assertCompletionRequestSupported,\n type CompletionFinishReason,\n type CompletionModel,\n type CompletionRequest,\n type CompletionResponse,\n type CompletionSource,\n getAssistantGenerationMetadata,\n isJsonValue,\n type JsonObject,\n type Message as MessageType,\n type ProviderToolCall,\n parseMessage,\n parseMessages,\n type ToolCallPart,\n type ToolInteractionResponsePart,\n type ToolResultPart,\n textFromAssistantContent,\n Usage,\n} from \"../../completion/index\";\nimport { assertCompletionResponseIntegrity } from \"../../completion/provider-output-error\";\nimport { CompletionStreamAccumulator } from \"../../completion/stream-accumulator\";\nimport {\n appendGuardrailPolicies,\n type GuardrailDecisionRecord,\n type GuardrailPolicy,\n type GuardrailRunContext,\n hasEnforcedOutputGuardrails,\n runInputGuardrails,\n runOutputGuardrails,\n} from \"../../guardrails\";\nimport type { AgentHook } from \"../../hooks\";\nimport { runControl } from \"../../hooks\";\nimport { MemoryCompactionError } from \"../../memory/errors\";\nimport type { MemoryCompactionInfo, MemoryScope } from \"../../memory/types\";\nimport type { ModelCallOptions } from \"../../model-call-options\";\nimport {\n type ActiveAgentRunObservers,\n type ActiveGenerationObservers,\n startAgentRunObservers,\n} from \"../../observability/group\";\nimport type {\n AgentGenerationEndArgs,\n AgentGenerationModelInfo,\n AgentGenerationStartArgs,\n AgentRunEndArgs,\n AgentTraceOptions,\n} from \"../../observability/types\";\nimport {\n completionProviderOutputErrorUsage,\n type ResolvedRetryOptions,\n resolveRetryOptions,\n retryDelayMs,\n retryErrorAttributes,\n retryOptionsForFailure,\n waitForRetry,\n} from \"../../retry\";\nimport type { AgentMiddleware } from \"../../tool/middleware\";\nimport { isQuestionTool } from \"../../tool/question-tool\";\nimport { abortError, throwIfAborted } from \"../abort\";\nimport { createAsyncQueue } from \"../async-queue\";\nimport { createCompletionRequest } from \"../completion-request\";\nimport { assertJsonObject } from \"../json-object\";\nimport { extractRagText } from \"../rag-text\";\nimport { toolMayRequireApproval } from \"./approval-requirement\";\nimport {\n type AgentContinuationState,\n parseContinuationState,\n type QueuedSteering,\n questionResult,\n serializeContinuationState,\n} from \"./continuation-state\";\nimport {\n AgentInteractionSignal,\n approvalInteraction,\n ToolExecutionSuspension,\n} from \"./interaction-suspension\";\nimport { AgentRunMemory, type MemoryPreparation } from \"./memory\";\nimport { normalizeMemoryScope } from \"./memory-scope\";\nimport { fetchContextDocuments, fetchToolDefinitions } from \"./retrieval\";\nimport { getInternalAgentRunOptions, type InternalAgentRunOptions } from \"./run-options\";\nimport { assertNonnegativeSafeInteger, assertPositiveSafeInteger } from \"./run-validation\";\nimport { addTurn, addTurnToToolCallDelta, isGenerationDeltaEvent } from \"./stream-events\";\nimport {\n normalizeStructuredOutput,\n STRUCTURED_OUTPUT_RETRY_PROMPT,\n STRUCTURED_OUTPUT_TRUNCATED_RETRY_PROMPT,\n structuredOutputRepairPreview,\n} from \"./structured-output\";\nimport {\n type AgentToolEventPayload,\n ToolCallExecutor,\n type ToolExecutionEventPayload,\n type ToolExecutionObservation,\n type ToolResultEventPayload,\n} from \"./tool-execution\";\n\ntype AgentRunCreateOptions<Output, RawResponse> = AgentRunSettings<Output, RawResponse> & {\n memoryScope?: MemoryScope | undefined;\n continuationState?: AgentContinuationState | undefined;\n interactionResponse?: AgentInteractionResponse | undefined;\n sourceRunId?: string | undefined;\n interactionId?: string | undefined;\n};\n\ntype StreamingCompletionState = {\n response: CompletionResponse | undefined;\n firstDeltaMs: number | undefined;\n emittedToolCallIds: Set<string>;\n providerErrorUsage: Usage;\n};\n\ntype StructuredOutputRetryRequest = Readonly<{\n request: CompletionRequest;\n previousResponse: \"omitted\" | \"preview\";\n includedOutputLength: number;\n}>;\n\nasync function settleFailureCleanup(\n operations: Array<() => void | Promise<void> | undefined>,\n): Promise<void> {\n for (const operation of operations) {\n try {\n await operation();\n } catch {\n // Cleanup failures must not replace the primary run failure.\n }\n }\n}\n\ntype RawResponseOf<Model> =\n Model extends CompletionModel<infer RawResponse> ? RawResponse : unknown;\n\ntype AgentTerminalResult<Output> = AgentOutcome<Output>;\n\nexport class AgentRun<Output = string, M extends CompletionModel = CompletionModel> {\n private chatHistory: MessageType[];\n private maxTurnCount: number;\n private activeHook: AgentHook | undefined;\n private readonly activeLifecycle: AgentLifecycle<Output, unknown> | undefined;\n private guardrailPolicies: GuardrailPolicy[];\n private guardrailDecisions: GuardrailDecisionRecord[] = [];\n private readonly concurrency: number;\n private traceOptions: AgentTraceOptions | undefined;\n private completionRetryOptions: ResolvedRetryOptions | undefined;\n private readonly requestMiddlewares: AgentMiddleware[];\n private readonly steeringMessages: QueuedSteering[] = [];\n private runState: \"idle\" | \"running\" | \"closing\" | \"completed\" | \"errored\" | \"cancelled\" = \"idle\";\n private readonly memoryRecorder: AgentRunMemory;\n private readonly memoryScope: MemoryScope | undefined;\n private readonly onInternalFailure: InternalAgentRunOptions[\"onFailure\"];\n private readonly onInternalMemoryCompaction: InternalAgentRunOptions[\"onMemoryCompaction\"];\n private memoryCompaction: MemoryCompactionInfo | undefined;\n private readonly requestedRunId: string | undefined;\n private readonly continuationState: AgentContinuationState | undefined;\n private readonly interactionResponse: AgentInteractionResponse | undefined;\n private readonly resumedFrom: { runId: string; interactionId: string } | undefined;\n private currentMessages: MessageType[] = [];\n private cancellationError: AgentRunCancelledError | undefined;\n private activeGeneration: { turn: number; observers: ActiveGenerationObservers } | undefined;\n private validatedStructuredOutput: { text: string; output: Output } | undefined;\n private failedCompletionUsage = Usage.empty();\n private readonly abortController = new AbortController();\n private removeExternalAbortListener: (() => void) | undefined;\n\n private constructor(\n private readonly agent: Agent<Output, M>,\n private promptMessage: MessageType,\n initialHistory: MessageType[] = [],\n options: AgentRunCreateOptions<Output, RawResponseOf<M>> = {},\n ) {\n this.chatHistory = initialHistory;\n this.maxTurnCount = assertNonnegativeSafeInteger(\n options.maxTurns ?? agent.defaultMaxTurns ?? 0,\n \"maxTurns\",\n );\n const internalOptions = getInternalAgentRunOptions(options);\n this.activeHook = internalOptions?.hook;\n this.onInternalFailure = internalOptions?.onFailure;\n this.onInternalMemoryCompaction = internalOptions?.onMemoryCompaction;\n this.requestedRunId = normalizeRequestedRunId(internalOptions?.runId);\n this.activeLifecycle = composeAgentLifecycle(agent.lifecycle, options.lifecycle) as\n | AgentLifecycle<Output, unknown>\n | undefined;\n this.guardrailPolicies =\n options.guardrails === undefined\n ? [...agent.guardrails]\n : appendGuardrailPolicies([...agent.guardrails], options.guardrails);\n const configuredConcurrency = assertPositiveSafeInteger(\n options.toolConcurrency ?? 1,\n \"toolConcurrency\",\n );\n this.concurrency =\n this.activeHook !== undefined ||\n agent.tools.some(\n (tool) => toolMayRequireApproval(tool.requiresApproval) || isQuestionTool(tool),\n )\n ? 1\n : configuredConcurrency;\n this.traceOptions = options.trace;\n const retrySetting = options.retries === undefined ? agent.retries : options.retries;\n this.completionRetryOptions =\n retrySetting === undefined || retrySetting === false\n ? undefined\n : resolveRetryOptions(retrySetting);\n this.requestMiddlewares = [...(options.middlewares ?? [])];\n this.memoryScope = options.memoryScope;\n this.memoryRecorder = new AgentRunMemory(agent, options.memoryScope, initialHistory);\n this.continuationState = options.continuationState;\n this.interactionResponse = options.interactionResponse;\n if (options.continuationState !== undefined) {\n this.steeringMessages.push(\n ...options.continuationState.steering.map((entry) => ({\n id: entry.id,\n messages: [...entry.messages],\n })),\n );\n }\n this.resumedFrom =\n options.sourceRunId === undefined || options.interactionId === undefined\n ? undefined\n : { runId: options.sourceRunId, interactionId: options.interactionId };\n this.linkExternalAbortSignal(options.abortSignal);\n }\n\n static fromAgent<Output, M extends CompletionModel>(\n agent: Agent<Output, M>,\n options: AgentRunOptions<Output, RawResponseOf<M>>,\n ): AgentRun<Output, M> {\n const normalized = normalizeAgentInput(agent.id, options);\n if (normalized.scope !== undefined && agent.memory === undefined) {\n throw new TypeError(`Agent \"${agent.id}\" cannot use a session without a memory store.`);\n }\n return new AgentRun(agent, normalized.prompt, normalized.history, {\n ...options,\n memoryScope: normalized.scope,\n continuationState: normalized.continuationState,\n interactionResponse: normalized.interactionResponse,\n sourceRunId: normalized.sourceRunId,\n interactionId: normalized.interactionId,\n });\n }\n\n steer(input: AgentSteerInput): AgentSteerReceipt {\n if (this.isTerminal() || this.cancellationError !== undefined) {\n throw new AgentStreamClosedError();\n }\n const receipt: AgentSteerReceipt = Object.freeze({\n id: globalThis.crypto.randomUUID(),\n status: \"queued\",\n });\n this.steeringMessages.push({ id: receipt.id, messages: normalizeSteeringInput(input) });\n return receipt;\n }\n\n cancel(reason: string): AgentRunCancelledError | undefined {\n if (this.isTerminal() || this.cancellationError !== undefined) {\n return this.cancellationError;\n }\n const messages =\n this.currentMessages.length === 0 ? [this.promptMessage] : [...this.currentMessages];\n const error = new AgentRunCancelledError([...this.chatHistory, ...messages], reason);\n this.setCancellationError(error);\n return error;\n }\n\n private setCancellationError(error: AgentRunCancelledError): void {\n this.cancellationError = error;\n if (!this.abortController.signal.aborted) this.abortController.abort(error);\n }\n\n async generate(): Promise<AgentTerminalResult<Output>> {\n this.startRun();\n const runId = this.requestedRunId ?? globalThis.crypto.randomUUID();\n let usage = Usage.empty();\n let currentTurns = 0;\n let lastPrompt = this.promptMessage;\n let newMessages: MessageType[] = [this.promptMessage];\n let runObservers: ActiveAgentRunObservers | undefined;\n let pendingTurnMessages: MessageType[] = [];\n\n try {\n this.throwIfCancelled();\n const memoryPreparation =\n this.continuationState === undefined\n ? await this.memoryRecorder.prepareHistory(\n runId,\n newMessages,\n this.abortController.signal,\n )\n : undefined;\n if (memoryPreparation !== undefined) {\n this.chatHistory = memoryPreparation.history;\n usage = Usage.add(usage, memoryPreparation.usage);\n this.memoryCompaction = memoryPreparation.compaction;\n await this.notifyInternalMemoryCompaction(memoryPreparation.compaction);\n }\n runObservers = await this.startRunObservers(runId);\n if (memoryPreparation !== undefined) {\n await this.recordMemoryCompaction(memoryPreparation, runObservers);\n }\n this.throwIfCancelled();\n await this.activeLifecycle?.onStart?.({\n runId,\n input: lifecycleSnapshot(this.promptMessage),\n history: lifecycleSnapshot(this.chatHistory),\n maxTurns: this.maxTurnCount,\n });\n if (this.continuationState === undefined) {\n const inputResult = await runInputGuardrails(this.guardrailPolicies, {\n prompt: this.promptMessage,\n history: this.chatHistory,\n inputText: textFromMessage(this.promptMessage),\n run: this.guardrailRunContext(runId),\n });\n for (const decision of inputResult.decisions) {\n await this.recordGuardrailDecision(decision, runObservers);\n }\n this.promptMessage = inputResult.prompt;\n if (inputResult.blocked) {\n const text = inputResult.message ?? \"The request was blocked by a guardrail.\";\n const result: AgentBlockedOutcome = {\n type: \"blocked\",\n stage: \"input\",\n ...blockedOutcomeDetails(\n this.guardrailDecisions,\n \"The request was blocked by a guardrail.\",\n ),\n runId,\n text,\n usage,\n messages: [this.promptMessage, { role: \"assistant\", content: text }],\n trace: runObservers.trace,\n guardrails: [...this.guardrailDecisions],\n ...this.memoryCompactionResult(),\n };\n if (this.resumedFrom !== undefined) result.resumedFrom = this.resumedFrom;\n this.runState = \"closing\";\n await this.runLifecycleFinish(result);\n await runObservers.end(observerRunEnd(result));\n this.runState = \"completed\";\n this.disposeAbortLink();\n return result;\n }\n }\n\n newMessages = [this.promptMessage];\n await this.memoryRecorder.commitAcceptedInput(runId, newMessages);\n pendingTurnMessages = this.memoryRecorder.pendingTurnMessages(newMessages);\n await this.runRunStartHook(newMessages);\n if (this.continuationState !== undefined) {\n const interactionAttributes: JsonObject = {};\n if (this.resumedFrom?.runId !== undefined) {\n interactionAttributes.sourceRunId = this.resumedFrom.runId;\n }\n if (this.resumedFrom?.interactionId !== undefined) {\n interactionAttributes.interactionId = this.resumedFrom.interactionId;\n }\n if (this.interactionResponse?.type !== undefined) {\n interactionAttributes.interactionType = this.interactionResponse.type;\n }\n await runObservers.event({\n name: \"agent.interaction_response\",\n attributes: interactionAttributes,\n });\n try {\n const toolResults = await this.resolveContinuationTools(\n runId,\n newMessages,\n undefined,\n undefined,\n {\n turn: 1,\n runObservers,\n },\n );\n const toolMessage: MessageType = { role: \"tool\", content: toolResults };\n newMessages.push(toolMessage);\n await this.memoryRecorder.commitMessages(runId, 1, [toolMessage], pendingTurnMessages);\n await this.drainSteeringMessages(runId, 1, newMessages, pendingTurnMessages);\n await this.memoryRecorder.commitCompletedTurn(runId, 1, pendingTurnMessages);\n } catch (error) {\n if (error instanceof ToolExecutionSuspension) {\n return this.finishSuspension({\n runId,\n turn: 1,\n usage,\n newMessages,\n pendingTurnMessages,\n runObservers,\n suspension: error,\n uncommittedMessages: [],\n });\n }\n throw error;\n }\n }\n while (currentTurns <= this.maxTurnCount + 1) {\n const prompt = newMessages.at(-1);\n if (prompt === undefined) {\n throw new Error(\"AgentRun requires at least one message\");\n }\n\n lastPrompt = prompt;\n currentTurns += 1;\n\n const historyForRequest = [...this.chatHistory, ...newMessages.slice(0, -1)];\n await this.runTurnStartHook(currentTurns, prompt, historyForRequest, newMessages);\n await this.runCompletionCallHook(prompt, historyForRequest, newMessages);\n\n const request = await this.createTurnRequest(prompt, historyForRequest, currentTurns);\n\n let response: CompletionResponse;\n try {\n response = await this.runCompletion(request, currentTurns, runObservers);\n } catch (error) {\n await settleFailureCleanup([\n () => this.runCompletionErrorHook(prompt, error, newMessages),\n ]);\n throw error;\n }\n response = await this.runCompletionResponseMiddlewares(request, response, currentTurns);\n try {\n assertCompletionResponseIntegrity({ response });\n } catch (error) {\n const providerOutputUsage = completionProviderOutputErrorUsage(error);\n if (providerOutputUsage !== undefined) usage = Usage.add(usage, providerOutputUsage);\n throw error;\n }\n usage = Usage.add(usage, response.usage);\n this.updateRunProgress(newMessages);\n await this.runCompletionResponseHook(prompt, response, newMessages);\n await this.runTurnEndHook(currentTurns, response, newMessages);\n await this.activeLifecycle?.onStepFinish?.({\n runId,\n step: currentTurns,\n response: lifecycleSnapshot(response),\n usage: lifecycleSnapshot(usage),\n });\n\n const toolCalls = response.choice.filter(\n (item): item is ToolCallPart => item.type === \"tool-call\",\n );\n const assistantMessage = this.generatedAssistantMessage(response, request);\n newMessages.push(assistantMessage);\n if (toolCalls.length === 0) {\n if (this.steeringMessages.length > 0) {\n await this.memoryRecorder.commitMessages(\n runId,\n currentTurns,\n [assistantMessage],\n pendingTurnMessages,\n );\n }\n const appliedSteering = await this.drainSteeringMessages(\n runId,\n currentTurns,\n newMessages,\n pendingTurnMessages,\n { closeWhenEmpty: true },\n );\n if (appliedSteering.length > 0) {\n for (const receipt of appliedSteering) {\n await runObservers.event({\n name: \"agent.steering_applied\",\n attributes: { id: receipt.id, turn: currentTurns },\n });\n }\n await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);\n continue;\n }\n\n const guardedOutput = await this.runOutputGuardrailsForResponse(\n runId,\n usage,\n response,\n newMessages,\n runObservers,\n );\n response = guardedOutput.response;\n const finalAssistantMessage = this.generatedAssistantMessage(response, request);\n newMessages[newMessages.length - 1] = finalAssistantMessage;\n await this.memoryRecorder.commitMessages(\n runId,\n currentTurns,\n [finalAssistantMessage],\n pendingTurnMessages,\n );\n const result = this.createTerminalResult(\n runId,\n guardedOutput.text,\n guardedOutput.blocked,\n usage,\n newMessages,\n runObservers,\n );\n if (result.type === \"response\") {\n await this.runRunEndHook(result, newMessages);\n }\n await this.memoryRecorder.commitCompletedRun(\n runId,\n currentTurns,\n newMessages,\n pendingTurnMessages,\n );\n await this.runLifecycleFinish(result);\n await runObservers.end(observerRunEnd(result));\n this.runState = \"completed\";\n this.disposeAbortLink();\n return result;\n }\n\n this.updateRunProgress(newMessages);\n let toolResults: ToolResultPart[];\n try {\n toolResults = await this.executeToolCalls(\n runId,\n toolCalls,\n newMessages,\n undefined,\n undefined,\n {\n turn: currentTurns,\n runObservers,\n toolDefinitions: request.tools,\n },\n );\n } catch (error) {\n if (error instanceof ToolExecutionSuspension) {\n return this.finishSuspension({\n runId,\n turn: currentTurns,\n usage,\n newMessages,\n pendingTurnMessages,\n runObservers,\n suspension: error,\n uncommittedMessages: [assistantMessage],\n });\n }\n throw error;\n }\n const toolMessage: MessageType = { role: \"tool\", content: toolResults };\n newMessages.push(toolMessage);\n await this.memoryRecorder.commitMessages(\n runId,\n currentTurns,\n [assistantMessage, toolMessage],\n pendingTurnMessages,\n );\n await this.drainSteeringMessages(runId, currentTurns, newMessages, pendingTurnMessages);\n await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);\n }\n\n throw new MaxTurnsError(this.maxTurnCount, [...this.chatHistory, ...newMessages], lastPrompt);\n } catch (error) {\n if (error instanceof MemoryCompactionError && error.usage !== undefined) {\n usage = Usage.add(usage, error.usage);\n }\n const failedCompletionUsage = this.takeFailedCompletionUsage();\n if (error instanceof AgentStructuredOutputError) {\n usage = Usage.add(usage, error.usage);\n } else {\n usage = Usage.add(usage, failedCompletionUsage);\n }\n this.runState = \"closing\";\n const runError = this.normalizeRunError(error);\n const reportedError = await this.reportRunFailure(\n runError,\n runId,\n usage,\n newMessages,\n runObservers,\n );\n this.runState = reportedError instanceof AgentRunCancelledError ? \"cancelled\" : \"errored\";\n this.disposeAbortLink();\n throw reportedError;\n }\n }\n\n async *events(): AsyncIterable<AgentStreamEvent<Output, RawResponseOf<M>>> {\n this.startRun();\n const runId = this.requestedRunId ?? globalThis.crypto.randomUUID();\n let usage = Usage.empty();\n let currentTurns = 0;\n let lastPrompt = this.promptMessage;\n let newMessages: MessageType[] = [this.promptMessage];\n const bufferOutputDeltas = hasEnforcedOutputGuardrails(this.guardrailPolicies);\n let runObservers: ActiveAgentRunObservers | undefined;\n let pendingTurnMessages: MessageType[] = [];\n\n try {\n this.throwIfCancelled();\n const memoryPreparation =\n this.continuationState === undefined\n ? await this.memoryRecorder.prepareHistory(\n runId,\n newMessages,\n this.abortController.signal,\n )\n : undefined;\n if (memoryPreparation !== undefined) {\n this.chatHistory = memoryPreparation.history;\n usage = Usage.add(usage, memoryPreparation.usage);\n this.memoryCompaction = memoryPreparation.compaction;\n await this.notifyInternalMemoryCompaction(memoryPreparation.compaction);\n }\n runObservers = await this.startRunObservers(runId);\n if (memoryPreparation !== undefined) {\n await this.recordMemoryCompaction(memoryPreparation, runObservers);\n }\n if (memoryPreparation?.compaction !== undefined) {\n yield { type: \"memory_compaction\", ...memoryPreparation.compaction };\n }\n this.throwIfCancelled();\n await this.activeLifecycle?.onStart?.({\n runId,\n input: lifecycleSnapshot(this.promptMessage),\n history: lifecycleSnapshot(this.chatHistory),\n maxTurns: this.maxTurnCount,\n });\n if (this.continuationState === undefined) {\n const inputResult = await runInputGuardrails(this.guardrailPolicies, {\n prompt: this.promptMessage,\n history: this.chatHistory,\n inputText: textFromMessage(this.promptMessage),\n run: this.guardrailRunContext(runId),\n });\n for (const decision of inputResult.decisions) {\n await this.recordGuardrailDecision(decision, runObservers);\n yield { type: \"guardrail_decision\", decision };\n }\n this.promptMessage = inputResult.prompt;\n if (inputResult.blocked) {\n const text = inputResult.message ?? \"The request was blocked by a guardrail.\";\n const result: AgentBlockedOutcome = {\n type: \"blocked\",\n stage: \"input\",\n ...blockedOutcomeDetails(\n this.guardrailDecisions,\n \"The request was blocked by a guardrail.\",\n ),\n runId,\n text,\n usage,\n messages: [this.promptMessage, { role: \"assistant\", content: text }],\n trace: runObservers.trace,\n guardrails: [...this.guardrailDecisions],\n ...this.memoryCompactionResult(),\n };\n if (this.resumedFrom !== undefined) result.resumedFrom = this.resumedFrom;\n this.runState = \"closing\";\n await this.runLifecycleFinish(result);\n await runObservers.end(observerRunEnd(result));\n this.runState = \"completed\";\n this.disposeAbortLink();\n yield result;\n return;\n }\n }\n\n newMessages = [this.promptMessage];\n await this.memoryRecorder.commitAcceptedInput(runId, newMessages);\n pendingTurnMessages = this.memoryRecorder.pendingTurnMessages(newMessages);\n await this.runRunStartHook(newMessages);\n if (this.continuationState !== undefined) {\n const responsePart =\n this.promptMessage.role === \"tool\" ? this.promptMessage.content[0] : undefined;\n if (responsePart === undefined || responsePart.type === \"tool-result\") {\n throw new TypeError(\"Agent continuation response message is invalid.\");\n }\n yield {\n type: \"interaction_response\",\n response: responsePart,\n sourceRunId: this.resumedFrom?.runId ?? this.continuationState.kind,\n };\n try {\n const execution = this.executeContinuationToolStream(runId, newMessages, {\n turn: 1,\n runObservers,\n });\n for await (const event of execution.events) {\n yield { turn: 1, ...event };\n }\n const toolResults = await execution.results;\n const toolMessage: MessageType = { role: \"tool\", content: toolResults };\n newMessages.push(toolMessage);\n await this.memoryRecorder.commitMessages(runId, 1, [toolMessage], pendingTurnMessages);\n for (const receipt of await this.drainSteeringMessages(\n runId,\n 1,\n newMessages,\n pendingTurnMessages,\n )) {\n yield { type: \"steering_applied\", id: receipt.id, turn: 1 };\n }\n await this.memoryRecorder.commitCompletedTurn(runId, 1, pendingTurnMessages);\n } catch (error) {\n if (error instanceof ToolExecutionSuspension) {\n const result = await this.finishSuspension({\n runId,\n turn: 1,\n usage,\n newMessages,\n pendingTurnMessages,\n runObservers,\n suspension: error,\n uncommittedMessages: [],\n });\n yield result;\n return;\n }\n throw error;\n }\n }\n while (currentTurns <= this.maxTurnCount + 1) {\n const prompt = newMessages.at(-1);\n if (prompt === undefined) {\n throw new Error(\"AgentRun requires at least one message\");\n }\n\n lastPrompt = prompt;\n currentTurns += 1;\n\n const historyForRequest = [...this.chatHistory, ...newMessages.slice(0, -1)];\n yield {\n type: \"turn_start\",\n turn: currentTurns,\n prompt,\n history: historyForRequest,\n };\n await this.runTurnStartHook(currentTurns, prompt, historyForRequest, newMessages);\n await this.runCompletionCallHook(prompt, historyForRequest, newMessages);\n\n const request = await this.createTurnRequest(prompt, historyForRequest, currentTurns);\n\n assertCompletionRequestSupported(this.agent.model, request, { streaming: true });\n const providerRequest = this.providerTraceRequest(request, { stream: true });\n const generationStartArgs = this.generationStartArgs(\n currentTurns,\n request,\n providerRequest,\n );\n const generationObservers = await runObservers.startGeneration(generationStartArgs);\n this.activeGeneration = { turn: currentTurns, observers: generationObservers };\n const generationStartedAt = Date.now();\n yield {\n type: \"generation_start\",\n turn: currentTurns,\n request,\n modelInfo: generationStartArgs.modelInfo,\n };\n const bufferResponseEvents =\n this.shouldBufferStreamResponseEvents() || this.agent.outputSchema !== undefined;\n const completionState: StreamingCompletionState = {\n response: undefined,\n firstDeltaMs: undefined,\n emittedToolCallIds: new Set(),\n providerErrorUsage: Usage.empty(),\n };\n let response: CompletionResponse;\n try {\n try {\n for await (const event of this.streamCompletion({\n request,\n turn: currentTurns,\n bufferResponseEvents,\n bufferOutputDeltas,\n generationStartedAt,\n generationObservers,\n runObservers,\n state: completionState,\n })) {\n yield event;\n }\n } finally {\n usage = Usage.add(usage, completionState.providerErrorUsage);\n }\n if (completionState.response === undefined) {\n throw new Error(\"Streaming completion ended without a response.\");\n }\n response = completionState.response;\n } catch (error) {\n await settleFailureCleanup([\n () => this.closeActiveGeneration(error),\n () => this.runCompletionErrorHook(prompt, error, newMessages),\n ]);\n throw error;\n }\n const { firstDeltaMs, emittedToolCallIds } = completionState;\n\n let generationEndArgs: AgentGenerationEndArgs = {\n turn: currentTurns,\n response,\n };\n if (firstDeltaMs !== undefined) {\n generationEndArgs = { ...generationEndArgs, firstDeltaMs };\n }\n this.activeGeneration = undefined;\n await generationObservers.end(generationEndArgs);\n response = await this.runCompletionResponseMiddlewares(request, response, currentTurns);\n try {\n assertCompletionResponseIntegrity({ response });\n } catch (error) {\n const providerOutputUsage = completionProviderOutputErrorUsage(error);\n if (providerOutputUsage !== undefined) usage = Usage.add(usage, providerOutputUsage);\n throw error;\n }\n usage = Usage.add(usage, response.usage);\n this.updateRunProgress(newMessages);\n await this.runCompletionResponseHook(prompt, response, newMessages);\n await this.runTurnEndHook(currentTurns, response, newMessages);\n await this.activeLifecycle?.onStepFinish?.({\n runId,\n step: currentTurns,\n response: lifecycleSnapshot(response),\n usage: lifecycleSnapshot(usage),\n });\n\n const toolCalls = response.choice.filter(\n (item): item is ToolCallPart => item.type === \"tool-call\",\n );\n const assistantMessage = this.generatedAssistantMessage(response, request);\n newMessages.push(assistantMessage);\n\n if (toolCalls.length === 0) {\n let emittedTurnEnd = false;\n if (!bufferOutputDeltas) {\n if (bufferResponseEvents) {\n for (const event of responseStreamEvents(currentTurns, response)) {\n yield event as AgentStreamEvent<Output, RawResponseOf<M>>;\n }\n }\n yield {\n type: \"turn_end\",\n turn: currentTurns,\n response: response as CompletionResponse<RawResponseOf<M>>,\n firstDeltaMs,\n };\n emittedTurnEnd = true;\n }\n if (this.steeringMessages.length > 0) {\n await this.memoryRecorder.commitMessages(\n runId,\n currentTurns,\n [assistantMessage],\n pendingTurnMessages,\n );\n }\n const appliedSteering = await this.drainSteeringMessages(\n runId,\n currentTurns,\n newMessages,\n pendingTurnMessages,\n { closeWhenEmpty: true },\n );\n for (const receipt of appliedSteering) {\n yield { type: \"steering_applied\", id: receipt.id, turn: currentTurns };\n }\n if (appliedSteering.length > 0) {\n await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);\n continue;\n }\n\n for await (const event of this.completeStreamingRun({\n runId,\n turn: currentTurns,\n request,\n response,\n firstDeltaMs,\n usage,\n newMessages,\n pendingTurnMessages,\n runObservers,\n bufferResponseEvents,\n bufferOutputDeltas,\n emittedTurnEnd,\n })) {\n yield event;\n }\n return;\n }\n\n if (bufferResponseEvents) {\n for (const event of responseStreamEvents(currentTurns, response)) {\n yield event as AgentStreamEvent<Output, RawResponseOf<M>>;\n }\n } else {\n for (const toolCall of toolCalls) {\n if (!emittedToolCallIds.has(toolCall.toolCallId)) {\n yield { type: \"tool_call\", turn: currentTurns, toolCall };\n }\n }\n }\n this.updateRunProgress(newMessages);\n yield {\n type: \"turn_end\",\n turn: currentTurns,\n response: response as CompletionResponse<RawResponseOf<M>>,\n firstDeltaMs,\n };\n\n let toolResults: ToolResultPart[];\n try {\n const toolExecution = this.executeStreamingToolCalls(runId, toolCalls, newMessages, {\n turn: currentTurns,\n runObservers,\n toolDefinitions: request.tools,\n });\n for await (const result of toolExecution.events) {\n yield { turn: currentTurns, ...result };\n }\n toolResults = await toolExecution.results;\n } catch (error) {\n if (error instanceof ToolExecutionSuspension) {\n const result = await this.finishSuspension({\n runId,\n turn: currentTurns,\n usage,\n newMessages,\n pendingTurnMessages,\n runObservers,\n suspension: error,\n uncommittedMessages: [assistantMessage],\n });\n yield result;\n return;\n }\n throw error;\n }\n const toolMessage: MessageType = { role: \"tool\", content: toolResults };\n newMessages.push(toolMessage);\n await this.memoryRecorder.commitMessages(\n runId,\n currentTurns,\n [assistantMessage, toolMessage],\n pendingTurnMessages,\n );\n for (const receipt of await this.drainSteeringMessages(\n runId,\n currentTurns,\n newMessages,\n pendingTurnMessages,\n )) {\n yield { type: \"steering_applied\", id: receipt.id, turn: currentTurns };\n }\n await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);\n }\n\n throw new MaxTurnsError(this.maxTurnCount, [...this.chatHistory, ...newMessages], lastPrompt);\n } catch (error) {\n if (error instanceof MemoryCompactionError && error.usage !== undefined) {\n usage = Usage.add(usage, error.usage);\n }\n if (error instanceof AgentStructuredOutputError) {\n usage = Usage.add(usage, error.usage);\n }\n this.runState = \"closing\";\n const runError = this.normalizeRunError(error);\n const reportedError = await this.reportRunFailure(\n runError,\n runId,\n usage,\n newMessages,\n runObservers,\n );\n this.runState = reportedError instanceof AgentRunCancelledError ? \"cancelled\" : \"errored\";\n const finalUsage = usage;\n yield { type: \"error\", error: reportedError, usage: finalUsage };\n this.disposeAbortLink();\n return;\n } finally {\n if (this.runState === \"running\" || this.runState === \"closing\") {\n const cancellation =\n this.cancellationError ??\n new AgentRunCancelledError([...this.chatHistory, ...newMessages], \"Agent stream closed.\");\n this.cancellationError = cancellation;\n await settleFailureCleanup([() => this.closeActiveGeneration(cancellation)]);\n await this.reportRunFailure(cancellation, runId, usage, newMessages, runObservers);\n this.runState = \"cancelled\";\n this.disposeAbortLink();\n }\n }\n }\n\n private async runCompletion(\n request: CompletionRequest,\n turn: number,\n runObservers: ActiveAgentRunObservers,\n ): Promise<CompletionResponse> {\n assertCompletionRequestSupported(this.agent.model, request);\n this.validatedStructuredOutput = undefined;\n this.failedCompletionUsage = Usage.empty();\n const providerRequest = this.providerTraceRequest(request);\n const generationObservers = await runObservers.startGeneration(\n this.generationStartArgs(turn, request, providerRequest),\n );\n let currentRequest = request;\n let failedAttemptUsage = Usage.empty();\n try {\n for (let attempt = 1; ; attempt += 1) {\n let response: CompletionResponse;\n try {\n this.throwIfCancelled();\n response = await this.agent.model.completion(currentRequest, this.modelCallOptions());\n assertCompletionResponseIntegrity({ response });\n } catch (error) {\n const attemptUsage = completionProviderOutputErrorUsage(error);\n if (attemptUsage !== undefined) {\n failedAttemptUsage = Usage.add(failedAttemptUsage, attemptUsage);\n this.failedCompletionUsage = failedAttemptUsage;\n }\n const retryOptions = this.retryOptionsForFailure(error, attempt, turn, false);\n if (retryOptions === undefined) {\n throw error;\n }\n await this.scheduleCompletionRetry(\n error,\n attempt,\n turn,\n false,\n retryOptions,\n runObservers,\n providerOutputRetryEventAttributes(error, failedAttemptUsage),\n );\n continue;\n }\n\n const cumulativeUsage = Usage.add(failedAttemptUsage, response.usage);\n try {\n this.validateStructuredResponse(response, attempt, cumulativeUsage);\n } catch (error) {\n const retryOptions = this.retryOptionsForFailure(error, attempt, turn, false);\n if (retryOptions === undefined) {\n throw error;\n }\n failedAttemptUsage = cumulativeUsage;\n this.failedCompletionUsage = failedAttemptUsage;\n const retryRequest = structuredOutputRetryRequest(request, response, error);\n currentRequest = retryRequest.request;\n await this.scheduleCompletionRetry(\n error,\n attempt,\n turn,\n false,\n retryOptions,\n runObservers,\n structuredOutputRetryEventAttributes(error, retryRequest),\n );\n continue;\n }\n\n const finalResponse = Usage.isEmpty(failedAttemptUsage)\n ? response\n : { ...response, usage: cumulativeUsage };\n await generationObservers.end({ turn, response: finalResponse });\n this.failedCompletionUsage = Usage.empty();\n return finalResponse;\n }\n } catch (error) {\n await settleFailureCleanup([() => generationObservers.error({ turn, error })]);\n throw error;\n }\n }\n\n private async createTurnRequest(\n prompt: MessageType,\n history: MessageType[],\n turn: number,\n ): Promise<CompletionRequest> {\n const ragText = extractRagText(prompt);\n const abortSignal = this.abortController.signal;\n const documents = await fetchContextDocuments(this.agent, ragText, abortSignal);\n const toolDefinitions = await fetchToolDefinitions(this.agent, ragText, abortSignal);\n const request = createCompletionRequest(providerMessages([...history, prompt]), {\n instructions: this.agent.instructions,\n documents,\n tools: [...toolDefinitions, ...getAgentToolState(this.agent).providerTools],\n temperature: this.agent.temperature,\n maxTokens: this.agent.maxTokens,\n providerOptions: this.agent.providerOptions,\n toolChoice: this.agent.toolChoice,\n outputSchema: getAgentProviderOutputSchema(this.agent),\n });\n return this.runCompletionRequestMiddlewares(request, turn);\n }\n\n private async *streamCompletion(args: {\n request: CompletionRequest;\n turn: number;\n bufferResponseEvents: boolean;\n bufferOutputDeltas: boolean;\n generationStartedAt: number;\n generationObservers: ActiveGenerationObservers;\n runObservers: ActiveAgentRunObservers;\n state: StreamingCompletionState;\n }): AsyncIterable<AgentStreamEvent<Output, RawResponseOf<M>>> {\n const model = this.agent.model;\n if (!isStreamingCompletionModel(model)) {\n throw new TypeError(\"Streaming completion requires a streaming-capable model.\");\n }\n this.validatedStructuredOutput = undefined;\n let currentRequest = args.request;\n for (let attempt = 1; ; attempt += 1) {\n const accumulator = new CompletionStreamAccumulator();\n let hasProviderProgress = false;\n let recordedErrorUsage = false;\n let attemptErrorUsage: Usage | undefined;\n try {\n this.throwIfCancelled();\n for await (const event of model.streamCompletion(currentRequest, this.modelCallOptions())) {\n if (event.type === \"error\") {\n const eventUsage = event.usage ?? completionProviderOutputErrorUsage(event.error);\n if (eventUsage !== undefined) {\n args.state.providerErrorUsage = Usage.add(args.state.providerErrorUsage, eventUsage);\n recordedErrorUsage = true;\n attemptErrorUsage = eventUsage;\n }\n throw event.error;\n }\n const mapped = accumulator.accept(event);\n if (event.type === \"final\") break;\n if (event.type === \"tool_call_delta\" || mapped !== undefined) {\n hasProviderProgress = true;\n }\n if (args.state.firstDeltaMs === undefined && isGenerationDeltaEvent(event.type)) {\n args.state.firstDeltaMs = Date.now() - args.generationStartedAt;\n }\n if (event.type === \"tool_call_delta\") {\n yield addTurnToToolCallDelta(args.turn, event);\n }\n if (mapped !== undefined) {\n await args.generationObservers.update?.({ turn: args.turn, delta: mapped });\n if (mapped.type === \"tool_call\") {\n args.state.emittedToolCallIds.add(mapped.toolCall.toolCallId);\n }\n const shouldBuffer =\n args.bufferResponseEvents ||\n (args.bufferOutputDeltas &&\n (mapped.type === \"text_delta\" || mapped.type === \"reasoning_delta\"));\n if (!shouldBuffer) {\n yield addTurn(args.turn, mapped) as AgentStreamEvent<Output, RawResponseOf<M>>;\n }\n }\n }\n const response = accumulator.response();\n assertCompletionResponseIntegrity({ response });\n const cumulativeStructuredUsage = Usage.add(args.state.providerErrorUsage, response.usage);\n try {\n this.validateStructuredResponse(response, attempt, cumulativeStructuredUsage);\n } catch (error) {\n const retryOptions = this.retryOptionsForFailure(error, attempt, args.turn, true);\n if (retryOptions === undefined) {\n if (error instanceof AgentStructuredOutputError) {\n args.state.providerErrorUsage = Usage.empty();\n }\n throw error;\n }\n args.state.providerErrorUsage = Usage.add(args.state.providerErrorUsage, response.usage);\n args.state.firstDeltaMs = undefined;\n args.state.emittedToolCallIds.clear();\n const retryRequest = structuredOutputRetryRequest(args.request, response, error);\n currentRequest = retryRequest.request;\n await this.scheduleCompletionRetry(\n error,\n attempt,\n args.turn,\n true,\n retryOptions,\n args.runObservers,\n structuredOutputRetryEventAttributes(error, retryRequest),\n );\n continue;\n }\n args.state.response = Usage.isEmpty(args.state.providerErrorUsage)\n ? response\n : { ...response, usage: cumulativeStructuredUsage };\n args.state.providerErrorUsage = Usage.empty();\n return;\n } catch (error) {\n if (!recordedErrorUsage) {\n const attemptUsage = completionProviderOutputErrorUsage(error);\n if (attemptUsage !== undefined) {\n args.state.providerErrorUsage = Usage.add(args.state.providerErrorUsage, attemptUsage);\n attemptErrorUsage = attemptUsage;\n }\n }\n const retryOptions = hasProviderProgress\n ? undefined\n : this.retryOptionsForFailure(error, attempt, args.turn, true);\n if (retryOptions === undefined) {\n throw error;\n }\n await this.scheduleCompletionRetry(\n error,\n attempt,\n args.turn,\n true,\n retryOptions,\n args.runObservers,\n providerOutputRetryEventAttributes(\n error,\n args.state.providerErrorUsage,\n attemptErrorUsage,\n ),\n );\n }\n }\n }\n\n private async *completeStreamingRun(args: {\n runId: string;\n turn: number;\n request: CompletionRequest;\n response: CompletionResponse;\n firstDeltaMs: number | undefined;\n usage: Usage;\n newMessages: MessageType[];\n pendingTurnMessages: MessageType[];\n runObservers: ActiveAgentRunObservers;\n bufferResponseEvents: boolean;\n bufferOutputDeltas: boolean;\n emittedTurnEnd: boolean;\n }): AsyncIterable<AgentStreamEvent<Output, RawResponseOf<M>>> {\n const guardedOutput = await this.runOutputGuardrailsForResponse(\n args.runId,\n args.usage,\n args.response,\n args.newMessages,\n args.runObservers,\n );\n for (const decision of guardedOutput.decisions) {\n yield { type: \"guardrail_decision\", decision };\n }\n\n const response = guardedOutput.response;\n const assistantMessage = this.generatedAssistantMessage(response, args.request);\n args.newMessages[args.newMessages.length - 1] = assistantMessage;\n await this.memoryRecorder.commitMessages(\n args.runId,\n args.turn,\n [assistantMessage],\n args.pendingTurnMessages,\n );\n if (!args.emittedTurnEnd && (args.bufferResponseEvents || args.bufferOutputDeltas)) {\n for (const event of responseStreamEvents(args.turn, response, args.bufferResponseEvents)) {\n yield event as AgentStreamEvent<Output, RawResponseOf<M>>;\n }\n }\n if (!args.emittedTurnEnd) {\n yield {\n type: \"turn_end\",\n turn: args.turn,\n response: response as CompletionResponse<RawResponseOf<M>>,\n firstDeltaMs: args.firstDeltaMs,\n };\n }\n\n const result = this.createTerminalResult(\n args.runId,\n guardedOutput.text,\n guardedOutput.blocked,\n args.usage,\n args.newMessages,\n args.runObservers,\n );\n if (result.type === \"response\") {\n await this.runRunEndHook(result, args.newMessages);\n }\n await this.memoryRecorder.commitCompletedRun(\n args.runId,\n args.turn,\n args.newMessages,\n args.pendingTurnMessages,\n );\n await this.runLifecycleFinish(result);\n await args.runObservers.end(observerRunEnd(result));\n this.runState = \"completed\";\n this.disposeAbortLink();\n yield result;\n }\n\n private async finishSuspension(args: {\n runId: string;\n turn: number;\n usage: Usage;\n newMessages: MessageType[];\n pendingTurnMessages: MessageType[];\n runObservers: ActiveAgentRunObservers;\n suspension: ToolExecutionSuspension;\n uncommittedMessages: MessageType[];\n }): Promise<AgentInteractionOutcome> {\n const partialToolMessage: MessageType | undefined =\n args.suspension.completedResults.length === 0\n ? undefined\n : { role: \"tool\", content: [...args.suspension.completedResults] };\n if (partialToolMessage !== undefined) {\n args.newMessages.push(partialToolMessage);\n args.uncommittedMessages.push(partialToolMessage);\n }\n await this.memoryRecorder.commitMessages(\n args.runId,\n args.turn,\n args.uncommittedMessages,\n args.pendingTurnMessages,\n );\n await this.memoryRecorder.commitCompletedRun(\n args.runId,\n args.turn,\n args.newMessages,\n args.pendingTurnMessages,\n );\n\n this.runState = \"closing\";\n\n const continuationState: AgentContinuationState = {\n kind: \"anvia.agent-continuation\",\n history: [...this.chatHistory],\n messages: [...args.newMessages],\n pending: args.suspension.pending,\n remainingToolCalls: [...args.suspension.remainingToolCalls],\n steering: this.steeringMessages.map((entry) => ({\n id: entry.id,\n messages: [...entry.messages],\n })),\n };\n if (this.memoryScope !== undefined) continuationState.memoryScope = this.memoryScope;\n const continuation = parseAgentContinuation({\n version: 1,\n agentId: this.agent.id,\n sourceRunId: args.runId,\n interaction: args.suspension.interaction,\n state: serializeContinuationState(continuationState),\n });\n const result: AgentInteractionOutcome = {\n type: \"interaction\",\n runId: args.runId,\n text: latestAssistantText([...this.chatHistory, ...args.newMessages]),\n usage: args.usage,\n messages: [...args.newMessages],\n trace: args.runObservers.trace,\n guardrails: [...this.guardrailDecisions],\n interaction: continuation.interaction,\n continuation,\n ...generationArtifacts([...this.chatHistory, ...args.newMessages]),\n ...this.memoryCompactionResult(),\n };\n if (this.resumedFrom !== undefined) result.resumedFrom = this.resumedFrom;\n await this.runLifecycleFinish(result);\n await args.runObservers.end(observerRunEnd(result));\n this.runState = \"completed\";\n this.currentMessages = [...args.newMessages];\n this.disposeAbortLink();\n return result;\n }\n\n private generatedAssistantMessage(\n response: CompletionResponse,\n _request: CompletionRequest,\n ): MessageType {\n const generation: JsonObject = {\n provider: this.agent.model.provider,\n modelId: this.agent.model.modelId,\n usage: { ...response.usage },\n };\n if (response.finishReason !== undefined) generation.finishReason = response.finishReason;\n if (response.providerFinishReason !== undefined) {\n generation.providerFinishReason = response.providerFinishReason;\n }\n if (response.contextUsage !== undefined) generation.contextUsage = response.contextUsage;\n if (response.sources !== undefined) generation.sources = response.sources;\n if (response.providerToolCalls !== undefined) {\n generation.providerToolCalls = response.providerToolCalls;\n }\n const metadata: JsonObject = { anvia: { generation } };\n let message: MessageType = {\n role: \"assistant\",\n content: response.choice,\n metadata,\n };\n if (response.messageId !== undefined) message = { ...message, id: response.messageId };\n return message;\n }\n\n private providerTraceRequest(\n request: CompletionRequest,\n options: { stream?: boolean | undefined } = {},\n ): JsonObject | undefined {\n try {\n return this.agent.model.traceRequest?.(request, options);\n } catch (error) {\n return {\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n private generationStartArgs(\n turn: number,\n request: CompletionRequest,\n providerRequest: JsonObject | undefined,\n ): AgentGenerationStartArgs & { modelInfo: AgentGenerationModelInfo } {\n let args: AgentGenerationStartArgs & { modelInfo: AgentGenerationModelInfo } = {\n turn,\n request,\n modelInfo: {\n provider: this.agent.model.provider,\n modelId: this.agent.model.modelId,\n capabilities: this.agent.model.capabilities,\n },\n };\n if (providerRequest !== undefined) args = { ...args, providerRequest };\n return args;\n }\n\n private retryOptionsForFailure(\n error: unknown,\n attempt: number,\n turn: number,\n streaming: boolean,\n ): ResolvedRetryOptions | undefined {\n if (this.abortController.signal.aborted) return undefined;\n return retryOptionsForFailure(this.completionRetryOptions, {\n error,\n attempt,\n turn,\n streaming,\n });\n }\n\n private async scheduleCompletionRetry(\n error: unknown,\n attempt: number,\n turn: number,\n streaming: boolean,\n options: ResolvedRetryOptions,\n runObservers: ActiveAgentRunObservers,\n additionalAttributes?: JsonObject | undefined,\n ): Promise<void> {\n const delayMs = retryDelayMs(options, attempt);\n const attributes: JsonObject = {\n turn,\n attempt,\n nextAttempt: attempt + 1,\n maxAttempts: options.maxAttempts,\n delayMs,\n streaming,\n ...retryErrorAttributes(error),\n };\n if (additionalAttributes !== undefined) {\n Object.assign(attributes, additionalAttributes);\n }\n await runObservers.event({\n name: \"completion.retry\",\n level: \"WARNING\",\n attributes,\n });\n await waitForRetry(delayMs, this.abortController.signal);\n }\n\n private async executeToolCalls(\n runId: string,\n toolCalls: ToolCallPart[],\n newMessages: MessageType[],\n onResult?: (result: ToolResultEventPayload) => void,\n onStreamEvent?: (event: AgentToolEventPayload) => void,\n observation?: ToolExecutionObservation,\n ): Promise<ToolResultPart[]> {\n const executor = this.createToolExecutor(runId, newMessages);\n return executor.execute(toolCalls, onResult, onStreamEvent, observation);\n }\n\n private createToolExecutor(runId: string, newMessages: MessageType[]): ToolCallExecutor {\n return new ToolCallExecutor(\n this.agent,\n this.activeHook,\n async (request) => {\n throw new AgentInteractionSignal(approvalInteraction(request), request.rejectMessage);\n },\n this.activeLifecycle,\n {\n runId,\n sessionId: this.memoryScope?.sessionId,\n metadata: this.memoryScope?.metadata,\n },\n this.concurrency,\n this.requestMiddlewares,\n this.abortController.signal,\n (reason) => this.cancelled(newMessages, reason),\n );\n }\n\n private async resolveContinuationTools(\n runId: string,\n newMessages: MessageType[],\n onResult: ((result: ToolResultEventPayload) => void) | undefined,\n onStreamEvent: ((event: AgentToolEventPayload) => void) | undefined,\n observation: ToolExecutionObservation,\n ): Promise<ToolResultPart[]> {\n const state = this.continuationState;\n const response = this.interactionResponse;\n if (state === undefined || response === undefined) {\n return [];\n }\n const pending = state.pending;\n const interaction = this.resumedFrom;\n if (interaction === undefined) {\n throw new TypeError(\"Agent continuation is missing its source run linkage.\");\n }\n const executor = this.createToolExecutor(runId, newMessages);\n const results: ToolResultPart[] = [];\n if (response.type === \"tool-approval\") {\n const attributes: JsonObject = {\n approvalId: interaction.interactionId,\n toolName: pending.toolCall.toolName,\n toolCallId: pending.toolCall.toolCallId,\n internalCallId: pending.internalCallId,\n approved: response.approved,\n };\n if (response.reason !== undefined) attributes.decisionReason = response.reason;\n await observation.runObservers.event({\n name: \"tool.approval_resolved\",\n attributes,\n });\n if (response.approved) {\n results.push(await executor.executeResumed(pending, onResult, onStreamEvent, observation));\n } else {\n const output = {\n type: \"execution-denied\" as const,\n reason: response.reason ?? pending.rejectMessage ?? \"Tool approval was rejected.\",\n };\n results.push(await executor.resolveResumed(pending, output, onResult, observation));\n }\n } else {\n const currentTool = this.agent.getTool(pending.toolCall.toolName);\n if (currentTool === undefined || !isQuestionTool(currentTool)) {\n throw new TypeError(\n `Cannot resume question interaction because tool \"${pending.toolCall.toolName}\" is no longer registered as a question tool.`,\n );\n }\n const output = questionResult(response.answers);\n results.push(await executor.resolveResumed(pending, output, onResult, observation));\n }\n try {\n results.push(\n ...(await executor.execute(state.remainingToolCalls, onResult, onStreamEvent, observation)),\n );\n } catch (error) {\n if (error instanceof ToolExecutionSuspension) {\n error.completedResults = [...results, ...error.completedResults];\n }\n throw error;\n }\n return results;\n }\n\n private executeStreamingToolCalls(\n runId: string,\n toolCalls: ToolCallPart[],\n newMessages: MessageType[],\n observation: ToolExecutionObservation,\n ): {\n events: AsyncIterable<ToolExecutionEventPayload>;\n results: Promise<ToolResultPart[]>;\n } {\n const events = createAsyncQueue<ToolExecutionEventPayload>();\n const results = this.executeToolCalls(\n runId,\n toolCalls,\n newMessages,\n (result) => events.enqueue(result),\n (event) => events.enqueue(event),\n observation,\n );\n results.then(\n () => events.close(),\n (error: unknown) => events.throw(error),\n );\n return { events, results };\n }\n\n private executeContinuationToolStream(\n runId: string,\n newMessages: MessageType[],\n observation: ToolExecutionObservation,\n ): {\n events: AsyncIterable<ToolExecutionEventPayload>;\n results: Promise<ToolResultPart[]>;\n } {\n const events = createAsyncQueue<ToolExecutionEventPayload>();\n const results = this.resolveContinuationTools(\n runId,\n newMessages,\n (result) => events.enqueue(result),\n (event) => events.enqueue(event),\n observation,\n );\n results.then(\n () => events.close(),\n (error: unknown) => events.throw(error),\n );\n return { events, results };\n }\n\n private async closeActiveGeneration(error: unknown): Promise<void> {\n const active = this.activeGeneration;\n if (active === undefined) {\n return;\n }\n this.activeGeneration = undefined;\n await active.observers.error({ turn: active.turn, error });\n }\n\n private updateRunProgress(messages: MessageType[]): void {\n this.currentMessages = [...messages];\n }\n\n private async runLifecycleFinish(result: AgentTerminalResult<Output>): Promise<void> {\n const common = {\n runId: result.runId,\n text: result.text,\n usage: lifecycleSnapshot(result.usage),\n messages: lifecycleSnapshot(result.messages),\n };\n if (result.memoryCompaction !== undefined) {\n Object.assign(common, { memoryCompaction: lifecycleSnapshot(result.memoryCompaction) });\n }\n const event =\n result.type === \"response\"\n ? {\n ...common,\n status: \"completed\",\n output: lifecycleSnapshot(result.output),\n }\n : result.type === \"blocked\"\n ? {\n ...common,\n status: \"blocked\",\n stage: result.stage,\n }\n : {\n ...common,\n status: \"suspended\",\n interaction: lifecycleSnapshot(result.interaction),\n };\n await this.activeLifecycle?.onFinish?.(event as AgentFinishEvent<Output>);\n }\n\n private async runLifecycleError(\n error: unknown,\n runId: string,\n usage: Usage,\n messages: MessageType[],\n ): Promise<unknown | undefined> {\n try {\n await this.activeLifecycle?.onError?.({\n runId,\n error: lifecycleSnapshot(error),\n usage: lifecycleSnapshot(usage),\n messages: lifecycleSnapshot([...this.chatHistory, ...messages]),\n });\n return undefined;\n } catch (lifecycleError) {\n return lifecycleError;\n }\n }\n\n private async reportRunFailure(\n error: unknown,\n runId: string,\n usage: Usage,\n messages: MessageType[],\n runObservers: ActiveAgentRunObservers | undefined,\n ): Promise<unknown> {\n const reportedError = await this.resolveReportedRunError(error, runId, usage, messages);\n await settleFailureCleanup([\n () =>\n this.onInternalFailure?.({\n error: reportedError,\n messages: lifecycleSnapshot(messages),\n }),\n () =>\n runObservers?.error({\n status: reportedError instanceof AgentRunCancelledError ? \"cancelled\" : \"failed\",\n error: reportedError,\n usage,\n messages: [...messages],\n }),\n () => this.memoryRecorder.recordError(runId, reportedError, messages),\n ]);\n return reportedError;\n }\n\n private async resolveReportedRunError(\n error: unknown,\n runId: string,\n usage: Usage,\n messages: MessageType[],\n ): Promise<unknown> {\n try {\n await this.runRunErrorHook(error, usage, messages);\n } catch {\n // Thrown hook errors are diagnostic cleanup and must not replace the run failure.\n }\n const reportedError = this.cancellationError ?? error;\n await this.runLifecycleError(reportedError, runId, usage, messages);\n return reportedError;\n }\n\n private async runOutputGuardrailsForResponse(\n runId: string,\n usage: Usage,\n response: CompletionResponse,\n messages: MessageType[],\n runObservers: ActiveAgentRunObservers,\n ): Promise<{\n text: string;\n blocked: boolean;\n response: CompletionResponse;\n decisions: GuardrailDecisionRecord[];\n }> {\n const originalOutput = textFromAssistantContent(response.choice);\n const result = await runOutputGuardrails(this.guardrailPolicies, {\n outputText: originalOutput,\n messages: [...this.chatHistory, ...messages],\n usage,\n run: this.guardrailRunContext(runId),\n });\n for (const decision of result.decisions) {\n await this.recordGuardrailDecision(decision, runObservers);\n }\n const text = result.blocked\n ? (result.message ?? \"The response was blocked by a guardrail.\")\n : result.outputText;\n if (text === originalOutput) {\n return { text, blocked: result.blocked, response, decisions: result.decisions };\n }\n return {\n text,\n blocked: result.blocked,\n response: {\n ...response,\n choice: [{ type: \"text\", text }],\n },\n decisions: result.decisions,\n };\n }\n\n private createTerminalResult(\n runId: string,\n text: string,\n blocked: boolean,\n usage: Usage,\n messages: MessageType[],\n runObservers: ActiveAgentRunObservers,\n ): AgentTerminalResult<Output> {\n const common = {\n runId,\n text,\n usage,\n messages: [...messages],\n trace: runObservers.trace,\n guardrails: [...this.guardrailDecisions],\n ...generationArtifacts(messages),\n ...this.memoryCompactionResult(),\n };\n if (this.resumedFrom !== undefined) Object.assign(common, { resumedFrom: this.resumedFrom });\n if (blocked) {\n return {\n ...common,\n type: \"blocked\",\n stage: \"output\",\n ...blockedOutcomeDetails(\n this.guardrailDecisions,\n \"The response was blocked by a guardrail.\",\n ),\n };\n }\n return {\n ...common,\n type: \"response\",\n output: this.parseOutput(text),\n };\n }\n\n private validateStructuredResponse(\n response: CompletionResponse,\n attempt: number,\n usage: Usage,\n ): void {\n if (this.agent.outputSchema === undefined) return;\n if (response.choice.some((item) => item.type === \"tool-call\")) return;\n const text = textFromAssistantContent(response.choice);\n const normalized = normalizeStructuredOutput(text);\n if (response.finishReason === \"content-filter\") {\n throw new AgentStructuredOutputError({\n phase: \"content-filter\",\n attempt,\n maxAttempts: this.completionRetryOptions?.maxAttempts ?? 1,\n outputLength: text.length,\n normalizedLength: normalized.text.length,\n outputFormat: normalized.format,\n attemptUsage: response.usage,\n usage,\n finishReason: response.finishReason,\n providerFinishReason: response.providerFinishReason,\n });\n }\n if (response.finishReason === \"length\") {\n throw new AgentStructuredOutputError({\n phase: \"truncated\",\n attempt,\n maxAttempts: this.completionRetryOptions?.maxAttempts ?? 1,\n outputLength: text.length,\n normalizedLength: normalized.text.length,\n outputFormat: normalized.format,\n attemptUsage: response.usage,\n usage,\n finishReason: response.finishReason,\n providerFinishReason: response.providerFinishReason,\n });\n }\n const output = this.parseOutput(text, attempt, usage, {\n useValidatedOutput: false,\n attemptUsage: response.usage,\n finishReason: response.finishReason,\n providerFinishReason: response.providerFinishReason,\n });\n this.validatedStructuredOutput = { text, output };\n }\n\n private takeFailedCompletionUsage(): Usage {\n const usage = this.failedCompletionUsage;\n this.failedCompletionUsage = Usage.empty();\n return usage;\n }\n\n private parseOutput(\n text: string,\n attempt = 1,\n usage = Usage.empty(),\n options: {\n useValidatedOutput?: boolean;\n attemptUsage?: Usage;\n finishReason?: CompletionFinishReason | undefined;\n providerFinishReason?: string | undefined;\n } = {},\n ): Output {\n const schema = this.agent.outputSchema;\n if (schema === undefined) return text as Output;\n if (options.useValidatedOutput !== false && this.validatedStructuredOutput?.text === text) {\n return this.validatedStructuredOutput.output;\n }\n const normalized = normalizeStructuredOutput(text);\n const maxAttempts = this.completionRetryOptions?.maxAttempts ?? 1;\n let json: unknown;\n try {\n json = JSON.parse(normalized.text);\n if (!isJsonValue(json)) {\n throw new TypeError(\"Agent structured output is not a JSON value.\");\n }\n } catch (error) {\n throw new AgentStructuredOutputError({\n phase: \"parse\",\n attempt,\n maxAttempts,\n outputLength: text.length,\n normalizedLength: normalized.text.length,\n outputFormat: normalized.format,\n attemptUsage: options.attemptUsage ?? usage,\n usage,\n finishReason: options.finishReason,\n providerFinishReason: options.providerFinishReason,\n cause: error,\n });\n }\n try {\n return schema.parse(json);\n } catch (error) {\n throw new AgentStructuredOutputError({\n phase: \"schema\",\n attempt,\n maxAttempts,\n outputLength: text.length,\n normalizedLength: normalized.text.length,\n outputFormat: normalized.format,\n attemptUsage: options.attemptUsage ?? usage,\n usage,\n finishReason: options.finishReason,\n providerFinishReason: options.providerFinishReason,\n cause: error,\n });\n }\n }\n\n private memoryCompactionResult(): {\n memoryCompaction?: MemoryCompactionInfo | undefined;\n } {\n return this.memoryCompaction === undefined\n ? {}\n : { memoryCompaction: lifecycleSnapshot(this.memoryCompaction) };\n }\n\n private async recordGuardrailDecision(\n decision: GuardrailDecisionRecord,\n runObservers: ActiveAgentRunObservers,\n ): Promise<void> {\n this.guardrailDecisions.push(decision);\n await runObservers.event({\n name: \"guardrail.decision\",\n level: decision.action === \"block\" ? \"WARNING\" : \"DEFAULT\",\n attributes: guardrailDecisionAttributes(decision),\n });\n }\n\n private async recordMemoryCompaction(\n preparation: MemoryPreparation,\n runObservers: ActiveAgentRunObservers,\n ): Promise<void> {\n const compaction = preparation.compaction;\n if (compaction === undefined) {\n return;\n }\n await runObservers.event({\n name: \"memory.compaction\",\n attributes: {\n originalMessageCount: compaction.originalMessageCount,\n compactedMessageCount: compaction.compactedMessageCount,\n retainedMessageCount: compaction.retainedMessageCount,\n originalTokenCount: compaction.originalTokenCount,\n compactedTokenCount: compaction.compactedTokenCount,\n retainedTokenCount: compaction.retainedTokenCount,\n resultTokenCount: compaction.resultTokenCount,\n attempts: compaction.attempts,\n inputTokens: compaction.usage.inputTokens,\n outputTokens: compaction.usage.outputTokens,\n totalTokens: compaction.usage.totalTokens,\n },\n });\n }\n\n private async notifyInternalMemoryCompaction(\n compaction: MemoryCompactionInfo | undefined,\n ): Promise<void> {\n if (compaction === undefined) {\n return;\n }\n await this.onInternalMemoryCompaction?.(lifecycleSnapshot(compaction));\n }\n\n private guardrailRunContext(runId: string): GuardrailRunContext {\n const context: GuardrailRunContext = {\n agentId: this.agent.id,\n runId,\n };\n if (this.memoryScope !== undefined) {\n context.sessionId = this.memoryScope.sessionId;\n if (this.memoryScope.metadata !== undefined) {\n context.metadata = this.memoryScope.metadata;\n }\n }\n return context;\n }\n\n private async startRunObservers(runId: string): Promise<ActiveAgentRunObservers> {\n const observability = this.agent.observability;\n return startAgentRunObservers(\n observability?.observers ?? {},\n {\n runId,\n agentName: this.agent.name,\n agentDescription: this.agent.description,\n instructions: this.agent.instructions,\n trace: this.traceOptions,\n promptRef: this.traceOptions?.promptRef,\n prompt: this.promptMessage,\n history: this.chatHistory,\n maxTurns: this.maxTurnCount,\n },\n {\n primaryTrace: observability?.primaryTrace,\n errorPolicy: observability?.errorPolicy ?? \"ignore\",\n },\n );\n }\n\n private async runCompletionCallHook(\n prompt: MessageType,\n history: MessageType[],\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onCompletionCall?.({\n prompt,\n history,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runRunStartHook(newMessages: MessageType[]): Promise<void> {\n const action = await this.activeHook?.onRunStart?.({\n prompt: this.promptMessage,\n history: this.chatHistory,\n maxTurns: this.maxTurnCount,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runRunEndHook(\n result: AgentResponse<Output>,\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onRunEnd?.({\n status: \"completed\",\n output: result.output,\n text: result.text,\n usage: result.usage,\n messages: result.messages,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runRunErrorHook(\n error: unknown,\n usage: Usage,\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onRunError?.({\n error,\n usage,\n messages: [...this.chatHistory, ...newMessages],\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runTurnStartHook(\n turn: number,\n prompt: MessageType,\n history: MessageType[],\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onTurnStart?.({\n turn,\n prompt,\n history,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runTurnEndHook(\n turn: number,\n response: CompletionResponse,\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onTurnEnd?.({\n turn,\n response,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runCompletionRequestMiddlewares(\n request: CompletionRequest,\n turn: number,\n ): Promise<CompletionRequest> {\n let current = request;\n for (const middleware of this.activeMiddlewares()) {\n const replacement = await middleware.onCompletionRequest?.({\n turn,\n request: current,\n originalRequest: request,\n });\n if (replacement?.request !== undefined) {\n current = replacement.request;\n if (current.providerOptions !== undefined) {\n assertJsonObject(current.providerOptions, \"providerOptions\");\n }\n }\n }\n return current;\n }\n\n private async runCompletionResponseMiddlewares(\n request: CompletionRequest,\n response: CompletionResponse,\n turn: number,\n ): Promise<CompletionResponse> {\n let current = response;\n for (const middleware of this.activeMiddlewares()) {\n const replacement = await middleware.onCompletionResponse?.({\n turn,\n request,\n response: current,\n originalResponse: response,\n });\n if (replacement?.response !== undefined) {\n current = replacement.response;\n }\n }\n return current;\n }\n\n private async runCompletionResponseHook(\n prompt: MessageType,\n response:\n | Awaited<ReturnType<M[\"completion\"]>>\n | Awaited<ReturnType<CompletionModel[\"completion\"]>>,\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onCompletionResponse?.({\n prompt,\n response,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runCompletionErrorHook(\n prompt: MessageType,\n error: unknown,\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onCompletionError?.({\n prompt,\n error,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private activeMiddlewares(): AgentMiddleware[] {\n return [...this.agent.middlewares, ...this.requestMiddlewares];\n }\n\n private shouldBufferStreamResponseEvents(): boolean {\n return (\n this.activeHook?.onCompletionResponse !== undefined ||\n this.activeMiddlewares().some((middleware) => middleware.onCompletionResponse !== undefined)\n );\n }\n\n private async drainSteeringMessages(\n runId: string,\n turn: number,\n newMessages: MessageType[],\n pendingTurnMessages: MessageType[],\n options: { closeWhenEmpty?: boolean } = {},\n ): Promise<QueuedSteering[]> {\n const receipts = this.steeringMessages.splice(0);\n if (receipts.length === 0) {\n if (options.closeWhenEmpty === true) {\n this.runState = \"closing\";\n }\n return [];\n }\n const messages = receipts.flatMap((receipt) => receipt.messages);\n newMessages.push(...messages);\n await this.memoryRecorder.commitMessages(runId, turn, messages, pendingTurnMessages);\n return receipts;\n }\n\n private startRun(): void {\n if (this.runState === \"idle\") {\n this.runState = \"running\";\n return;\n }\n if (this.runState === \"running\") {\n throw new Error(\"Agent stream is already running.\");\n }\n throw new Error(\"Agent stream has already been consumed.\");\n }\n\n private isTerminal(): boolean {\n return this.runState !== \"idle\" && this.runState !== \"running\";\n }\n\n private cancelled(newMessages: MessageType[], reason: string): AgentRunCancelledError {\n if (this.cancellationError !== undefined) return this.cancellationError;\n const error = new AgentRunCancelledError([...this.chatHistory, ...newMessages], reason);\n this.setCancellationError(error);\n return error;\n }\n\n private linkExternalAbortSignal(signal: AbortSignal | undefined): void {\n if (signal === undefined) return;\n const cancelFromSignal = () => {\n if (this.cancellationError !== undefined || this.isTerminal()) return;\n const cause = abortError(signal.reason);\n const reason = abortReason(signal.reason);\n const messages =\n this.currentMessages.length === 0 ? [this.promptMessage] : [...this.currentMessages];\n this.setCancellationError(\n new AgentRunCancelledError([...this.chatHistory, ...messages], reason, { cause }),\n );\n };\n if (signal.aborted) {\n cancelFromSignal();\n return;\n }\n signal.addEventListener(\"abort\", cancelFromSignal, { once: true });\n this.removeExternalAbortListener = () => signal.removeEventListener(\"abort\", cancelFromSignal);\n }\n\n private throwIfCancelled(): void {\n if (this.cancellationError !== undefined) throw this.cancellationError;\n throwIfAborted(this.abortController.signal);\n }\n\n private normalizeRunError(error: unknown): unknown {\n return this.abortController.signal.aborted && this.cancellationError !== undefined\n ? this.cancellationError\n : error;\n }\n\n private modelCallOptions(): ModelCallOptions {\n return { abortSignal: this.abortController.signal };\n }\n\n private disposeAbortLink(): void {\n this.removeExternalAbortListener?.();\n this.removeExternalAbortListener = undefined;\n }\n}\n\nfunction abortReason(reason: unknown): string {\n if (typeof reason === \"string\" && reason.trim().length > 0) return reason;\n if (reason instanceof Error && reason.message.trim().length > 0) return reason.message;\n return \"External abort signal.\";\n}\n\nfunction normalizeAgentInput(\n agentId: string,\n input: AgentInput,\n): {\n prompt: MessageType;\n history: MessageType[];\n scope?: MemoryScope | undefined;\n continuationState?: AgentContinuationState | undefined;\n interactionResponse?: AgentInteractionResponse | undefined;\n sourceRunId?: string | undefined;\n interactionId?: string | undefined;\n} {\n if (typeof input !== \"object\" || input === null || Array.isArray(input)) {\n throw new TypeError(\"Agent runs require one options object with prompt or messages.\");\n }\n const hasContinuation = \"continuation\" in input && input.continuation !== undefined;\n const hasPrompt = \"prompt\" in input && input.prompt !== undefined;\n const hasMessages = \"messages\" in input && input.messages !== undefined;\n if (Number(hasContinuation) + Number(hasPrompt) + Number(hasMessages) !== 1) {\n throw new TypeError(\"Agent runs require exactly one of prompt, messages, or continuation.\");\n }\n if (hasContinuation) {\n if (!(\"response\" in input) || input.response === undefined) {\n throw new TypeError(\"Agent continuation runs require an interaction response.\");\n }\n if (\"session\" in input && input.session !== undefined) {\n throw new TypeError(\"Agent continuations carry their memory scope and cannot use session.\");\n }\n const continuation = parseAgentContinuation(input.continuation);\n if (continuation.agentId !== agentId) {\n throw new TypeError(\n `Agent continuation belongs to \"${continuation.agentId}\", not \"${agentId}\".`,\n );\n }\n const response = parseAgentInteractionResponse(input.response);\n assertAgentInteractionResponse(continuation.interaction, response);\n const state = parseContinuationState(continuation.state, continuation.interaction);\n let responsePart: ToolInteractionResponsePart;\n if (response.type === \"tool-approval\") {\n responsePart = {\n type: \"tool-approval-response\",\n interactionId: continuation.interaction.id,\n toolCallId: continuation.interaction.toolCallId,\n toolName: continuation.interaction.toolName,\n approved: response.approved,\n };\n if (response.reason !== undefined)\n responsePart = { ...responsePart, reason: response.reason };\n } else {\n responsePart = {\n type: \"tool-question-response\",\n interactionId: continuation.interaction.id,\n toolCallId: continuation.interaction.toolCallId,\n toolName: continuation.interaction.toolName,\n answers: response.answers,\n };\n }\n if (continuation.interaction.callId !== undefined) {\n responsePart = { ...responsePart, callId: continuation.interaction.callId };\n }\n const normalized = {\n prompt: parseMessage({ role: \"tool\", content: [responsePart] }),\n history: [...state.history, ...state.messages],\n continuationState: state,\n interactionResponse: response,\n sourceRunId: continuation.sourceRunId,\n interactionId: continuation.interaction.id,\n };\n if (state.memoryScope !== undefined) {\n Object.assign(normalized, { scope: normalizeMemoryScope(state.memoryScope) });\n }\n return normalized;\n }\n if (hasPrompt) {\n const prompt = input.prompt;\n if (\n typeof prompt !== \"string\" &&\n (typeof prompt !== \"object\" || prompt === null || prompt.role !== \"user\")\n ) {\n throw new TypeError(\"Agent prompt must be text or a user message.\");\n }\n const parsedPrompt = parseMessage(\n typeof prompt === \"string\" ? { role: \"user\", content: prompt } : prompt,\n );\n if (parsedPrompt.role !== \"user\") {\n throw new TypeError(\"Agent prompt must be text or a user message.\");\n }\n const normalized = {\n prompt: parsedPrompt,\n history: [],\n };\n if (input.session !== undefined) {\n Object.assign(normalized, { scope: normalizeMemoryScope(input.session) });\n }\n return normalized;\n }\n if (input.session !== undefined) {\n throw new TypeError(\"Agent messages cannot be combined with a persisted session.\");\n }\n const messages = input.messages;\n if (!Array.isArray(messages) || messages.length === 0) {\n throw new TypeError(\"Agent input transcript must contain at least one message.\");\n }\n const parsedMessages = parseMessages(messages);\n const activePrompt = parsedMessages.at(-1);\n if (activePrompt === undefined) {\n throw new TypeError(\"Agent input transcript must contain at least one message.\");\n }\n if (activePrompt.role !== \"user\") {\n throw new TypeError(\"Agent input transcript must end with a user message.\");\n }\n return {\n prompt: activePrompt,\n history: parsedMessages.slice(0, -1),\n };\n}\n\nfunction normalizeSteeringInput(input: AgentSteerInput): MessageType[] {\n if (typeof input !== \"object\" || input === null || Array.isArray(input)) {\n throw new TypeError(\"Agent steering requires one options object with prompt or messages.\");\n }\n const hasPrompt = \"prompt\" in input && input.prompt !== undefined;\n const hasMessages = \"messages\" in input && input.messages !== undefined;\n if (hasPrompt === hasMessages) {\n throw new TypeError(\"Agent steering requires exactly one of prompt or messages.\");\n }\n if (hasPrompt) {\n const prompt = input.prompt;\n if (\n typeof prompt !== \"string\" &&\n (typeof prompt !== \"object\" || prompt === null || prompt.role !== \"user\")\n ) {\n throw new TypeError(\"Agent steering prompt must be text or a user message.\");\n }\n const parsedPrompt = parseMessage(\n typeof prompt === \"string\" ? { role: \"user\", content: prompt } : prompt,\n );\n if (parsedPrompt.role !== \"user\") {\n throw new TypeError(\"Agent steering prompt must be text or a user message.\");\n }\n return [parsedPrompt];\n }\n const messages = input.messages;\n if (!Array.isArray(messages) || messages.length === 0) {\n throw new TypeError(\"Agent steering messages must contain at least one user message.\");\n }\n const parsedMessages = parseMessages(messages);\n if (parsedMessages.some((message) => message.role !== \"user\")) {\n throw new TypeError(\"Agent steering messages must all be user messages.\");\n }\n return parsedMessages;\n}\n\nfunction normalizeRequestedRunId(runId: string | undefined): string | undefined {\n if (runId === undefined) {\n return undefined;\n }\n if (typeof runId !== \"string\" || runId.trim().length === 0) {\n throw new TypeError(\"runId must be a non-empty string.\");\n }\n return runId;\n}\n\nfunction responseStreamEvents(\n turn: number,\n response: CompletionResponse,\n includeProviderArtifacts = true,\n): AgentStreamEvent[] {\n const events: AgentStreamEvent[] = [];\n for (const item of response.choice) {\n if (item.type === \"text\") {\n if (item.text.length > 0) {\n events.push({ type: \"text_delta\", turn, delta: item.text });\n }\n continue;\n }\n\n if (item.type === \"reasoning\") {\n if (item.details === undefined) {\n if (item.text.length > 0) {\n events.push(reasoningDeltaEvent(turn, item.text, { id: item.id }));\n }\n continue;\n }\n\n for (const content of item.details) {\n const delta =\n content.type === \"encrypted\" || content.type === \"redacted\" ? content.data : content.text;\n events.push(\n reasoningDeltaEvent(turn, delta, {\n id: item.id,\n contentType: content.type,\n signature: content.type === \"text\" ? content.signature : undefined,\n }),\n );\n }\n continue;\n }\n\n if (item.type === \"tool-call\") {\n events.push({ type: \"tool_call\", turn, toolCall: item });\n }\n }\n if (includeProviderArtifacts) {\n for (const source of response.sources ?? []) {\n events.push({ type: \"source\", turn, source });\n }\n for (const toolCall of response.providerToolCalls ?? []) {\n events.push({ type: \"provider_tool_call\", turn, toolCall });\n }\n }\n return events;\n}\n\nfunction generationArtifacts(messages: MessageType[]): {\n sources?: CompletionSource[];\n providerToolCalls?: ProviderToolCall[];\n finishReason?: CompletionFinishReason;\n providerFinishReason?: string;\n contextUsage?: import(\"../../completion/index\").ContextUsage;\n} {\n const sources = new Map<string, CompletionSource>();\n const providerToolCalls = new Map<string, ProviderToolCall>();\n let finishReason: CompletionFinishReason | undefined;\n let providerFinishReason: string | undefined;\n let contextUsage: import(\"../../completion/index\").ContextUsage | undefined;\n for (const message of messages) {\n const metadata = getAssistantGenerationMetadata(message);\n if (metadata !== undefined) {\n finishReason = metadata.finishReason;\n providerFinishReason = metadata.providerFinishReason;\n contextUsage = metadata.contextUsage;\n }\n for (const source of metadata?.sources ?? []) {\n const key = `${source.url}\\u0000${source.startIndex ?? \"\"}\\u0000${source.endIndex ?? \"\"}`;\n sources.set(key, source);\n }\n for (const toolCall of metadata?.providerToolCalls ?? []) {\n providerToolCalls.set(toolCall.id, toolCall);\n }\n }\n const artifacts: {\n sources?: CompletionSource[];\n providerToolCalls?: ProviderToolCall[];\n finishReason?: CompletionFinishReason;\n providerFinishReason?: string;\n contextUsage?: import(\"../../completion/index\").ContextUsage;\n } = {};\n if (sources.size > 0) artifacts.sources = [...sources.values()];\n if (providerToolCalls.size > 0) {\n artifacts.providerToolCalls = [...providerToolCalls.values()];\n }\n if (finishReason !== undefined) artifacts.finishReason = finishReason;\n if (providerFinishReason !== undefined) {\n artifacts.providerFinishReason = providerFinishReason;\n }\n if (contextUsage !== undefined) artifacts.contextUsage = contextUsage;\n return artifacts;\n}\n\ntype ReasoningDeltaEvent = Extract<AgentStreamEvent, { type: \"reasoning_delta\" }>;\n\nfunction reasoningDeltaEvent(\n turn: number,\n delta: string,\n details: {\n id?: ReasoningDeltaEvent[\"id\"] | undefined;\n contentType?: ReasoningDeltaEvent[\"contentType\"] | undefined;\n signature?: ReasoningDeltaEvent[\"signature\"] | undefined;\n } = {},\n): ReasoningDeltaEvent {\n const event: ReasoningDeltaEvent = {\n type: \"reasoning_delta\",\n turn,\n delta,\n };\n if (details.id !== undefined) {\n event.id = details.id;\n }\n if (details.contentType !== undefined) {\n event.contentType = details.contentType;\n }\n if (details.signature !== undefined) {\n event.signature = details.signature;\n }\n return event;\n}\n\nfunction textFromMessage(message: MessageType): string {\n if (message.role === \"system\") {\n return message.content;\n }\n if (typeof message.content === \"string\") {\n return message.content;\n }\n return message.content\n .flatMap((content) => {\n if (content.type === \"text\") {\n return [content.text];\n }\n if (content.type === \"file\" && content.data.type === \"text\") {\n return [content.data.text];\n }\n return [];\n })\n .join(\"\\n\");\n}\n\nfunction latestAssistantText(messages: readonly MessageType[]): string {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index];\n if (message?.role === \"assistant\") {\n return typeof message.content === \"string\"\n ? message.content\n : textFromAssistantContent(message.content);\n }\n }\n return \"\";\n}\n\nfunction structuredOutputRetryRequest(\n request: CompletionRequest,\n response: CompletionResponse,\n error: unknown,\n): StructuredOutputRetryRequest {\n const truncated = error instanceof AgentStructuredOutputError && error.phase === \"truncated\";\n const correction: MessageType = {\n role: \"user\",\n content: truncated ? STRUCTURED_OUTPUT_TRUNCATED_RETRY_PROMPT : STRUCTURED_OUTPUT_RETRY_PROMPT,\n };\n if (truncated) {\n return {\n request: {\n ...request,\n chatHistory: [...request.chatHistory, correction],\n },\n previousResponse: \"omitted\",\n includedOutputLength: 0,\n };\n }\n const preview = structuredOutputRepairPreview(textFromAssistantContent(response.choice));\n if (preview.includedOutputLength === 0) {\n return {\n request: {\n ...request,\n chatHistory: [...request.chatHistory, correction],\n },\n previousResponse: \"omitted\",\n includedOutputLength: 0,\n };\n }\n const invalidResponse: MessageType = {\n role: \"assistant\",\n content: [{ type: \"text\", text: preview.text }],\n };\n return {\n request: {\n ...request,\n chatHistory: [...request.chatHistory, invalidResponse, correction],\n },\n previousResponse: \"preview\",\n includedOutputLength: preview.includedOutputLength,\n };\n}\n\nfunction structuredOutputRetryEventAttributes(\n error: unknown,\n retryRequest: StructuredOutputRetryRequest,\n): JsonObject {\n const attributes: JsonObject = {\n previousResponse: retryRequest.previousResponse,\n includedOutputLength: retryRequest.includedOutputLength,\n };\n if (!(error instanceof AgentStructuredOutputError)) return attributes;\n Object.assign(attributes, {\n failurePhase: error.phase,\n outputLength: error.outputLength,\n normalizedLength: error.normalizedLength,\n attemptUsage: usageEventValue(error.attemptUsage),\n cumulativeUsage: usageEventValue(error.usage),\n });\n if (error.finishReason !== undefined) attributes.finishReason = error.finishReason;\n if (error.providerFinishReason !== undefined) {\n attributes.providerFinishReason = error.providerFinishReason;\n }\n return attributes;\n}\n\nfunction providerOutputRetryEventAttributes(\n error: unknown,\n cumulativeUsage: Usage,\n attemptUsage?: Usage | undefined,\n): JsonObject | undefined {\n const resolvedAttemptUsage = attemptUsage ?? completionProviderOutputErrorUsage(error);\n if (resolvedAttemptUsage === undefined) return undefined;\n return {\n attemptUsage: usageEventValue(resolvedAttemptUsage),\n cumulativeUsage: usageEventValue(cumulativeUsage),\n };\n}\n\nfunction usageEventValue(usage: Usage): JsonObject {\n const value: JsonObject = {\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n totalTokens: usage.totalTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n };\n if (usage.details !== undefined) value.details = { ...usage.details };\n return value;\n}\n\nfunction providerMessages(messages: readonly MessageType[]): MessageType[] {\n const providerMessages: MessageType[] = [];\n for (const message of messages) {\n if (message.role !== \"tool\") {\n providerMessages.push(message);\n continue;\n }\n const results = message.content.filter((part) => part.type === \"tool-result\");\n if (results.length > 0) {\n providerMessages.push({ ...message, content: results });\n }\n }\n return providerMessages;\n}\n\nfunction guardrailDecisionAttributes(decision: GuardrailDecisionRecord): JsonObject {\n const attributes: JsonObject = {\n policyId: decision.policyId,\n guardrailId: decision.guardrailId,\n boundary: decision.boundary,\n mode: decision.mode,\n action: decision.action,\n applied: decision.applied,\n latencyMs: decision.latencyMs,\n };\n if (decision.reason !== undefined) {\n attributes.reason = decision.reason;\n }\n if (decision.message !== undefined) {\n attributes.message = decision.message;\n }\n return attributes;\n}\n\nfunction blockedOutcomeDetails(\n decisions: readonly GuardrailDecisionRecord[],\n fallbackReason: string,\n): { reason: string; message?: string | undefined } {\n for (let index = decisions.length - 1; index >= 0; index -= 1) {\n const decision = decisions[index];\n if (decision?.applied !== true || decision.action !== \"block\") continue;\n return decision.message === undefined\n ? { reason: decision.reason ?? fallbackReason }\n : { reason: decision.reason ?? fallbackReason, message: decision.message };\n }\n return { reason: fallbackReason };\n}\n\nfunction observerRunEnd<Output>(outcome: AgentOutcome<Output>): AgentRunEndArgs {\n const common = {\n runId: outcome.runId,\n text: outcome.text,\n usage: outcome.usage,\n messages: outcome.messages,\n sources: outcome.sources,\n providerToolCalls: outcome.providerToolCalls,\n resumedFrom: outcome.resumedFrom,\n };\n switch (outcome.type) {\n case \"response\":\n return { ...common, status: \"completed\", output: outcome.output };\n case \"blocked\":\n return { ...common, status: \"blocked\", stage: outcome.stage };\n case \"interaction\":\n return { ...common, status: \"suspended\", interaction: outcome.interaction };\n }\n}\n","import type { CompletionModel } from \"../completion\";\nimport type { AgentRun } from \"../internal/agent-runtime/agent-run\";\nimport type {\n AgentOutcome,\n AgentSteerInput,\n AgentSteerReceipt,\n AgentStream,\n AgentStreamEvent,\n} from \"./run-types\";\n\ntype RawResponseOf<Model> =\n Model extends CompletionModel<infer RawResponse> ? RawResponse : unknown;\n\nexport function createAgentStream<Output, M extends CompletionModel>(\n run: AgentRun<Output, M>,\n): AgentStream<Output, RawResponseOf<M>> {\n return new DefaultAgentStream(run);\n}\n\nclass DefaultAgentStream<Output, M extends CompletionModel> implements AgentStream<\n Output,\n RawResponseOf<M>\n> {\n private consuming = false;\n private completed = false;\n private settled = false;\n private drainScheduled = false;\n private readonly resultPromise: Promise<AgentOutcome<Output>>;\n private readonly textPromise: Promise<string>;\n private readonly resolveResult: (result: AgentOutcome<Output>) => void;\n private readonly rejectResult: (error: unknown) => void;\n\n constructor(private readonly run: AgentRun<Output, M>) {\n let resolveResult!: (result: AgentOutcome<Output>) => void;\n let rejectResult!: (error: unknown) => void;\n this.resultPromise = new Promise<AgentOutcome<Output>>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n this.resolveResult = resolveResult;\n this.rejectResult = rejectResult;\n this.textPromise = this.resultPromise.then((result) => result.text);\n void this.resultPromise.catch(() => undefined);\n void this.textPromise.catch(() => undefined);\n }\n\n get events(): AsyncIterable<AgentStreamEvent<Output, RawResponseOf<M>>> {\n return this;\n }\n\n get textStream(): AsyncIterable<string> {\n return {\n [Symbol.asyncIterator]: () => this.consumeText(),\n };\n }\n\n get text(): Promise<string> {\n this.scheduleDrain();\n return this.textPromise;\n }\n\n get result(): Promise<AgentOutcome<Output>> {\n this.scheduleDrain();\n return this.resultPromise;\n }\n\n steer(input: AgentSteerInput): AgentSteerReceipt {\n return this.run.steer(input);\n }\n\n cancel(reason = \"Agent stream cancelled.\"): void {\n this.run.cancel(reason);\n }\n\n [Symbol.asyncIterator](): AsyncIterator<AgentStreamEvent<Output, RawResponseOf<M>>> {\n return this.consume()[Symbol.asyncIterator]();\n }\n\n private async *consume(): AsyncIterableIterator<AgentStreamEvent<Output, RawResponseOf<M>>> {\n if (this.completed) {\n throw new Error(\"Agent stream has already been consumed.\");\n }\n if (this.consuming) {\n throw new Error(\"Agent stream is already running.\");\n }\n this.consuming = true;\n try {\n for await (const event of this.run.events()) {\n if (isAgentOutcome(event)) {\n this.settled = true;\n this.resolveResult(event);\n } else if (event.type === \"error\") {\n this.settled = true;\n this.rejectResult(event.error);\n }\n yield event;\n }\n } finally {\n if (!this.completed) {\n const cancellation = this.run.cancel(\"Agent stream consumer closed the stream.\");\n if (!this.settled && cancellation !== undefined) {\n this.settled = true;\n this.rejectResult(cancellation);\n }\n }\n this.consuming = false;\n this.completed = true;\n }\n }\n\n private async *consumeText(): AsyncIterableIterator<string> {\n for await (const event of this.consume()) {\n if (event.type === \"text_delta\") yield event.delta;\n }\n }\n\n private scheduleDrain(): void {\n if (this.completed || this.consuming || this.drainScheduled) return;\n this.drainScheduled = true;\n queueMicrotask(() => {\n this.drainScheduled = false;\n if (this.completed || this.consuming) return;\n void this.drain();\n });\n }\n\n private async drain(): Promise<void> {\n try {\n for await (const _event of this.consume()) {\n // Accessing a final promise consumes unobserved stream events.\n }\n } catch (error) {\n if (!this.settled) {\n this.settled = true;\n this.rejectResult(error);\n }\n }\n }\n}\n\nfunction isAgentOutcome<Output>(\n event: AgentStreamEvent<Output, unknown>,\n): event is AgentOutcome<Output> {\n return event.type === \"response\" || event.type === \"interaction\" || event.type === \"blocked\";\n}\n","import { z } from \"zod\";\nimport { isStreamingCompletionModel } from \"../completion/generate-completion\";\nimport type { CompletionModel } from \"../completion/index\";\nimport { createTool } from \"../tool/create-tool\";\nimport type { Tool, ToolCallContext, ToolCallStreamEvent } from \"../tool/tool\";\nimport type { Agent } from \"./agent\";\nimport { AgentRunBlockedError, AgentToolSuspensionError } from \"./errors\";\nimport type { AgentToolOptions } from \"./types\";\n\nexport function createAgentTool<Output, M extends CompletionModel, ContextDocument>(\n agent: Agent<Output, M, ContextDocument>,\n options: AgentToolOptions,\n): Tool<{ prompt: string }, Output> {\n if (options.suspension !== \"reject\") {\n throw new TypeError('Agent.asTool() requires suspension: \"reject\".');\n }\n const description =\n options.description ?? agent.description ?? `Prompt the ${options.name} agent.`;\n\n return createTool({\n name: options.name,\n description,\n inputSchema: z.object({\n prompt: z.string().describe(\"The prompt to send to the agent.\"),\n }),\n execute: async ({ prompt }, context: ToolCallContext) => {\n if (\n options.stream === true &&\n context.emitStreamEvent !== undefined &&\n agent.model.capabilities.streaming &&\n isStreamingCompletionModel(agent.model)\n ) {\n let completed = false;\n let output!: Output;\n const childStream = agent.stream({\n prompt,\n maxTurns: options.maxTurns,\n abortSignal: context.abortSignal,\n });\n for await (const event of childStream) {\n const streamEvent: ToolCallStreamEvent = {\n agentId: agent.id,\n event,\n };\n if (agent.name !== undefined) {\n streamEvent.agentName = agent.name;\n }\n await context.emitStreamEvent(streamEvent);\n if (event.type === \"error\") {\n throw event.error;\n }\n if (event.type === \"interaction\") {\n throw new AgentToolSuspensionError(event);\n }\n if (event.type === \"blocked\") {\n throw new AgentRunBlockedError(event);\n }\n if (event.type === \"response\") {\n output = event.output;\n completed = true;\n }\n }\n if (!completed) {\n throw new Error(`Agent tool \"${options.name}\" ended without a final result.`);\n }\n return output;\n }\n const response = await agent.generate({\n prompt,\n maxTurns: options.maxTurns,\n abortSignal: context.abortSignal,\n });\n if (response.type === \"interaction\") {\n throw new AgentToolSuspensionError(response);\n }\n if (response.type === \"blocked\") {\n throw new AgentRunBlockedError(response);\n }\n return response.output;\n },\n });\n}\n","export function normalizeAgentId(id: string): string {\n if (typeof id !== \"string\") {\n throw new TypeError(\"Agent id must be a string.\");\n }\n\n const normalized = id.trim();\n if (normalized.length === 0) {\n throw new TypeError(\"Agent id must be a non-empty string.\");\n }\n\n return normalized;\n}\n","import type { CompletionModel, ProviderTool } from \"../completion\";\nimport { isProviderTool } from \"../completion/types\";\nimport { appendGuardrailPolicies } from \"../guardrails\";\nimport { isMcpTool } from \"../mcp\";\nimport { resolveMemoryOptions } from \"../memory/options\";\nimport { isToolIndex, type ToolIndex } from \"../tool/dynamic-tools\";\nimport type { AnyTool } from \"../tool/tool\";\nimport type { AgentMemory, AgentOptions, ResolvedAgentOptions } from \"./types\";\n\nconst resolvedAgentOptions = Symbol(\"resolvedAgentOptions\");\n\ntype InternalAgentOptions<\n Output,\n M extends CompletionModel,\n ContextDocument,\n> = ResolvedAgentOptions<Output, M, ContextDocument> & {\n [resolvedAgentOptions]: true;\n};\n\nexport function resolveAgentOptions<Output, M extends CompletionModel, ContextDocument>(\n options: AgentOptions<Output, M, ContextDocument>,\n): ResolvedAgentOptions<Output, M, ContextDocument> {\n if (isInternalAgentOptions(options)) {\n return options as unknown as ResolvedAgentOptions<Output, M, ContextDocument>;\n }\n\n const toolsByName = new Map<string, AnyTool>();\n const providerTools: ProviderTool[] = [];\n const toolIndexes: ToolIndex[] = [];\n for (const tool of options.tools ?? []) {\n if (isProviderTool(tool)) {\n providerTools.push(tool);\n } else if (isToolIndex(tool)) {\n toolIndexes.push(tool);\n } else if ((tool as { kind?: unknown }).kind === \"tool-index\") {\n throw new TypeError(\"Invalid tool index: search, tools, and a numeric topK are required.\");\n } else if (isMcpTool(tool)) {\n throw new TypeError(\n `MCP tool \"${tool.name}\" must be registered through Agent.mcpServers, not Agent.tools.`,\n );\n } else {\n addUniqueTool(toolsByName, tool, \"local tool\");\n }\n }\n if (options.skills !== undefined) {\n for (const tool of options.skills.tools) {\n if (isMcpTool(tool)) {\n throw new TypeError(\n `MCP tool \"${tool.name}\" must be registered through Agent.mcpServers, not Agent.skills.`,\n );\n }\n addUniqueTool(toolsByName, tool, \"skill tool\");\n }\n }\n const memory = resolveAgentMemory(options);\n const instructions = [options.instructions, options.skills?.instructions]\n .filter((part): part is string => part !== undefined && part.length > 0)\n .join(\"\\n\\n\");\n\n return {\n id: options.id,\n name: options.name,\n description: options.description,\n model: options.model,\n instructions: instructions.length === 0 ? undefined : instructions,\n context: [...(options.context ?? [])],\n temperature: options.temperature,\n maxTokens: options.maxTokens,\n providerOptions: options.providerOptions,\n retries: options.retries,\n tools: [...toolsByName.values()],\n mcpServers: [...(options.mcpServers ?? [])],\n providerTools,\n toolIndexes,\n toolChoice: options.toolChoice,\n defaultMaxTurns: options.maxTurns,\n lifecycle: options.lifecycle,\n outputSchema: options.outputSchema,\n observability: options.observability,\n guardrails:\n options.guardrails === undefined ? [] : appendGuardrailPolicies([], options.guardrails),\n middlewares: [...(options.middlewares ?? [])],\n memory,\n };\n}\n\nexport function markResolvedAgentOptions<Output, M extends CompletionModel, ContextDocument>(\n options: ResolvedAgentOptions<Output, M, ContextDocument>,\n): AgentOptions<Output, M, ContextDocument> {\n return {\n ...options,\n [resolvedAgentOptions]: true,\n } as unknown as AgentOptions<Output, M, ContextDocument>;\n}\n\nfunction isInternalAgentOptions<Output, M extends CompletionModel, ContextDocument>(\n options: AgentOptions<Output, M, ContextDocument>,\n): boolean {\n return (\n (options as unknown as Partial<InternalAgentOptions<Output, M, ContextDocument>>)[\n resolvedAgentOptions\n ] === true\n );\n}\n\nfunction resolveAgentMemory<Output, M extends CompletionModel, ContextDocument>(\n options: AgentOptions<Output, M, ContextDocument>,\n): AgentMemory | undefined {\n if (options.memory === undefined) {\n return undefined;\n }\n const { store, ...memoryOptions } = options.memory;\n const resolvedOptions = resolveMemoryOptions(memoryOptions);\n if (resolvedOptions.compaction !== undefined && store.compaction === undefined) {\n throw new TypeError(\n \"Memory compaction requires a store with the optional compaction capability.\",\n );\n }\n return { store, ...resolvedOptions };\n}\n\nfunction addUniqueTool(tools: Map<string, AnyTool>, tool: AnyTool, source: string): void {\n if (tools.has(tool.name)) {\n throw new TypeError(`Duplicate ${source} name \"${tool.name}\".`);\n }\n tools.set(tool.name, tool);\n}\n","import type { GuardrailPolicy } from \"../guardrails\";\nimport { assertFiniteMinScore, assertPositiveSearchLimit } from \"../internal/vector-search-options\";\nimport type { AgentObservabilityOptions, AgentObserverMap } from \"../observability\";\nimport type { VectorSearchResult } from \"../vector-store\";\nimport type { AgentContextInput, AgentMemory } from \"./types\";\nimport {\n isVectorContext,\n type VectorContext,\n type VectorContextBaseOptions,\n} from \"./vector-context\";\n\nexport function snapshotAgentContext<T>(\n inputs: readonly AgentContextInput<T>[] | undefined,\n): readonly AgentContextInput<T>[] {\n const context = (inputs ?? []).map(snapshotContextInput);\n for (const input of context) {\n if (!isVectorContext(input)) continue;\n assertPositiveSearchLimit(input.topK);\n assertFiniteMinScore(input.minScore);\n }\n return Object.freeze(context);\n}\n\nexport function snapshotAgentObservability(\n observability: AgentObservabilityOptions | undefined,\n): AgentObservabilityOptions | undefined {\n if (observability === undefined) return undefined;\n const observers: Record<string, AgentObserverMap[string]> = {};\n for (const [name, observer] of Object.entries(observability.observers)) {\n if (name.trim().length === 0) {\n throw new TypeError(\"Agent observer names must not be empty.\");\n }\n if (\n typeof observer !== \"object\" ||\n observer === null ||\n typeof observer.startRun !== \"function\"\n ) {\n throw new TypeError(`Agent observer \"${name}\" must implement startRun().`);\n }\n observers[name] = observer;\n }\n if (observability.primaryTrace !== undefined && !(observability.primaryTrace in observers)) {\n throw new TypeError(\n `Agent primaryTrace \"${observability.primaryTrace}\" must name a configured observer.`,\n );\n }\n const errorPolicy = observability.errorPolicy ?? \"ignore\";\n if (errorPolicy !== \"ignore\" && errorPolicy !== \"throw\") {\n throw new TypeError('Agent observability.errorPolicy must be \"ignore\" or \"throw\".');\n }\n let snapshot: AgentObservabilityOptions = {\n observers: Object.freeze(observers),\n errorPolicy,\n };\n if (observability.primaryTrace !== undefined) {\n snapshot = { ...snapshot, primaryTrace: observability.primaryTrace };\n }\n return Object.freeze(snapshot);\n}\n\nexport function snapshotGuardrailPolicies(\n policies: readonly GuardrailPolicy[] | undefined,\n): readonly GuardrailPolicy[] {\n return Object.freeze((policies ?? []).map(snapshotGuardrailPolicy));\n}\n\nexport function snapshotAgentMemory(memory: AgentMemory | undefined): AgentMemory | undefined {\n if (memory === undefined) {\n return undefined;\n }\n const compaction =\n memory.compaction === undefined\n ? undefined\n : Object.freeze({\n ...memory.compaction,\n trigger: Object.freeze({ ...memory.compaction.trigger }),\n retention: Object.freeze({ ...memory.compaction.retention }),\n conflictRetries:\n memory.compaction.conflictRetries === false\n ? false\n : Object.freeze({ ...memory.compaction.conflictRetries }),\n });\n let snapshot: AgentMemory = {\n store: memory.store,\n savePolicy: memory.savePolicy,\n };\n if (compaction !== undefined) {\n snapshot = { ...snapshot, compaction };\n }\n return Object.freeze(snapshot);\n}\n\nexport function cloneFrozenPlainData<T>(value: T): T {\n if (Array.isArray(value)) {\n return Object.freeze(value.map(cloneFrozenPlainData)) as T;\n }\n if (typeof value !== \"object\" || value === null) {\n return value;\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n return value;\n }\n const clone = Object.fromEntries(\n Object.entries(value).map(([key, item]) => [key, cloneFrozenPlainData(item)]),\n );\n return Object.freeze(clone) as T;\n}\n\nfunction snapshotContextInput<T>(input: AgentContextInput<T>): AgentContextInput<T> {\n if (!isVectorContext(input)) {\n let document: AgentContextInput<T> = {\n id: input.id,\n text: input.text,\n };\n if (input.additionalProps !== undefined) {\n document = {\n ...document,\n additionalProps: cloneFrozenPlainData(input.additionalProps),\n };\n }\n return Object.freeze(document);\n }\n const format = input.format;\n let shared: VectorContextBaseOptions<T> & {\n kind: \"vector-context\";\n store: VectorContext<T>[\"store\"];\n } = {\n kind: \"vector-context\" as const,\n store: input.store,\n topK: input.topK,\n };\n if (input.minScore !== undefined) {\n shared = { ...shared, minScore: input.minScore };\n }\n if (input.filter !== undefined) {\n shared = { ...shared, filter: cloneFrozenPlainData(input.filter) };\n }\n if (input.retries !== undefined) {\n shared = { ...shared, retries: cloneFrozenPlainData(input.retries) };\n }\n if (format !== undefined) {\n shared = {\n ...shared,\n format: (result: VectorSearchResult<T>) => format.call(input, result),\n };\n }\n if (!(\"models\" in input) || input.models === undefined) {\n return Object.freeze<VectorContext<T>>({ ...shared, store: input.store, model: input.model });\n }\n let context: VectorContext<T> = {\n ...shared,\n store: input.store,\n models: input.models,\n };\n if (input.fusion !== undefined) {\n context = { ...context, fusion: input.fusion };\n }\n return Object.freeze(context);\n}\n\nfunction snapshotGuardrailPolicy(policy: GuardrailPolicy): GuardrailPolicy {\n return Object.freeze({\n ...policy,\n input: Object.freeze([...policy.input]),\n output: Object.freeze([...policy.output]),\n }) as GuardrailPolicy;\n}\n","import type { JsonValue, ProviderTool } from \"../completion\";\nimport { assertFiniteMinScore, assertPositiveSearchLimit } from \"../internal/vector-search-options\";\nimport { isMcpTool, type McpServer } from \"../mcp\";\nimport { isToolIndex, type ToolIndex } from \"../tool/dynamic-tools\";\nimport type { AnyTool, ToolCallContext } from \"../tool/tool\";\nimport type { VectorInspectRequest } from \"../vector-store\";\nimport { cloneFrozenPlainData } from \"./snapshot\";\nimport type { AgentToolState } from \"./tool-state\";\nimport type { ResolvedAgentOptions } from \"./types\";\n\nexport type PreparedAgentTools = {\n mcpServers: readonly McpServer[];\n tools: readonly AnyTool[];\n publicState: AgentToolState;\n toolsByName: Map<string, AnyTool>;\n};\n\nexport function prepareAgentTools(\n options: Pick<ResolvedAgentOptions, \"tools\" | \"mcpServers\" | \"providerTools\" | \"toolIndexes\">,\n): PreparedAgentTools {\n assertUniqueMcpServerNames(options.mcpServers ?? []);\n const mcpServers = Object.freeze((options.mcpServers ?? []).map(snapshotMcpServer));\n const configuredTools = [...(options.tools ?? [])];\n const staticTools = [...configuredTools, ...mcpServers.flatMap((server) => server.tools)];\n const toolIndexes = (options.toolIndexes ?? []).map(snapshotToolIndex);\n const providerTools = (options.providerTools ?? []).map(snapshotProviderTool);\n assertUniqueAgentToolNames({ staticTools, providerTools, toolIndexes });\n\n const toolsByName = new Map(staticTools.map((tool) => [tool.name, tool]));\n for (const index of toolIndexes) {\n for (const tool of index.tools) {\n toolsByName.set(tool.name, tool);\n }\n }\n const tools = Object.freeze([...toolsByName.values()]);\n const publicState = Object.freeze({\n configuredTools: Object.freeze(configuredTools),\n staticTools: Object.freeze(staticTools),\n providerTools: Object.freeze(providerTools),\n toolIndexes: Object.freeze(toolIndexes),\n });\n return { mcpServers, tools, publicState, toolsByName };\n}\n\nfunction assertUniqueAgentToolNames(options: {\n staticTools: readonly AnyTool[];\n providerTools: readonly ProviderTool[];\n toolIndexes: readonly ToolIndex[];\n}): void {\n const owners = new Map<string, string>();\n for (const tool of options.staticTools) {\n registerToolOwner(owners, tool.name, isMcpTool(tool) ? \"MCP tool\" : \"local or skill tool\");\n }\n for (const tool of options.providerTools) {\n registerToolOwner(owners, tool.name, \"provider tool\");\n }\n for (const [indexPosition, index] of options.toolIndexes.entries()) {\n if (!isToolIndex(index)) {\n throw new TypeError(\"Invalid tool index: search, tools, and a numeric topK are required.\");\n }\n assertPositiveSearchLimit(index.topK);\n assertFiniteMinScore(index.minScore);\n for (const tool of index.tools) {\n if (isMcpTool(tool)) {\n throw new TypeError(\n `MCP tool \"${tool.name}\" must be registered through Agent.mcpServers, not a tool index.`,\n );\n }\n registerToolOwner(owners, tool.name, `tool index ${indexPosition + 1}`);\n }\n }\n}\n\nfunction registerToolOwner(owners: Map<string, string>, name: string, owner: string): void {\n const existing = owners.get(name);\n if (existing !== undefined) {\n throw new TypeError(\n `Tool name collision for \"${name}\" between ${existing} and ${owner}. Tool names must be unique across every Agent tool source.`,\n );\n }\n owners.set(name, owner);\n}\n\nfunction snapshotProviderTool(tool: ProviderTool): ProviderTool {\n let snapshot: ProviderTool = {\n ...tool,\n };\n if (tool.configuration !== undefined) {\n snapshot = { ...snapshot, configuration: cloneFrozenPlainData(tool.configuration) };\n }\n return Object.freeze(snapshot);\n}\n\nfunction snapshotMcpServer(server: McpServer): McpServer {\n if (server.name.trim() === \"\") {\n throw new TypeError(\"MCP server name must not be empty.\");\n }\n for (const tool of server.tools) {\n if (!isMcpTool(tool)) {\n throw new TypeError(`MCP server \"${server.name}\" contains an invalid MCP tool.`);\n }\n if (tool.mcp.serverName !== server.name) {\n throw new TypeError(\n `MCP tool \"${tool.name}\" belongs to server \"${tool.mcp.serverName}\", not \"${server.name}\".`,\n );\n }\n }\n const tools = server.tools.map(snapshotMcpTool);\n let snapshot: McpServer = {\n name: server.name,\n tools: Object.freeze(tools),\n };\n if (server.serverInfo !== undefined) {\n snapshot = { ...snapshot, serverInfo: cloneFrozenPlainData(server.serverInfo) };\n }\n if (server.capabilities !== undefined) {\n snapshot = { ...snapshot, capabilities: cloneFrozenPlainData(server.capabilities) };\n }\n if (server.instructions !== undefined) {\n snapshot = { ...snapshot, instructions: server.instructions };\n }\n return Object.freeze(snapshot);\n}\n\nfunction snapshotMcpTool(tool: McpServer[\"tools\"][number]): McpServer[\"tools\"][number] {\n if (Object.isFrozen(tool) && Object.isFrozen(tool.mcp)) {\n return tool;\n }\n const parseInput = tool.parseInput;\n let snapshot: McpServer[\"tools\"][number] = {\n name: tool.name,\n mcp: Object.freeze({ ...tool.mcp }),\n definition: (prompt: string) => tool.definition(prompt),\n call: (args: unknown, context?: ToolCallContext) => tool.call(args, context),\n };\n if (tool.requiresApproval !== undefined) {\n snapshot = { ...snapshot, requiresApproval: tool.requiresApproval };\n }\n if (parseInput !== undefined) {\n snapshot = {\n ...snapshot,\n parseInput: (args: JsonValue) => parseInput.call(tool, args),\n };\n }\n return Object.freeze(snapshot);\n}\n\nfunction assertUniqueMcpServerNames(servers: readonly McpServer[]): void {\n const names = new Set<string>();\n for (const server of servers) {\n if (names.has(server.name)) {\n throw new TypeError(`Duplicate MCP server name \"${server.name}\".`);\n }\n names.add(server.name);\n }\n}\n\nfunction snapshotToolIndex(index: ToolIndex): ToolIndex {\n const inspect = index.inspect;\n let snapshot: ToolIndex = {\n kind: \"tool-index\" as const,\n tools: Object.freeze([...index.tools]),\n topK: index.topK,\n search: (options: { query: string; abortSignal?: AbortSignal | undefined }) =>\n index.search(options),\n };\n if (index.minScore !== undefined) {\n snapshot = { ...snapshot, minScore: index.minScore };\n }\n if (index.filter !== undefined) {\n snapshot = { ...snapshot, filter: cloneFrozenPlainData(index.filter) };\n }\n if (inspect !== undefined) {\n snapshot = {\n ...snapshot,\n inspect: (request: VectorInspectRequest) => inspect.call(index, request),\n };\n }\n return Object.freeze(snapshot);\n}\n","import { isStreamingCompletionModel } from \"../completion/generate-completion\";\nimport type { CompletionModel, JsonObject, ToolChoice } from \"../completion/index\";\nimport type { GuardrailPolicy } from \"../guardrails\";\nimport { AgentRun } from \"../internal/agent-runtime/agent-run\";\nimport { AgentRunMemory } from \"../internal/agent-runtime/memory\";\nimport { normalizeMemoryScope } from \"../internal/agent-runtime/memory-scope\";\nimport { prepareToolCall } from \"../internal/agent-runtime/prepared-tool-call\";\nimport { assertNonnegativeSafeInteger } from \"../internal/agent-runtime/run-validation\";\nimport { assertJsonObject } from \"../internal/json-object\";\nimport type { McpServer } from \"../mcp\";\nimport type { MemoryCompactionResult } from \"../memory\";\nimport type { AgentObservabilityOptions } from \"../observability\";\nimport type { RetrySetting } from \"../retry\";\nimport type { ZodSchema } from \"../schema/zod-schema\";\nimport { ToolNotFoundError } from \"../tool/errors\";\nimport type { AgentMiddleware } from \"../tool/middleware\";\nimport type { AnyTool, NormalizedToolOutput, Tool, ToolCallContext } from \"../tool/tool\";\nimport { createAgentStream } from \"./agent-stream\";\nimport { createAgentTool } from \"./agent-tool\";\nimport { normalizeAgentId } from \"./ids\";\nimport type { AgentContinuation, AgentInteractionResponse } from \"./interactions\";\nimport type { AgentLifecycle } from \"./lifecycle\";\nimport { registerAgentProviderOutputSchema } from \"./output-schema\";\nimport { resolveAgentOptions } from \"./resolve-options\";\nimport type {\n AgentMemoryCompactionOptions,\n AgentOutcome,\n AgentRunOptions,\n AgentRunSettings,\n AgentStream,\n} from \"./run-types\";\nimport {\n cloneFrozenPlainData,\n snapshotAgentContext,\n snapshotAgentMemory,\n snapshotAgentObservability,\n snapshotGuardrailPolicies,\n} from \"./snapshot\";\nimport { prepareAgentTools } from \"./tool-catalog\";\nimport { getRegisteredAgentTool, registerAgentToolState } from \"./tool-state\";\nimport type { AgentContextInput, AgentMemory, AgentOptions, AgentToolOptions } from \"./types\";\n\nconst DEFAULT_MAX_TURNS = 20;\n\ntype RawResponseOf<Model> =\n Model extends CompletionModel<infer RawResponse> ? RawResponse : unknown;\n\nexport class Agent<\n Output = string,\n M extends CompletionModel = CompletionModel,\n ContextDocument = unknown,\n> {\n readonly id: string;\n readonly name: string | undefined;\n readonly description: string | undefined;\n readonly model: M;\n readonly instructions: string | undefined;\n readonly context: readonly AgentContextInput<ContextDocument>[];\n readonly temperature: number | undefined;\n readonly maxTokens: number | undefined;\n readonly providerOptions: JsonObject | undefined;\n readonly retries: RetrySetting | undefined;\n readonly mcpServers: readonly McpServer[];\n readonly tools: readonly AnyTool[];\n readonly toolChoice: ToolChoice | undefined;\n readonly defaultMaxTurns: number | undefined;\n readonly lifecycle: AgentLifecycle<Output, RawResponseOf<M>> | undefined;\n readonly outputSchema: ZodSchema<Output> | undefined;\n readonly observability: AgentObservabilityOptions | undefined;\n readonly guardrails: readonly GuardrailPolicy[];\n readonly middlewares: readonly AgentMiddleware[];\n readonly memory: AgentMemory | undefined;\n\n constructor(options: AgentOptions<Output, M, ContextDocument>) {\n const resolved = resolveAgentOptions(options);\n this.id = normalizeAgentId(resolved.id);\n this.name = resolved.name;\n this.description = resolved.description;\n this.model = resolved.model;\n this.instructions = resolved.instructions;\n this.context = snapshotAgentContext(resolved.context);\n this.temperature = resolved.temperature;\n this.maxTokens = resolved.maxTokens;\n if (resolved.providerOptions !== undefined) {\n assertJsonObject(resolved.providerOptions, \"Agent providerOptions\");\n }\n this.providerOptions = cloneFrozenPlainData(resolved.providerOptions);\n this.retries = cloneFrozenPlainData(resolved.retries);\n\n const preparedTools = prepareAgentTools(resolved);\n this.mcpServers = preparedTools.mcpServers;\n this.tools = preparedTools.tools;\n registerAgentToolState(this, preparedTools.publicState, preparedTools.toolsByName);\n\n this.toolChoice = cloneFrozenPlainData(resolved.toolChoice);\n this.defaultMaxTurns = assertNonnegativeSafeInteger(\n resolved.defaultMaxTurns ?? DEFAULT_MAX_TURNS,\n \"maxTurns\",\n );\n this.lifecycle = resolved.lifecycle;\n this.outputSchema = resolved.outputSchema;\n registerAgentProviderOutputSchema(this, resolved.outputSchema);\n this.observability = snapshotAgentObservability(resolved.observability);\n this.guardrails = snapshotGuardrailPolicies(resolved.guardrails);\n this.middlewares = Object.freeze([...(resolved.middlewares ?? [])]);\n this.memory = snapshotAgentMemory(resolved.memory);\n }\n\n generate(options: AgentRunOptions<Output, RawResponseOf<M>>): Promise<AgentOutcome<Output>> {\n return AgentRun.fromAgent(this, options).generate();\n }\n\n resume(\n continuation: AgentContinuation,\n response: AgentInteractionResponse,\n settings: AgentRunSettings<Output, RawResponseOf<M>> = {},\n ): Promise<AgentOutcome<Output>> {\n return this.generate({ continuation, response, ...settings });\n }\n\n stream(\n options: AgentRunOptions<Output, RawResponseOf<M>>,\n ): AgentStream<Output, RawResponseOf<M>> {\n const run = AgentRun.fromAgent(this, options);\n if (!this.model.capabilities.streaming || !isStreamingCompletionModel(this.model)) {\n throw new Error(\"This completion model does not support streaming\");\n }\n return createAgentStream(run);\n }\n\n compactMemory(options: AgentMemoryCompactionOptions): Promise<MemoryCompactionResult> {\n if (typeof options !== \"object\" || options === null || Array.isArray(options)) {\n throw new TypeError(\"Manual memory compaction requires an options object.\");\n }\n const scope = normalizeMemoryScope(options.session, \"Manual memory compaction\");\n const memory = new AgentRunMemory(this, scope, []);\n return memory.compact(\n `manual-memory-compaction:${globalThis.crypto.randomUUID()}`,\n options.abortSignal,\n );\n }\n\n asTool(options: AgentToolOptions): Tool<{ prompt: string }, Output> {\n return createAgentTool(this, options);\n }\n\n getTool(toolName: string): AnyTool | undefined {\n return getRegisteredAgentTool(this, toolName);\n }\n\n async callTool(\n toolName: string,\n args: string,\n context?: ToolCallContext,\n ): Promise<NormalizedToolOutput> {\n const tool = this.getTool(toolName);\n if (tool === undefined) {\n throw new ToolNotFoundError(toolName);\n }\n return prepareToolCall(tool, args).call(context ?? {});\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,IAAM,kBAAkB,oBAAI,QAAsC;AAE3D,SAAS,uBACd,OACA,aACA,aACM;AACN,kBAAgB,IAAI,OAAO,EAAE,aAAa,YAAY,CAAC;AACzD;AAEO,SAAS,kBAAkB,OAA+B;AAC/D,SAAO,wBAAwB,KAAK,EAAE;AACxC;AAEO,SAAS,uBAAuB,OAAe,UAAuC;AAC3F,SAAO,wBAAwB,KAAK,EAAE,YAAY,IAAI,QAAQ;AAChE;AAEA,SAAS,wBAAwB,OAAqC;AACpE,QAAM,QAAQ,gBAAgB,IAAI,KAAK;AACvC,MAAI,UAAU,QAAW;AACvB,UAAM,IAAI,UAAU,kCAAkC;AAAA,EACxD;AACA,SAAO;AACT;;;AC/BO,SAAS,WACd,MACwB;AACxB,SAAO;AACT;AAEO,SAAS,UAAU,QAA4B;AACpD,SAAO,EAAE,MAAM,aAAa,OAAO;AACrC;AAEO,SAAS,SAAS,QAAoC;AAC3D,SAAO,EAAE,MAAM,QAAQ,OAAO;AAChC;AAEO,SAAS,oBAAoB,UAAsC,CAAC,GAAuB;AAChG,QAAM,SAA6B;AAAA,IACjC,MAAM;AAAA,EACR;AACA,MAAI,QAAQ,WAAW,QAAW;AAChC,WAAO,SAAS,QAAQ;AAAA,EAC1B;AACA,MAAI,QAAQ,kBAAkB,QAAW;AACvC,WAAO,gBAAgB,QAAQ;AAAA,EACjC;AACA,SAAO;AACT;AAEO,IAAM,aAAyB;AAAA,EACpC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