@anvia/core 0.26.0 → 1.0.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -11
- package/dist/agent/index.d.ts +26 -68
- package/dist/agent/index.js +20 -17
- package/dist/agent-DGYY_onS.d.ts +145 -0
- package/dist/audio-generation/index.d.ts +12 -14
- package/dist/audio-generation/index.js +5 -39
- package/dist/audio-generation/index.js.map +1 -1
- package/dist/{chunk-MRQLEK2B.js → chunk-5XKDW36Z.js} +30 -7
- package/dist/chunk-5XKDW36Z.js.map +1 -0
- package/dist/chunk-6WGGTJE6.js +139 -0
- package/dist/chunk-6WGGTJE6.js.map +1 -0
- package/dist/chunk-A3UBYTJT.js +157 -0
- package/dist/chunk-A3UBYTJT.js.map +1 -0
- package/dist/{chunk-NCPN4SJR.js → chunk-DMPUP4R3.js} +10 -10
- package/dist/chunk-DMPUP4R3.js.map +1 -0
- package/dist/{chunk-MNWK2USR.js → chunk-DZ3CKYTH.js} +29 -5
- package/dist/chunk-DZ3CKYTH.js.map +1 -0
- package/dist/{chunk-CWUJUSOS.js → chunk-FNQB2JEH.js} +1 -1
- package/dist/chunk-FNQB2JEH.js.map +1 -0
- package/dist/chunk-I6G7BC42.js +41 -0
- package/dist/chunk-I6G7BC42.js.map +1 -0
- package/dist/{chunk-BALBBVI3.js → chunk-IL3ZSNJI.js} +2720 -1704
- package/dist/chunk-IL3ZSNJI.js.map +1 -0
- package/dist/chunk-J6GNQART.js +122 -0
- package/dist/chunk-J6GNQART.js.map +1 -0
- package/dist/{chunk-MC3CCKEB.js → chunk-M3IOWB4Y.js} +124 -65
- package/dist/chunk-M3IOWB4Y.js.map +1 -0
- package/dist/chunk-QY5GZ7HR.js +39 -0
- package/dist/chunk-QY5GZ7HR.js.map +1 -0
- package/dist/{chunk-MELYDKWQ.js → chunk-R2LJSQUW.js} +190 -20
- package/dist/chunk-R2LJSQUW.js.map +1 -0
- package/dist/{chunk-WQKHFADH.js → chunk-RFDVKCIE.js} +3 -3
- package/dist/chunk-RFDVKCIE.js.map +1 -0
- package/dist/chunk-RMUBRRSK.js +34 -0
- package/dist/chunk-RMUBRRSK.js.map +1 -0
- package/dist/{chunk-I6XOQ4LK.js → chunk-RXKHOYEH.js} +1 -1
- package/dist/chunk-RXKHOYEH.js.map +1 -0
- package/dist/chunk-XDRSPSR7.js +38 -0
- package/dist/chunk-XDRSPSR7.js.map +1 -0
- package/dist/completion/index.d.ts +5 -36
- package/dist/completion/index.js +4 -5
- package/dist/dynamic-tools-i9woysFa.d.ts +33 -0
- package/dist/embeddings/index.d.ts +2 -2
- package/dist/embeddings/index.js +1 -2
- package/dist/{errors-2moLDuuN.d.ts → errors-CYKUcU89.d.ts} +2 -2
- package/dist/evals/index.d.ts +22 -15
- package/dist/evals/index.js +57 -35
- package/dist/evals/index.js.map +1 -1
- package/dist/extractor/index.d.ts +23 -35
- package/dist/extractor/index.js +7 -21
- package/dist/guardrails/index.d.ts +2 -2
- package/dist/guardrails/index.js +1 -1
- package/dist/image-generation/index.d.ts +12 -14
- package/dist/image-generation/index.js +5 -39
- package/dist/image-generation/index.js.map +1 -1
- package/dist/index-DxB74ybJ.d.ts +349 -0
- package/dist/index.d.ts +20 -17
- package/dist/index.js +31 -36
- package/dist/internal/agent.d.ts +152 -9
- package/dist/internal/agent.js +22 -17
- package/dist/{json-BVPssigK.d.ts → json-Zo7K3xmt.d.ts} +12 -11
- package/dist/loaders/index.d.ts +5 -10
- package/dist/loaders/index.js.map +1 -1
- package/dist/mcp/index.d.ts +4 -4
- package/dist/mcp/index.js.map +1 -1
- package/dist/memory/index.d.ts +4 -4
- package/dist/memory/index.js +6 -7
- package/dist/middleware-KynLg_RW.d.ts +56 -0
- package/dist/observability/index.d.ts +6 -3
- package/dist/observability/index.js.map +1 -1
- package/dist/pipeline/index.d.ts +40 -47
- package/dist/pipeline/index.js +99 -99
- package/dist/pipeline/index.js.map +1 -1
- package/dist/retry-D3Ruy-ba.d.ts +15 -0
- package/dist/skills/index.d.ts +4 -4
- package/dist/skills/index.js +5 -6
- package/dist/streaming/index.js +37 -3
- package/dist/streaming/index.js.map +1 -1
- package/dist/{think-tool-DfCMuO8e.d.ts → think-tool-DZqZj2LV.d.ts} +5 -5
- package/dist/tool/index.d.ts +8 -6
- package/dist/tool/index.js +12 -15
- package/dist/tool-C_8GudXn.d.ts +49 -0
- package/dist/transcription/index.d.ts +14 -16
- package/dist/transcription/index.js +5 -57
- package/dist/transcription/index.js.map +1 -1
- package/dist/type-utils-CtHVDRn_.d.ts +6 -0
- package/dist/{types-G12i56s2.d.ts → types-B3A4YxaA.d.ts} +1 -1
- package/dist/{types-BrLbKnEz.d.ts → types-BBEGKB9m.d.ts} +1 -1
- package/dist/{types-O-abTIin.d.ts → types-DT3nEemY.d.ts} +3 -3
- package/dist/{types-04LqWrmy.d.ts → types-DhQfwiZn.d.ts} +1 -1
- package/dist/{types-JJCxRnaZ.d.ts → types-DulRCYdB.d.ts} +2 -2
- package/dist/{types-BCTRUGex.d.ts → types-p55Jc-sr.d.ts} +1 -1
- package/dist/ui/index.d.ts +1 -1
- package/dist/ui/index.js +1 -1
- package/dist/vector-store/index.d.ts +5 -5
- package/dist/vector-store/index.js +4 -4
- package/package.json +2 -10
- package/dist/agent-x3YTyv5i.d.ts +0 -222
- package/dist/chunk-2ODTMRHP.js +0 -54
- package/dist/chunk-2ODTMRHP.js.map +0 -1
- package/dist/chunk-BALBBVI3.js.map +0 -1
- package/dist/chunk-CWUJUSOS.js.map +0 -1
- package/dist/chunk-DALYP4PX.js +0 -225
- package/dist/chunk-DALYP4PX.js.map +0 -1
- package/dist/chunk-HYUYZEAJ.js +0 -223
- package/dist/chunk-HYUYZEAJ.js.map +0 -1
- package/dist/chunk-I6XOQ4LK.js.map +0 -1
- package/dist/chunk-JI5YZWNT.js +0 -220
- package/dist/chunk-JI5YZWNT.js.map +0 -1
- package/dist/chunk-MC3CCKEB.js.map +0 -1
- package/dist/chunk-MELYDKWQ.js.map +0 -1
- package/dist/chunk-MNWK2USR.js.map +0 -1
- package/dist/chunk-MRQLEK2B.js.map +0 -1
- package/dist/chunk-NCPN4SJR.js.map +0 -1
- package/dist/chunk-OIMLU4SF.js +0 -20
- package/dist/chunk-OIMLU4SF.js.map +0 -1
- package/dist/chunk-Q25IWLBT.js +0 -138
- package/dist/chunk-Q25IWLBT.js.map +0 -1
- package/dist/chunk-UQX6EXWG.js +0 -33
- package/dist/chunk-UQX6EXWG.js.map +0 -1
- package/dist/chunk-WQKHFADH.js.map +0 -1
- package/dist/chunk-XUUY2L2D.js +0 -42
- package/dist/chunk-XUUY2L2D.js.map +0 -1
- package/dist/chunk-YLMDBQO4.js +0 -141
- package/dist/chunk-YLMDBQO4.js.map +0 -1
- package/dist/hooks/index.d.ts +0 -12
- package/dist/hooks/index.js +0 -17
- package/dist/hooks/index.js.map +0 -1
- package/dist/index-BxSbmOMr.d.ts +0 -257
- package/dist/middleware-Dp3d_pxi.d.ts +0 -90
- package/dist/request/index.d.ts +0 -28
- package/dist/request/index.js +0 -25
- package/dist/request/index.js.map +0 -1
- package/dist/tool-Cohdv5GC.d.ts +0 -65
- package/dist/types-D9JpeAPF.d.ts +0 -114
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agent/errors.ts","../src/agent/tool-state.ts","../src/hooks/control.ts","../src/internal/agent-runtime/approval-details.ts","../src/agent/context-index.ts","../src/internal/agent-runtime/run-options.ts","../src/agent/agent.ts","../src/agent/lifecycle.ts","../src/observability/snapshot.ts","../src/observability/group.ts","../src/internal/async-queue.ts","../src/internal/rag-text.ts","../src/internal/agent-runtime/memory.ts","../src/internal/agent-runtime/retrieval.ts","../src/internal/agent-runtime/run-validation.ts","../src/internal/agent-runtime/stream-accumulator.ts","../src/internal/agent-runtime/stream-events.ts","../src/internal/agent-runtime/tool-execution.ts","../src/internal/agent-runtime/agent-run.ts","../src/agent/ids.ts"],"sourcesContent":["import type { Message } from \"../completion/index\";\n\nexport class MaxTurnsError extends Error {\n constructor(\n readonly maxTurns: number,\n readonly chatHistory: Message[],\n readonly prompt: Message,\n ) {\n super(`Reached max turn limit: ${maxTurns}`);\n this.name = \"MaxTurnsError\";\n }\n}\n\nexport class AgentRunCancelledError extends Error {\n constructor(\n readonly chatHistory: Message[],\n readonly reason: string,\n ) {\n super(`Agent run cancelled: ${reason}`);\n this.name = \"AgentRunCancelledError\";\n }\n}\n","import type { ProviderTool } from \"../completion\";\nimport type { ToolIndex } from \"../tool/dynamic-tools\";\nimport type { AnyTool } from \"../tool/tool\";\n\nexport type AgentToolState = {\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 { AgentToolApprovalRequest } from \"../../agent/run-types\";\nimport type { ToolApprovalRequest } from \"./approval-request\";\n\nconst approvalDetails = new WeakMap<object, ToolApprovalRequest>();\n\nexport function registerAgentApprovalRequestDetails(\n approval: AgentToolApprovalRequest,\n request: ToolApprovalRequest,\n): void {\n approvalDetails.set(approval, request);\n}\n\nexport function getAgentApprovalRequestDetails(\n approval: AgentToolApprovalRequest,\n): ToolApprovalRequest | undefined {\n return approvalDetails.get(approval);\n}\n","import type { Document } from \"../completion\";\nimport {\n assertFiniteSearchThreshold,\n assertPositiveSearchLimit,\n} from \"../internal/vector-search-options\";\nimport type { VectorFilter, VectorSearchIndex, VectorSearchResult } from \"../vector-store\";\n\nexport type CreateContextIndexOptions<T = unknown> = {\n topK: number;\n threshold?: number | undefined;\n filter?: VectorFilter | undefined;\n format?(result: VectorSearchResult<T>): Document;\n};\n\nexport interface ContextIndex<T = unknown> extends CreateContextIndexOptions<T> {\n readonly kind: \"context-index\";\n readonly index: VectorSearchIndex<T>;\n}\n\nexport function createContextIndex<T>(\n index: VectorSearchIndex<T>,\n options: CreateContextIndexOptions<T>,\n): ContextIndex<T> {\n const topK = assertPositiveSearchLimit(options.topK);\n const threshold = assertFiniteSearchThreshold(options.threshold);\n return Object.freeze({\n ...options,\n topK,\n ...(threshold === undefined ? {} : { threshold }),\n kind: \"context-index\" as const,\n index,\n });\n}\n\nexport function isContextIndex(value: unknown): value is ContextIndex {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const candidate = value as { kind?: unknown; index?: unknown };\n if (candidate.kind !== \"context-index\" || typeof candidate.index !== \"object\") {\n return false;\n }\n return (\n candidate.index !== null &&\n typeof (candidate.index as { search?: unknown }).search === \"function\"\n );\n}\n","import type { AgentRunOptions } from \"../../agent/run-types\";\nimport type { AgentHook } from \"../../hooks\";\n\nconst internalAgentRunOptions = Symbol(\"internalAgentRunOptions\");\n\nexport type InternalAgentRunOptions = {\n hook?: AgentHook | undefined;\n runId?: string | undefined;\n};\n\ntype AgentRunOptionsWithInternal = AgentRunOptions & {\n [internalAgentRunOptions]?: InternalAgentRunOptions;\n};\n\nexport function withInternalAgentRunOptions<T extends AgentRunOptions>(\n options: T,\n internal: InternalAgentRunOptions,\n): T {\n return {\n ...options,\n [internalAgentRunOptions]: internal,\n };\n}\n\nexport function getInternalAgentRunOptions(\n options: AgentRunOptions,\n): InternalAgentRunOptions | undefined {\n return (options as AgentRunOptionsWithInternal)[internalAgentRunOptions];\n}\n","import { z } from \"zod\";\nimport { isStreamingCompletionModel } from \"../completion/create-completion\";\nimport type {\n CompletionModel,\n ContextUsage,\n JsonObject,\n JsonValue,\n Message as MessageType,\n ProviderTool,\n ToolChoice,\n} from \"../completion/index\";\nimport { getAssistantGenerationMetadata, isProviderTool } from \"../completion/types\";\nimport { appendGuardrailPolicies, type GuardrailPolicy } from \"../guardrails\";\nimport { AgentRun } from \"../internal/agent-runtime/agent-run\";\nimport { prepareToolCall } from \"../internal/agent-runtime/prepared-tool-call\";\nimport { assertNonnegativeSafeInteger } from \"../internal/agent-runtime/run-validation\";\nimport {\n assertFiniteSearchThreshold,\n assertPositiveSearchLimit,\n} from \"../internal/vector-search-options\";\nimport { resolveMemoryOptions } from \"../memory/options\";\nimport type { MemoryContext, MemoryRegistration, SessionOptions } from \"../memory/types\";\nimport type { AgentObserverRegistration } from \"../observability\";\nimport { toProviderJsonSchema } from \"../schema/zod-schema\";\nimport { createTool } from \"../tool/create-tool\";\nimport { isToolIndex, type ToolIndex } from \"../tool/dynamic-tools\";\nimport { ToolNotFoundError } from \"../tool/errors\";\nimport type { AgentMiddleware } from \"../tool/middleware\";\nimport type {\n AnyTool,\n NormalizedToolOutput,\n Tool,\n ToolCallContext,\n ToolCallStreamEvent,\n} from \"../tool/tool\";\nimport type {\n VectorInspectRequest,\n VectorSearchRequest,\n VectorSearchResult,\n VectorSearchToolOptions,\n} from \"../vector-store\";\nimport { type ContextIndex, isContextIndex } from \"./context-index\";\nimport { normalizeAgentId } from \"./ids\";\nimport type { AgentLifecycle } from \"./lifecycle\";\nimport type {\n AgentApprovalDecision,\n AgentApprovalRequiredEvent,\n AgentApprovalRequiredResult,\n AgentInput,\n AgentResult,\n AgentRunOptions,\n AgentStream,\n AgentStreamEvent,\n AgentStreamEventWithoutToolCallDeltas,\n AgentStreamOptions,\n} from \"./run-types\";\nimport { getAgentToolState, getRegisteredAgentTool, registerAgentToolState } from \"./tool-state\";\nimport type {\n AgentContextInput,\n AgentOptions,\n AgentToolOptions,\n ResolvedAgentOptions,\n} from \"./types\";\n\nconst DEFAULT_MAX_TURNS = 20;\n\nexport class Agent<M extends CompletionModel = CompletionModel, ContextDocument = unknown> {\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 additionalParams: JsonValue | undefined;\n readonly tools: readonly AnyTool[];\n readonly toolChoice: ToolChoice | undefined;\n readonly defaultMaxTurns: number | undefined;\n readonly lifecycle: AgentLifecycle | undefined;\n readonly outputSchema: JsonObject | undefined;\n readonly observers: readonly AgentObserverRegistration[];\n readonly guardrails: readonly GuardrailPolicy[];\n readonly middlewares: readonly AgentMiddleware[];\n readonly memory: MemoryRegistration | undefined;\n\n constructor(options: AgentOptions<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 const context = (resolved.context ?? []).map(snapshotContextInput);\n assertValidContextIndexes(context);\n this.context = Object.freeze(context);\n this.temperature = resolved.temperature;\n this.maxTokens = resolved.maxTokens;\n this.additionalParams = cloneFrozenPlainData(resolved.additionalParams);\n const staticTools = dedupeTools(resolved.tools ?? []);\n const toolIndexes = (resolved.toolIndexes ?? []).map(snapshotToolIndex);\n assertUniqueIndexedToolNames(toolIndexes);\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 if (!toolsByName.has(tool.name)) {\n toolsByName.set(tool.name, tool);\n }\n }\n }\n this.tools = Object.freeze([...toolsByName.values()]);\n const publicToolState = Object.freeze({\n staticTools: Object.freeze(staticTools),\n providerTools: Object.freeze((resolved.providerTools ?? []).map(snapshotProviderTool)),\n toolIndexes: Object.freeze(toolIndexes),\n });\n registerAgentToolState(this, publicToolState, toolsByName);\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 = cloneFrozenPlainData(resolved.outputSchema);\n this.observers = Object.freeze(\n (resolved.observers ?? []).map((registration) => Object.freeze({ ...registration })),\n );\n this.guardrails = Object.freeze((resolved.guardrails ?? []).map(snapshotGuardrailPolicy));\n this.middlewares = Object.freeze([...(resolved.middlewares ?? [])]);\n this.memory = snapshotMemoryRegistration(resolved.memory);\n }\n\n generate(input: AgentInput, options: AgentRunOptions = {}): Promise<AgentResult> {\n return createGenerateExecution(this, AgentRun.fromAgent(this, input, options)).next();\n }\n\n stream(\n input: AgentInput,\n options: AgentStreamOptions & { includeToolCallDeltas: false },\n ): AgentStream<AgentStreamEventWithoutToolCallDeltas>;\n stream(\n input: AgentInput,\n options?: AgentStreamOptions & { includeToolCallDeltas?: true },\n ): AgentStream<AgentStreamEvent>;\n stream(input: AgentInput, options: AgentStreamOptions): AgentStream<AgentStreamEvent>;\n stream(input: AgentInput, options: AgentStreamOptions = {}): AgentStream<AgentStreamEvent> {\n return createStreamExecution(\n this,\n AgentRun.fromAgent(this, input, options),\n options.includeToolCallDeltas !== false,\n );\n }\n\n resume(\n pending: AgentApprovalRequiredResult,\n decision: AgentApprovalDecision,\n ): Promise<AgentResult>;\n resume(\n pending: AgentApprovalRequiredEvent,\n decision: AgentApprovalDecision,\n ): AgentStream<AgentStreamEvent>;\n resume(\n pending: AgentApprovalRequiredResult | AgentApprovalRequiredEvent,\n decision: AgentApprovalDecision,\n ): Promise<AgentResult> | AgentStream<AgentStreamEvent> {\n assertAgentApprovalDecision(decision);\n const continuation = approvalContinuations.get(pending);\n if (continuation === undefined || continuation.agent !== this) {\n throw new TypeError(\"Approval continuation does not belong to this agent.\");\n }\n approvalContinuations.delete(pending);\n continuation.run.resolveApproval(decision);\n return continuation.mode === \"generate\"\n ? continuation.execution.next()\n : continuation.execution.segment();\n }\n\n session(sessionId: string, options: SessionOptions = {}): AgentSession<M> {\n if (this.memory === undefined) {\n throw new Error(`Agent \"${this.id}\" has no memory store configured.`);\n }\n const normalized = sessionId.trim();\n if (normalized.length === 0) {\n throw new TypeError(\"Session id must be a non-empty string.\");\n }\n const context: MemoryContext = {\n sessionId: normalized,\n };\n if (options.userId !== undefined) {\n context.userId = options.userId;\n }\n if (options.metadata !== undefined) {\n context.metadata = cloneFrozenPlainData(options.metadata);\n }\n return new AgentSession(this, context);\n }\n\n asTool(options: AgentToolOptions): Tool<{ prompt: string }, string> {\n const description =\n options.description ?? this.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 outputSchema: z.string(),\n execute: async ({ prompt }, context: ToolCallContext) => {\n if (\n options.stream === true &&\n context.emitStreamEvent !== undefined &&\n this.model.capabilities.streaming &&\n isStreamingCompletionModel(this.model)\n ) {\n let output = \"\";\n const childStream = this.stream(prompt, {\n maxTurns: options.maxTurns,\n includeToolCallDeltas: context.includeToolCallDeltas !== false,\n });\n for await (const event of childStream) {\n if (event.type === \"approval_required\") {\n await cancelAgentApproval(\n event,\n `Agent tool \"${options.name}\" cannot suspend for tool approval.`,\n );\n throw new Error(\n `Agent tool \"${options.name}\" cannot suspend for tool approval. Run the agent directly to handle approvals.`,\n );\n }\n const streamEvent: ToolCallStreamEvent = {\n agentId: this.id,\n event,\n };\n if (this.name !== undefined) {\n streamEvent.agentName = this.name;\n }\n await context.emitStreamEvent(streamEvent);\n if (event.type === \"final\") {\n output = event.output;\n }\n }\n return output;\n }\n const response = await this.generate(prompt, { maxTurns: options.maxTurns });\n if (response.status === \"approval_required\") {\n await cancelAgentApproval(\n response,\n `Agent tool \"${options.name}\" cannot suspend for tool approval.`,\n );\n throw new Error(\n `Agent tool \"${options.name}\" cannot suspend for tool approval. Run the agent directly to handle approvals.`,\n );\n }\n return response.output;\n },\n });\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\n return prepareToolCall(tool, args).call(context ?? {});\n }\n}\n\nconst resolvedAgentOptions = Symbol(\"resolvedAgentOptions\");\n\ntype InternalAgentOptions<M extends CompletionModel, ContextDocument> = ResolvedAgentOptions<\n M,\n ContextDocument\n> & {\n [resolvedAgentOptions]: true;\n};\n\nexport function createResolvedAgent<M extends CompletionModel, ContextDocument = unknown>(\n options: ResolvedAgentOptions<M, ContextDocument>,\n): Agent<M, ContextDocument> {\n return new Agent({\n ...options,\n [resolvedAgentOptions]: true,\n } as unknown as AgentOptions<M, ContextDocument>);\n}\n\nexport function getResolvedAgentOptions<M extends CompletionModel, ContextDocument>(\n agent: Agent<M, ContextDocument>,\n): ResolvedAgentOptions<M, ContextDocument> {\n const toolState = getAgentToolState(agent);\n return {\n id: agent.id,\n name: agent.name,\n description: agent.description,\n model: agent.model,\n instructions: agent.instructions,\n context: [...agent.context],\n temperature: agent.temperature,\n maxTokens: agent.maxTokens,\n additionalParams: agent.additionalParams,\n tools: [...toolState.staticTools],\n providerTools: [...toolState.providerTools],\n toolIndexes: [...toolState.toolIndexes],\n toolChoice: agent.toolChoice,\n defaultMaxTurns: agent.defaultMaxTurns,\n lifecycle: agent.lifecycle,\n outputSchema: agent.outputSchema,\n observers: [...agent.observers],\n guardrails: [...agent.guardrails],\n middlewares: [...agent.middlewares],\n memory: agent.memory,\n };\n}\n\nfunction resolveAgentOptions<M extends CompletionModel, ContextDocument>(\n options: AgentOptions<M, ContextDocument>,\n): ResolvedAgentOptions<M, ContextDocument> {\n if (isInternalAgentOptions(options)) {\n return options as unknown as ResolvedAgentOptions<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(\n \"Invalid tool index: search, searchIds, asTool, tools, and a numeric topK are required.\",\n );\n } else {\n toolsByName.set(tool.name, tool);\n }\n }\n for (const server of options.mcpServers ?? []) {\n for (const tool of server.tools) {\n toolsByName.set(tool.name, tool);\n }\n }\n if (options.skills !== undefined) {\n for (const tool of options.skills.tools) {\n toolsByName.set(tool.name, 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 additionalParams: options.additionalParams,\n tools: [...toolsByName.values()],\n providerTools,\n toolIndexes,\n toolChoice: options.toolChoice,\n defaultMaxTurns: options.maxTurns,\n lifecycle: options.lifecycle,\n outputSchema:\n options.outputSchema === undefined ? undefined : toProviderJsonSchema(options.outputSchema),\n observers: (options.observers ?? []).map((input) =>\n \"observer\" in input\n ? { observer: input.observer, failOnObserverError: input.failOnObserverError }\n : { observer: input },\n ),\n guardrails:\n options.guardrails === undefined ? [] : appendGuardrailPolicies([], options.guardrails),\n middlewares: [...(options.middlewares ?? [])],\n memory,\n };\n}\n\nfunction assertUniqueIndexedToolNames(indexes: readonly ToolIndex[]): void {\n const owners = new Map<string, number>();\n for (const [indexPosition, index] of indexes.entries()) {\n if (!isToolIndex(index)) {\n throw new TypeError(\n \"Invalid tool index: search, searchIds, asTool, tools, and a numeric topK are required.\",\n );\n }\n assertPositiveSearchLimit(index.topK);\n assertFiniteSearchThreshold(index.threshold);\n for (const tool of index.tools) {\n const existingPosition = owners.get(tool.name);\n if (existingPosition !== undefined) {\n if (existingPosition === indexPosition) {\n throw new TypeError(\n `Tool \"${tool.name}\" is registered more than once by tool index ${indexPosition + 1}. Tool names must be unique within each index.`,\n );\n }\n throw new TypeError(\n `Tool \"${tool.name}\" is registered by multiple tool indexes (${existingPosition + 1} and ${indexPosition + 1}). Tool names must be unique across indexes.`,\n );\n }\n owners.set(tool.name, indexPosition);\n }\n }\n}\n\nfunction assertValidContextIndexes(inputs: readonly AgentContextInput[]): void {\n for (const input of inputs) {\n if (!isContextIndex(input)) continue;\n assertPositiveSearchLimit(input.topK);\n assertFiniteSearchThreshold(input.threshold);\n }\n}\n\nfunction isInternalAgentOptions<M extends CompletionModel, ContextDocument>(\n options: AgentOptions<M, ContextDocument>,\n): boolean {\n return (\n (options as unknown as Partial<InternalAgentOptions<M, ContextDocument>>)[\n resolvedAgentOptions\n ] === true\n );\n}\n\nfunction resolveAgentMemory<M extends CompletionModel, ContextDocument>(\n options: AgentOptions<M, ContextDocument>,\n): MemoryRegistration | 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, options: resolvedOptions };\n}\n\ntype GenerateExecution = {\n next(): Promise<AgentResult>;\n cancel(reason: string): Promise<void>;\n};\n\ntype ApprovalContinuation =\n | {\n agent: Agent;\n run: AgentRun;\n mode: \"generate\";\n execution: GenerateExecution;\n }\n | {\n agent: Agent;\n run: AgentRun;\n mode: \"stream\";\n execution: StreamExecution;\n };\n\nconst approvalContinuations = new WeakMap<object, ApprovalContinuation>();\n\nfunction assertAgentApprovalDecision(decision: AgentApprovalDecision): void {\n if (typeof decision !== \"object\" || decision === null || typeof decision.approved !== \"boolean\") {\n throw new TypeError(\"Approval decision must include an approved boolean.\");\n }\n if (decision.reason !== undefined && typeof decision.reason !== \"string\") {\n throw new TypeError(\"Approval decision reason must be a string.\");\n }\n}\n\nfunction createGenerateExecution(agent: Agent, run: AgentRun): GenerateExecution {\n const completion = run.generate();\n const execution: GenerateExecution = {\n async next() {\n const outcome = await Promise.race([\n completion.then((result) => ({ type: \"completed\" as const, result })),\n run.waitForApproval().then(() => ({ type: \"approval\" as const })),\n ]);\n if (outcome.type === \"completed\") {\n return outcome.result;\n }\n const pending = run.approvalResult();\n approvalContinuations.set(pending, { agent, run, mode: \"generate\", execution });\n return pending;\n },\n async cancel(reason) {\n run.cancel(reason);\n await completion.catch(() => undefined);\n },\n };\n return execution;\n}\n\nclass StreamExecution {\n private readonly iterator: AsyncIterator<AgentStreamEvent>;\n private nextEvent: Promise<IteratorResult<AgentStreamEvent>> | undefined;\n private phase: \"active\" | \"approval\" | \"terminal\" | \"cancelled\" = \"active\";\n\n constructor(\n private readonly agent: Agent,\n private readonly run: AgentRun,\n includeToolCallDeltas: boolean,\n ) {\n this.iterator = run.events(includeToolCallDeltas)[Symbol.asyncIterator]();\n }\n\n segment(): AgentStream<AgentStreamEvent> {\n if (this.phase === \"approval\") {\n this.phase = \"active\";\n }\n return new DefaultAgentStream(this);\n }\n\n steer(input: AgentInput): boolean {\n return this.run.steer(input);\n }\n\n async *events(): AsyncIterable<AgentStreamEvent> {\n while (true) {\n this.nextEvent ??= this.iterator.next();\n let outcome:\n | { type: \"event\"; event: IteratorResult<AgentStreamEvent> }\n | { type: \"approval\" };\n try {\n outcome = await Promise.race([\n this.nextEvent.then((event) => ({ type: \"event\" as const, event })),\n this.run.waitForApproval().then(() => ({ type: \"approval\" as const })),\n ]);\n } catch (error) {\n this.phase = \"terminal\";\n throw error;\n }\n if (outcome.type === \"approval\") {\n this.phase = \"approval\";\n const pending = this.run.approvalEvent();\n approvalContinuations.set(pending, {\n agent: this.agent,\n run: this.run,\n mode: \"stream\",\n execution: this,\n });\n yield pending;\n return;\n }\n this.nextEvent = undefined;\n if (outcome.event.done) {\n this.phase = \"terminal\";\n return;\n }\n yield outcome.event.value;\n }\n }\n\n shouldCancelActiveSegment(): boolean {\n return this.phase === \"active\";\n }\n\n async cancel(reason: string): Promise<void> {\n if (this.phase === \"terminal\" || this.phase === \"cancelled\") {\n return;\n }\n this.phase = \"cancelled\";\n this.run.cancel(reason);\n try {\n await this.iterator.return?.();\n } catch {\n // Cancellation is best-effort; the run finalizes its observers and memory before rejecting.\n }\n }\n}\n\nfunction createStreamExecution(\n agent: Agent,\n run: AgentRun,\n includeToolCallDeltas: boolean,\n): AgentStream<AgentStreamEvent> {\n return new StreamExecution(agent, run, includeToolCallDeltas).segment();\n}\n\nclass DefaultAgentStream<Event extends AgentStreamEvent = AgentStreamEvent>\n implements AgentStream<Event>\n{\n private consuming = false;\n private completed = false;\n\n constructor(private readonly execution: StreamExecution) {}\n\n steer(input: AgentInput): boolean {\n return this.execution.steer(input);\n }\n\n [Symbol.asyncIterator](): AsyncIterator<Event> {\n return this.consume()[Symbol.asyncIterator]();\n }\n\n private async *consume(): AsyncIterableIterator<Event> {\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.execution.events()) {\n yield event as Event;\n }\n } finally {\n if (this.execution.shouldCancelActiveSegment()) {\n await this.execution.cancel(\"Agent stream consumer closed the stream.\");\n }\n this.consuming = false;\n this.completed = true;\n }\n }\n}\n\nexport async function cancelAgentApproval(\n pending: AgentApprovalRequiredResult | AgentApprovalRequiredEvent,\n reason: string,\n): Promise<void> {\n const continuation = approvalContinuations.get(pending);\n if (continuation === undefined) {\n return;\n }\n approvalContinuations.delete(pending);\n await continuation.execution.cancel(reason);\n}\n\nexport class AgentSession<M extends CompletionModel = CompletionModel> {\n constructor(\n private readonly agent: Agent<M>,\n private readonly context: {\n sessionId: string;\n userId?: string | undefined;\n metadata?: JsonObject | undefined;\n },\n ) {}\n\n generate(input: string | MessageType, options: AgentRunOptions = {}): Promise<AgentResult> {\n if (Array.isArray(input)) {\n throw new TypeError(\"AgentSession.generate does not accept Message[] transcripts.\");\n }\n const run = AgentRun.fromAgent(this.agent, input, {\n ...options,\n memoryContext: this.context,\n });\n return createGenerateExecution(this.agent, run).next();\n }\n\n stream(\n input: string | MessageType,\n options: AgentStreamOptions & { includeToolCallDeltas: false },\n ): AgentStream<AgentStreamEventWithoutToolCallDeltas>;\n stream(\n input: string | MessageType,\n options?: AgentStreamOptions & { includeToolCallDeltas?: true },\n ): AgentStream<AgentStreamEvent>;\n stream(input: string | MessageType, options: AgentStreamOptions): AgentStream<AgentStreamEvent>;\n stream(\n input: string | MessageType,\n options: AgentStreamOptions = {},\n ): AgentStream<AgentStreamEvent> {\n if (Array.isArray(input)) {\n throw new TypeError(\"AgentSession.stream does not accept Message[] transcripts.\");\n }\n return createStreamExecution(\n this.agent,\n AgentRun.fromAgent(this.agent, input, { ...options, memoryContext: this.context }),\n options.includeToolCallDeltas !== false,\n );\n }\n\n async messages(): Promise<MessageType[]> {\n const memory = this.agent.memory;\n if (memory === undefined) {\n throw new Error(`Agent \"${this.agent.id}\" has no memory store configured.`);\n }\n return memory.store.load(this.context);\n }\n\n async contextUsage(): Promise<ContextUsage | undefined> {\n const messages = await this.messages();\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index];\n if (message === undefined) {\n continue;\n }\n const generation = getAssistantGenerationMetadata(message);\n if (generation !== undefined) {\n return generation.contextUsage;\n }\n }\n return undefined;\n }\n\n async clear(): Promise<void> {\n const memory = this.agent.memory;\n if (memory === undefined) {\n throw new Error(`Agent \"${this.agent.id}\" has no memory store configured.`);\n }\n await memory.store.clear(this.context);\n }\n}\n\nfunction snapshotContextInput<T>(input: AgentContextInput<T>): AgentContextInput<T> {\n if (!isContextIndex(input)) {\n return Object.freeze({\n id: input.id,\n text: input.text,\n ...(input.additionalProps === undefined\n ? {}\n : { additionalProps: cloneFrozenPlainData(input.additionalProps) }),\n });\n }\n const format = input.format;\n return Object.freeze<ContextIndex<T>>({\n kind: \"context-index\",\n index: input.index,\n topK: input.topK,\n ...(input.threshold === undefined ? {} : { threshold: input.threshold }),\n ...(input.filter === undefined ? {} : { filter: cloneFrozenPlainData(input.filter) }),\n ...(format === undefined\n ? {}\n : { format: (result: VectorSearchResult<T>) => format.call(input, result) }),\n });\n}\n\nfunction snapshotProviderTool(tool: ProviderTool): ProviderTool {\n return Object.freeze({\n ...tool,\n ...(tool.configuration === undefined\n ? {}\n : { configuration: cloneFrozenPlainData(tool.configuration) }),\n });\n}\n\nfunction snapshotToolIndex(index: ToolIndex): ToolIndex {\n const inspect = index.inspect;\n return Object.freeze({\n kind: \"tool-index\" as const,\n tools: Object.freeze([...index.tools]),\n topK: index.topK,\n ...(index.threshold === undefined ? {} : { threshold: index.threshold }),\n ...(index.filter === undefined ? {} : { filter: cloneFrozenPlainData(index.filter) }),\n search: (request: VectorSearchRequest) => index.search(request),\n searchIds: (request: VectorSearchRequest) => index.searchIds(request),\n asTool: (options: VectorSearchToolOptions) => index.asTool(options),\n ...(inspect === undefined\n ? {}\n : { inspect: (request: VectorInspectRequest) => inspect.call(index, request) }),\n });\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\nfunction snapshotMemoryRegistration(\n memory: MemoryRegistration | undefined,\n): MemoryRegistration | undefined {\n if (memory === undefined) {\n return undefined;\n }\n const compaction =\n memory.options.compaction === undefined\n ? undefined\n : Object.freeze({ ...memory.options.compaction });\n return Object.freeze({\n store: memory.store,\n options: Object.freeze({\n ...memory.options,\n ...(compaction === undefined ? {} : { compaction }),\n }),\n });\n}\n\nfunction 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 dedupeTools(tools: readonly AnyTool[]): AnyTool[] {\n const byName = new Map<string, AnyTool>();\n for (const tool of tools) {\n byName.set(tool.name, tool);\n }\n return [...byName.values()];\n}\n","import type { CompletionResponse, Message, Usage } from \"../completion\";\nimport type { DeepReadonly, MaybePromise } from \"../internal/type-utils\";\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\nexport type AgentFinishEvent = AgentLifecycleRunEvent & {\n output: string;\n usage: DeepReadonly<Usage>;\n messages: DeepReadonly<Message[]>;\n};\n\nexport type AgentErrorEvent = AgentLifecycleRunEvent & {\n error: unknown;\n usage: DeepReadonly<Usage>;\n messages: DeepReadonly<Message[]>;\n};\n\nexport type AgentLifecycle<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): MaybePromise<void>;\n onError?(event: AgentErrorEvent): MaybePromise<void>;\n};\n\nexport function composeAgentLifecycle<RawResponse = unknown>(\n first: AgentLifecycle<RawResponse> | undefined,\n second: AgentLifecycle<RawResponse> | undefined,\n): AgentLifecycle<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","export function observerSnapshot<T>(value: T): T {\n if (containsError(value, new WeakSet<object>())) {\n return cloneObserverFallback(value, new WeakMap<object, object>());\n }\n try {\n return globalThis.structuredClone(value);\n } catch {\n return cloneObserverFallback(value, new WeakMap<object, object>());\n }\n}\n\nfunction cloneObserverFallback<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) => cloneObserverFallback(item, seen)));\n return clone as T;\n }\n if (value instanceof Date) {\n return new Date(value.getTime()) as T;\n }\n if (value instanceof Error) {\n const clone = Object.create(Object.getPrototypeOf(value)) as Error;\n seen.set(value, clone);\n Object.defineProperties(clone, {\n name: { configurable: true, writable: true, value: value.name },\n message: { configurable: true, writable: true, value: value.message },\n });\n if (value.stack !== undefined) {\n Object.defineProperty(clone, \"stack\", {\n configurable: true,\n writable: true,\n value: value.stack,\n });\n }\n if (value.cause !== undefined) {\n Object.defineProperty(clone, \"cause\", {\n configurable: true,\n writable: true,\n value: cloneObserverFallback(value.cause, seen),\n });\n }\n for (const key of Object.getOwnPropertyNames(value)) {\n if (key === \"name\" || key === \"message\" || key === \"stack\" || key === \"cause\") continue;\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined) continue;\n if (\"value\" in descriptor) {\n descriptor.value = cloneObserverFallback(descriptor.value, seen);\n }\n Object.defineProperty(clone, key, descriptor);\n }\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] = cloneObserverFallback(item, seen);\n }\n return clone as T;\n}\n\nfunction containsError(value: unknown, seen: WeakSet<object>): boolean {\n if (typeof value !== \"object\" || value === null) return false;\n if (value instanceof Error) return true;\n if (seen.has(value)) return false;\n seen.add(value);\n if (Array.isArray(value)) {\n return value.some((item) => containsError(item, seen));\n }\n if (Object.getPrototypeOf(value) !== Object.prototype) return false;\n return Object.values(value).some((item) => containsError(item, seen));\n}\n","import { observerSnapshot } from \"./snapshot\";\nimport type {\n AgentGenerationEndArgs,\n AgentGenerationErrorArgs,\n AgentGenerationObserver,\n AgentGenerationStartArgs,\n AgentGenerationUpdateArgs,\n AgentObserverRegistration,\n AgentRunEndArgs,\n AgentRunErrorArgs,\n AgentRunEventArgs,\n AgentRunObserver,\n AgentRunStartArgs,\n AgentToolEndArgs,\n AgentToolErrorArgs,\n AgentToolObserver,\n AgentToolStartArgs,\n AgentToolStreamEventArgs,\n AgentTraceInfo,\n} from \"./types\";\n\nexport async function startAgentRunObservers(\n registrations: readonly AgentObserverRegistration[],\n args: AgentRunStartArgs,\n failOnObserverError: boolean,\n): Promise<ActiveAgentRunObservers> {\n const runObservers: AgentRunObserver[] = [];\n for (const registration of registrations) {\n try {\n const runObserver = await registration.observer.startRun(observerSnapshot(args));\n if (runObserver !== undefined) {\n runObservers.push(runObserver);\n }\n } catch (error) {\n if (failOnObserverError || registration.failOnObserverError === true) {\n throw error;\n }\n }\n }\n\n return new ActiveAgentRunObservers(runObservers, failOnObserverError);\n}\n\nexport class ActiveAgentRunObservers {\n readonly trace: AgentTraceInfo | undefined;\n\n constructor(\n private readonly runObservers: AgentRunObserver[],\n private readonly failOnObserverError: boolean,\n ) {\n this.trace = runObservers.find((observer) => observer.trace !== undefined)?.trace;\n }\n\n async startGeneration(args: AgentGenerationStartArgs): Promise<ActiveGenerationObservers> {\n const generationObservers: AgentGenerationObserver[] = [];\n for (const runObserver of this.runObservers) {\n if (runObserver.startGeneration === undefined) {\n continue;\n }\n try {\n const generationObserver = await runObserver.startGeneration(observerSnapshot(args));\n if (generationObserver !== undefined) {\n generationObservers.push(generationObserver);\n }\n } catch (error) {\n this.handleError(error);\n }\n }\n return new ActiveGenerationObservers(generationObservers, this.failOnObserverError);\n }\n\n async startTool(args: AgentToolStartArgs): Promise<ActiveToolObservers> {\n const toolObservers: AgentToolObserver[] = [];\n for (const runObserver of this.runObservers) {\n if (runObserver.startTool === undefined) {\n continue;\n }\n try {\n const toolObserver = await runObserver.startTool(observerSnapshot(args));\n if (toolObserver !== undefined) {\n toolObservers.push(toolObserver);\n }\n } catch (error) {\n this.handleError(error);\n }\n }\n return new ActiveToolObservers(toolObservers, this.failOnObserverError);\n }\n\n async end(args: AgentRunEndArgs): Promise<void> {\n for (const runObserver of this.runObservers) {\n try {\n await runObserver.end(observerSnapshot(args));\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n async error(args: AgentRunErrorArgs): Promise<void> {\n for (const runObserver of this.runObservers) {\n if (runObserver.error === undefined) {\n continue;\n }\n try {\n await runObserver.error(observerSnapshot(args));\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n async event(args: AgentRunEventArgs): Promise<void> {\n for (const runObserver of this.runObservers) {\n if (runObserver.event === undefined) {\n continue;\n }\n try {\n await runObserver.event(observerSnapshot(args));\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n private handleError(error: unknown): void {\n if (this.failOnObserverError) {\n throw error;\n }\n }\n}\n\nexport class ActiveGenerationObservers {\n constructor(\n private readonly generationObservers: AgentGenerationObserver[],\n private readonly failOnObserverError: boolean,\n ) {}\n\n async end(args: AgentGenerationEndArgs): Promise<void> {\n for (const observer of this.generationObservers) {\n try {\n await observer.end(observerSnapshot(args));\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n async error(args: AgentGenerationErrorArgs): Promise<void> {\n for (const observer of this.generationObservers) {\n if (observer.error === undefined) {\n continue;\n }\n try {\n await observer.error(observerSnapshot(args));\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n async update(args: AgentGenerationUpdateArgs): Promise<void> {\n for (const observer of this.generationObservers) {\n if (observer.update === undefined) {\n continue;\n }\n try {\n await observer.update(observerSnapshot(args));\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n private handleError(error: unknown): void {\n if (this.failOnObserverError) {\n throw error;\n }\n }\n}\n\nexport class ActiveToolObservers {\n constructor(\n private readonly toolObservers: AgentToolObserver[],\n private readonly failOnObserverError: boolean,\n ) {}\n\n async streamEvent(args: AgentToolStreamEventArgs): Promise<void> {\n for (const observer of this.toolObservers) {\n if (observer.streamEvent === undefined) {\n continue;\n }\n try {\n await observer.streamEvent(observerSnapshot(args));\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n async end(args: AgentToolEndArgs): Promise<void> {\n for (const observer of this.toolObservers) {\n try {\n await observer.end(observerSnapshot(args));\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n async error(args: AgentToolErrorArgs): Promise<void> {\n for (const observer of this.toolObservers) {\n if (observer.error === undefined) {\n continue;\n }\n try {\n await observer.error(observerSnapshot(args));\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n private handleError(error: unknown): void {\n if (this.failOnObserverError) {\n throw error;\n }\n }\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 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) => item.content.flatMap((part) => (part.type === \"text\" ? [part.text] : [])))\n .join(\"\\n\");\n }\n\n return undefined;\n}\n","import type { Agent } from \"../../agent/agent\";\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 { MemoryContext, MemoryRegistration, MemorySavePolicy } from \"../../memory/types\";\n\nexport type MemoryPreparation = {\n history: MessageType[];\n usage: ReturnType<typeof Usage.empty>;\n compaction?: {\n originalMessageCount: number;\n compactedMessageCount: number;\n retainedMessageCount: number;\n conflictRetries: number;\n };\n};\n\nexport class AgentRunMemory {\n constructor(\n private readonly agent: Agent,\n private readonly memoryContext: MemoryContext | undefined,\n private readonly initialHistory: MessageType[],\n ) {}\n\n memoryPolicy(): MemorySavePolicy | undefined {\n return this.memory()?.options.savePolicy;\n }\n\n pendingTurnMessages(newMessages: MessageType[]): MessageType[] {\n return this.memoryPolicy() === \"turn\" ? [...newMessages] : [];\n }\n\n async prepareHistory(runId: string, incomingMessageCount: number): Promise<MemoryPreparation> {\n const memory = this.memory();\n if (memory === undefined || this.memoryContext === undefined) {\n return {\n history: this.initialHistory,\n usage: Usage.empty(),\n };\n }\n\n const preparation = await this.prepareStoredHistory(memory, runId, incomingMessageCount);\n const memoryHistory = preparation.history;\n const chatHistory = [...memoryHistory, ...this.initialHistory];\n return {\n ...preparation,\n history: chatHistory,\n };\n }\n\n async commitAcceptedInput(runId: string, messages: MessageType[]): Promise<void> {\n const memory = this.memory();\n if (\n memory === undefined ||\n this.memoryContext === undefined ||\n memory.options.savePolicy !== \"message\" ||\n messages.length === 0\n ) {\n return;\n }\n\n await memory.store.append({\n context: this.memoryContext,\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.memoryContext === undefined || messages.length === 0) {\n return;\n }\n if (memory.options.savePolicy === \"message\") {\n await memory.store.append({\n context: this.memoryContext,\n runId,\n turn,\n messages,\n });\n } else if (memory.options.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.memoryContext === undefined ||\n memory.options.savePolicy !== \"turn\" ||\n pendingTurnMessages.length === 0\n ) {\n return;\n }\n await memory.store.append({\n context: this.memoryContext,\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 (\n memory === undefined ||\n this.memoryContext === undefined ||\n memory.options.savePolicy !== \"run\"\n ) {\n return;\n }\n await memory.store.append({\n context: this.memoryContext,\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.memoryContext === undefined) {\n return;\n }\n await memory.store.recordError?.({\n context: this.memoryContext,\n runId,\n error,\n messages: [...newMessages],\n });\n }\n\n private memory(): MemoryRegistration | undefined {\n return this.memoryContext === undefined ? undefined : this.agent.memory;\n }\n\n private async prepareStoredHistory(\n memory: MemoryRegistration,\n runId: string,\n incomingMessageCount: number,\n ): Promise<MemoryPreparation> {\n const context = this.memoryContext;\n if (context === undefined) {\n return { history: [], usage: Usage.empty() };\n }\n const options = memory.options.compaction;\n const capability = memory.store.compaction;\n if (options === undefined || capability === undefined) {\n return {\n history: await memory.store.load(context),\n usage: Usage.empty(),\n };\n }\n\n let usage = Usage.empty();\n let conflictRetries = 0;\n for (let attempt = 0; attempt <= options.conflictRetries; attempt += 1) {\n const snapshot = await capability.load(context);\n const compactedMessageCount = compactedPrefixLength(\n snapshot.messages,\n incomingMessageCount,\n options.maxMessages,\n options.keepRecentUserTurns,\n );\n if (compactedMessageCount === 0) {\n return { history: snapshot.messages, usage };\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 context,\n messages: prefix,\n });\n } catch (error) {\n throw remappedCompactorError(error, usage);\n }\n if (result.usage !== undefined) {\n usage = Usage.add(usage, result.usage);\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 let commit: Awaited<ReturnType<typeof capability.commit>>;\n try {\n commit = await capability.commit({\n context,\n revision: snapshot.revision,\n compactedMessageCount,\n summary,\n runId: `memory-compaction:${runId}:${attempt + 1}`,\n });\n } catch (error) {\n throw new MemoryCompactionError(\"Memory compaction store commit failed.\", {\n cause: error,\n usage,\n });\n }\n if (commit === \"committed\") {\n const retained = snapshot.messages.slice(compactedMessageCount);\n return {\n history: [summary, ...retained],\n usage,\n compaction: {\n originalMessageCount: snapshot.messages.length,\n compactedMessageCount,\n retainedMessageCount: retained.length,\n conflictRetries,\n },\n };\n }\n conflictRetries += 1;\n }\n\n throw new MemoryCompactionConflictError(options.conflictRetries + 1, usage);\n }\n}\n\nfunction compactedPrefixLength(\n messages: MessageType[],\n incomingMessageCount: number,\n maxMessages: number,\n keepRecentUserTurns: number,\n): number {\n if (messages.length + incomingMessageCount <= maxMessages) {\n return 0;\n }\n const userMessageIndexes = messages.flatMap((message, index) =>\n message.role === \"user\" ? [index] : [],\n );\n // Keep the recent user-led tail intact. If there are not enough user messages to retain a\n // complete tail, skip compaction even when the transcript already exceeds maxMessages.\n if (userMessageIndexes.length <= keepRecentUserTurns) {\n return 0;\n }\n return userMessageIndexes[userMessageIndexes.length - keepRecentUserTurns] ?? 0;\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 type { Agent } from \"../../agent/agent\";\nimport { isContextIndex } from \"../../agent/context-index\";\nimport { getAgentToolState } from \"../../agent/tool-state\";\nimport type { Document, ToolDefinition } from \"../../completion/index\";\n\nexport async function fetchContextDocuments(\n agent: Agent,\n ragText: string | undefined,\n): Promise<Document[]> {\n const documents: Document[] = [];\n for (const input of agent.context) {\n if (!isContextIndex(input)) {\n documents.push(input);\n continue;\n }\n if (ragText === undefined || ragText.length === 0) {\n continue;\n }\n const results = await input.index.search({\n query: ragText,\n topK: input.topK,\n threshold: input.threshold,\n filter: input.filter,\n });\n for (const result of results) {\n const formatted = input.format?.(result);\n if (formatted !== undefined) {\n documents.push(formatted);\n } else {\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) {\n document.additionalProps = metadata;\n }\n documents.push(document);\n }\n }\n }\n return documents;\n}\n\nexport async function fetchToolDefinitions(\n agent: Agent,\n ragText: string | 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({\n query: ragText,\n topK: index.topK,\n threshold: index.threshold,\n filter: index.filter,\n });\n for (const result of results) {\n const toolName = result.document.toolName;\n if (names.has(toolName)) {\n continue;\n }\n const tool = index.tools.find((candidate) => candidate.name === toolName);\n if (tool === undefined) {\n continue;\n }\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) {\n return undefined;\n }\n\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 { AgentDeltaEvent } from \"../../agent/run-types\";\nimport type {\n AssistantContent as AssistantContentType,\n CompletionResponse,\n CompletionSource,\n CompletionStreamEvent,\n JsonValue,\n ProviderToolCall,\n ReasoningContent,\n ToolCall,\n} from \"../../completion/index\";\nimport { Usage } from \"../../completion/index\";\n\ntype ReasoningState = {\n id?: string;\n text: string;\n content?: ReasoningContent[];\n};\n\ntype PartialToolCall = {\n id: string;\n callId?: string;\n name: string;\n argumentsText: string;\n signature?: string;\n additionalParams?: JsonValue;\n};\n\ntype OrderedPartRef =\n | { type: \"text\"; key: string }\n | { type: \"reasoning\"; key: string }\n | { type: \"tool_call\"; key: string };\n\nexport class CompletionStreamAccumulator<RawResponse = unknown> {\n private orderedParts: OrderedPartRef[] = [];\n private textParts = new Map<string, string>();\n private reasoningByKey = new Map<string, ReasoningState>();\n private reasoningKeyById = new Map<string, string>();\n private toolCalls = new Map<string, PartialToolCall>();\n private sources = new Map<string, CompletionSource>();\n private providerToolCalls = new Map<string, ProviderToolCall>();\n private finalResponse: CompletionResponse<RawResponse> | undefined;\n private messageId: string | undefined;\n private nextTextKey = 0;\n private nextReasoningKey = 0;\n\n accept(event: CompletionStreamEvent<RawResponse>): AgentDeltaEvent | undefined {\n if (event.type === \"text_delta\") {\n this.appendText(event.delta);\n return { type: \"text_delta\", delta: event.delta };\n }\n\n if (event.type === \"reasoning_delta\") {\n const reasoning = this.reasoningStateForEvent(event);\n this.appendReasoning(reasoning, event);\n return reasoningDeltaEvent(event);\n }\n\n if (event.type === \"tool_call_delta\") {\n const toolCall = this.toolCallStateForId(event.id);\n if (event.callId !== undefined && event.callId.length > 0) toolCall.callId = event.callId;\n if (event.name !== undefined && event.name.length > 0) toolCall.name = event.name;\n if (event.signature !== undefined) toolCall.signature = event.signature;\n if (event.argumentsDelta !== undefined) {\n if (event.argumentsMode === \"replace\") {\n toolCall.argumentsText = event.argumentsDelta;\n } else {\n toolCall.argumentsText += event.argumentsDelta;\n }\n }\n return undefined;\n }\n\n if (event.type === \"tool_call\") {\n this.upsertToolCall(event.toolCall);\n return { type: \"tool_call\", toolCall: event.toolCall };\n }\n\n if (event.type === \"source\") {\n this.sources.set(sourceKey(event.source), event.source);\n return { type: \"source\", source: event.source };\n }\n\n if (event.type === \"provider_tool_call\") {\n this.providerToolCalls.set(event.toolCall.id, event.toolCall);\n return { type: \"provider_tool_call\", toolCall: event.toolCall };\n }\n\n if (event.type === \"message_id\") {\n this.messageId = event.id;\n return undefined;\n }\n\n if (event.type === \"final\") {\n this.finalResponse = event.response;\n return undefined;\n }\n\n return undefined;\n }\n\n response(): CompletionResponse<RawResponse> {\n const accumulatedResponse = this.buildAccumulatedResponse();\n if (this.finalResponse !== undefined) {\n if (accumulatedResponse.choice.length === 0) {\n return this.withAccumulatedArtifacts(this.finalResponse, accumulatedResponse);\n }\n return this.mergeFinalResponse(accumulatedResponse, this.finalResponse);\n }\n\n return accumulatedResponse;\n }\n\n private buildAccumulatedResponse(): CompletionResponse<RawResponse> {\n const choice: AssistantContentType[] = [];\n\n for (const part of this.orderedParts) {\n if (part.type === \"text\") {\n const text = this.textParts.get(part.key) ?? \"\";\n if (text.length > 0) {\n choice.push({ type: \"text\", text });\n }\n continue;\n }\n\n if (part.type === \"reasoning\") {\n const reasoning = this.reasoningByKey.get(part.key);\n if (reasoning !== undefined) {\n choice.push(reasoningContent(reasoning));\n }\n continue;\n }\n\n const toolCall = this.toolCalls.get(part.key);\n if (toolCall !== undefined) {\n choice.push(\n toolCallContent(toolCall, matchingFinalToolCall(toolCall, this.finalResponse?.choice)),\n );\n }\n }\n\n const response: CompletionResponse<RawResponse> = {\n choice,\n usage: Usage.empty(),\n rawResponse: undefined as RawResponse,\n };\n if (this.messageId !== undefined) {\n response.messageId = this.messageId;\n }\n const sources = [...this.sources.values()];\n if (sources.length > 0) {\n response.sources = sources;\n }\n const providerToolCalls = [...this.providerToolCalls.values()];\n if (providerToolCalls.length > 0) {\n response.providerToolCalls = providerToolCalls;\n }\n return response;\n }\n\n private upsertToolCall(toolCall: ToolCall): void {\n if (!this.toolCalls.has(toolCall.id)) {\n this.orderedParts.push({ type: \"tool_call\", key: toolCall.id });\n }\n const partial: PartialToolCall = {\n id: toolCall.id,\n name: toolCall.function.name,\n argumentsText: JSON.stringify(toolCall.function.arguments ?? {}),\n };\n if (toolCall.callId !== undefined) {\n partial.callId = toolCall.callId;\n }\n if (toolCall.signature !== undefined) {\n partial.signature = toolCall.signature;\n }\n if (toolCall.additionalParams !== undefined) {\n partial.additionalParams = toolCall.additionalParams;\n }\n this.toolCalls.set(toolCall.id, partial);\n }\n\n private mergeFinalResponse(\n accumulatedResponse: CompletionResponse<RawResponse>,\n finalResponse: CompletionResponse<RawResponse>,\n ): CompletionResponse<RawResponse> {\n if (finalResponse.choice.length === 0) {\n const mergedResponse: CompletionResponse<RawResponse> = {\n ...accumulatedResponse,\n usage: finalResponse.usage,\n rawResponse: finalResponse.rawResponse,\n };\n if (finalResponse.messageId !== undefined) {\n mergedResponse.messageId = finalResponse.messageId;\n }\n return this.withAccumulatedArtifacts(mergedResponse, accumulatedResponse);\n }\n\n const finalById = new Map<string, ToolCall>();\n const finalByCallId = new Map<string, ToolCall>();\n for (const content of finalResponse.choice) {\n if (content.type !== \"tool_call\") {\n continue;\n }\n finalById.set(content.id, content);\n if (content.callId !== undefined) {\n finalByCallId.set(content.callId, content);\n }\n }\n\n const matchedFinalToolCalls = new Set<ToolCall>();\n const choice = accumulatedResponse.choice.map((content) => {\n if (content.type !== \"tool_call\") {\n return content;\n }\n\n const finalToolCall =\n finalById.get(content.id) ??\n (content.callId === undefined ? undefined : finalByCallId.get(content.callId));\n if (finalToolCall === undefined) {\n return content;\n }\n\n matchedFinalToolCalls.add(finalToolCall);\n return mergeFinalToolCall(content, finalToolCall);\n });\n\n for (const content of finalResponse.choice) {\n if (content.type !== \"tool_call\") {\n continue;\n }\n if (!matchedFinalToolCalls.has(content)) {\n choice.push(content);\n }\n }\n\n return this.withAccumulatedArtifacts({ ...finalResponse, choice }, accumulatedResponse);\n }\n\n private appendText(delta: string): void {\n const lastPart = this.orderedParts.at(-1);\n const key = lastPart?.type === \"text\" ? lastPart.key : this.createTextKey();\n if (lastPart?.type !== \"text\") {\n this.orderedParts.push({ type: \"text\", key });\n }\n this.textParts.set(key, `${this.textParts.get(key) ?? \"\"}${delta}`);\n }\n\n private reasoningStateForEvent(\n event: Extract<CompletionStreamEvent<RawResponse>, { type: \"reasoning_delta\" }>,\n ): ReasoningState {\n if (event.id !== undefined) {\n const existingKey = this.reasoningKeyById.get(event.id);\n if (existingKey !== undefined) {\n const existing = this.reasoningByKey.get(existingKey);\n if (existing !== undefined) {\n return existing;\n }\n }\n\n const key = this.createReasoningKey();\n const reasoning: ReasoningState = { id: event.id, text: \"\" };\n this.reasoningKeyById.set(event.id, key);\n this.reasoningByKey.set(key, reasoning);\n this.orderedParts.push({ type: \"reasoning\", key });\n return reasoning;\n }\n\n const lastPart = this.orderedParts.at(-1);\n if (lastPart?.type === \"reasoning\") {\n const lastReasoning = this.reasoningByKey.get(lastPart.key);\n if (lastReasoning !== undefined && lastReasoning.id === undefined) {\n return lastReasoning;\n }\n }\n\n const key = this.createReasoningKey();\n const reasoning: ReasoningState = { text: \"\" };\n this.reasoningByKey.set(key, reasoning);\n this.orderedParts.push({ type: \"reasoning\", key });\n return reasoning;\n }\n\n private toolCallStateForId(id: string): PartialToolCall {\n const existing = this.toolCalls.get(id);\n if (existing !== undefined) {\n return existing;\n }\n\n const toolCall: PartialToolCall = {\n id,\n name: \"\",\n argumentsText: \"\",\n };\n this.toolCalls.set(id, toolCall);\n this.orderedParts.push({ type: \"tool_call\", key: id });\n return toolCall;\n }\n\n private withMessageIdFallback(\n response: CompletionResponse<RawResponse>,\n accumulatedResponse: CompletionResponse<RawResponse>,\n ): CompletionResponse<RawResponse> {\n if (response.messageId !== undefined || accumulatedResponse.messageId === undefined) {\n return response;\n }\n return { ...response, messageId: accumulatedResponse.messageId };\n }\n\n private withAccumulatedArtifacts(\n response: CompletionResponse<RawResponse>,\n accumulatedResponse: CompletionResponse<RawResponse>,\n ): CompletionResponse<RawResponse> {\n const withMessageId = this.withMessageIdFallback(response, accumulatedResponse);\n const sources = mergeSources(accumulatedResponse.sources, response.sources);\n const providerToolCalls = mergeProviderToolCalls(\n accumulatedResponse.providerToolCalls,\n response.providerToolCalls,\n );\n return {\n ...withMessageId,\n ...(sources.length === 0 ? {} : { sources }),\n ...(providerToolCalls.length === 0 ? {} : { providerToolCalls }),\n };\n }\n\n private createTextKey(): string {\n this.nextTextKey += 1;\n return `text_${this.nextTextKey.toString()}`;\n }\n\n private createReasoningKey(): string {\n this.nextReasoningKey += 1;\n return `reasoning_${this.nextReasoningKey.toString()}`;\n }\n\n private appendReasoning(\n reasoning: ReasoningState,\n event: Extract<CompletionStreamEvent<RawResponse>, { type: \"reasoning_delta\" }>,\n ): void {\n const contentType = event.contentType ?? \"text\";\n if (contentType === \"text\" || contentType === \"summary\") {\n reasoning.text += event.delta;\n }\n\n if (event.contentType === undefined && event.signature === undefined) {\n return;\n }\n\n reasoning.content ??= [];\n const last = reasoning.content.at(-1);\n if (contentType === \"text\") {\n if (last?.type === \"text\") {\n last.text += event.delta;\n if (event.signature !== undefined) {\n last.signature = event.signature;\n }\n } else {\n reasoning.content.push(\n event.signature === undefined\n ? { type: \"text\", text: event.delta }\n : { type: \"text\", text: event.delta, signature: event.signature },\n );\n }\n return;\n }\n\n if (contentType === \"summary\") {\n if (last?.type === \"summary\") {\n last.text += event.delta;\n } else {\n reasoning.content.push({ type: \"summary\", text: event.delta });\n }\n return;\n }\n\n if (contentType === \"encrypted\") {\n reasoning.content.push({ type: \"encrypted\", data: event.delta });\n return;\n }\n\n reasoning.content.push({ type: \"redacted\", data: event.delta });\n }\n}\n\nfunction sourceKey(source: CompletionSource): string {\n return `${source.url}\\u0000${source.startIndex ?? \"\"}\\u0000${source.endIndex ?? \"\"}`;\n}\n\nfunction mergeSources(\n accumulated: CompletionSource[] | undefined,\n final: CompletionSource[] | undefined,\n): CompletionSource[] {\n const sources = new Map<string, CompletionSource>();\n for (const source of [...(accumulated ?? []), ...(final ?? [])]) {\n sources.set(sourceKey(source), source);\n }\n return [...sources.values()];\n}\n\nfunction mergeProviderToolCalls(\n accumulated: ProviderToolCall[] | undefined,\n final: ProviderToolCall[] | undefined,\n): ProviderToolCall[] {\n const toolCalls = new Map<string, ProviderToolCall>();\n for (const toolCall of [...(accumulated ?? []), ...(final ?? [])]) {\n toolCalls.set(toolCall.id, toolCall);\n }\n return [...toolCalls.values()];\n}\n\nfunction reasoningContent(reasoning: ReasoningState): AssistantContentType {\n const content =\n reasoning.content === undefined\n ? { type: \"reasoning\" as const, text: reasoning.text }\n : { type: \"reasoning\" as const, text: reasoning.text, content: reasoning.content };\n return reasoning.id === undefined ? content : { ...content, id: reasoning.id };\n}\n\nfunction toolCallContent(toolCall: PartialToolCall, finalToolCall?: ToolCall): ToolCall {\n const argumentsValue =\n finalToolCall !== undefined && !isEmptyToolArguments(finalToolCall.function.arguments)\n ? finalToolCall.function.arguments\n : parseToolArguments(toolCall.id, toolCall.argumentsText);\n const content: ToolCall = {\n type: \"tool_call\",\n id: toolCall.id,\n function: {\n name: toolCall.name,\n arguments: argumentsValue,\n },\n };\n if (toolCall.callId !== undefined) {\n content.callId = toolCall.callId;\n }\n if (toolCall.signature !== undefined) {\n content.signature = toolCall.signature;\n }\n if (toolCall.additionalParams !== undefined) {\n content.additionalParams = toolCall.additionalParams;\n }\n return content;\n}\n\nfunction matchingFinalToolCall(\n accumulated: PartialToolCall,\n finalChoice: AssistantContentType[] | undefined,\n): ToolCall | undefined {\n const byId = finalChoice?.find(\n (content): content is ToolCall => content.type === \"tool_call\" && content.id === accumulated.id,\n );\n if (byId !== undefined || accumulated.callId === undefined) {\n return byId;\n }\n return finalChoice?.find(\n (content): content is ToolCall =>\n content.type === \"tool_call\" && content.callId === accumulated.callId,\n );\n}\n\nfunction mergeFinalToolCall(accumulated: ToolCall, finalToolCall: ToolCall): ToolCall {\n const argumentsValue = isEmptyToolArguments(finalToolCall.function.arguments)\n ? accumulated.function.arguments\n : finalToolCall.function.arguments;\n return {\n ...accumulated,\n ...finalToolCall,\n function: {\n ...accumulated.function,\n ...finalToolCall.function,\n arguments: argumentsValue,\n },\n };\n}\n\nfunction reasoningDeltaEvent(\n event: Extract<CompletionStreamEvent, { type: \"reasoning_delta\" }>,\n): AgentDeltaEvent {\n const mapped: AgentDeltaEvent = { type: \"reasoning_delta\", 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\nfunction isEmptyToolArguments(value: unknown): boolean {\n if (value === undefined || value === null) {\n return true;\n }\n if (typeof value === \"string\") {\n return value.trim().length === 0;\n }\n if (Array.isArray(value)) {\n return value.length === 0;\n }\n if (typeof value === \"object\") {\n return Object.values(value).every((item) => item === undefined);\n }\n return false;\n}\n\nfunction parseToolArguments(toolCallId: string, text: string): JsonValue {\n if (text.trim().length === 0) {\n return {};\n }\n try {\n return JSON.parse(text) as JsonValue;\n } catch {\n throw new Error(\n `Completion returned tool call \"${toolCallId}\" with malformed JSON arguments; this indicates invalid provider output or incomplete stream assembly.`,\n );\n }\n}\n","import type {\n AgentDeltaEvent,\n AgentStreamEvent,\n AgentToolCallDeltaEvent,\n} from \"../../agent/run-types\";\nimport type { CompletionStreamEvent } 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<CompletionStreamEvent, { 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 { Agent } from \"../../agent/agent\";\nimport { type AgentLifecycle, lifecycleSnapshot } from \"../../agent/lifecycle\";\nimport type { AgentApprovalDecision, AgentChildStreamEvent } from \"../../agent/run-types\";\nimport type {\n JsonObject,\n JsonValue,\n ToolCall,\n ToolDefinition,\n ToolResult,\n ToolResultContent,\n} from \"../../completion\";\nimport { ToolContent } from \"../../completion\";\nimport type { AgentHook, ToolApprovalRequestOptions, ToolHookArgs } from \"../../hooks\";\nimport { runControl, toolCallControl } from \"../../hooks\";\nimport type { ActiveAgentRunObservers, ActiveToolObservers } from \"../../observability/group\";\nimport type {\n AgentToolEndArgs,\n AgentToolErrorArgs,\n AgentToolStartArgs,\n AgentToolStreamEventArgs,\n} from \"../../observability/types\";\nimport type {\n AnyTool,\n NormalizedToolOutput,\n ToolApprovalContext,\n ToolApprovalRunContext,\n ToolCallContext,\n ToolCallStreamEvent,\n ToolRequiresApproval,\n} from \"../../tool\";\nimport { parseToolArgs, toolResultContentToText } from \"../../tool\";\nimport type {\n AgentMiddleware,\n ToolOutputMiddlewareArgs,\n ToolOutputMiddlewareResult,\n} from \"../../tool/middleware\";\nimport { isSkillTool } from \"../../tool/skill-tool-marker\";\nimport { mapWithConcurrency } from \"../concurrency\";\nimport type { ToolApprovalRequest } from \"./approval-request\";\nimport { assertToolApprovalRequirement, toolMayRequireApproval } from \"./approval-requirement\";\nimport {\n type PreparedToolCall,\n prepareToolCall as prepareRegisteredToolCall,\n} from \"./prepared-tool-call\";\n\nconst MCP_TOOL_METADATA_KEY = Symbol.for(\"anvia.mcp.tool.metadata\");\n\nexport type ToolResultEventPayload = {\n type: \"tool_result\";\n toolName: string;\n toolCallId?: string;\n internalCallId: string;\n args: string;\n result: string;\n structuredResult?: ToolResultContent[] | 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;\n};\n\nexport type ToolExecutionEventPayload = ToolResultEventPayload | AgentToolEventPayload;\n\nexport type ToolExecutionObservation = {\n turn: number;\n runObservers: ActiveAgentRunObservers;\n toolDefinitions?: ToolDefinition[];\n includeToolCallDeltas?: boolean;\n};\n\nexport type ToolExecutionRunContext = {\n runId: string;\n sessionId?: string | undefined;\n metadata?: JsonObject | undefined;\n};\n\nexport type ToolApprovalHandler = (request: ToolApprovalRequest) => Promise<AgentApprovalDecision>;\n\nexport class ToolCallExecutor {\n constructor(\n private readonly agent: Agent,\n private readonly activeHook: AgentHook | undefined,\n private readonly approvalHandler: ToolApprovalHandler,\n private readonly lifecycle: AgentLifecycle | undefined,\n private readonly runContext: ToolExecutionRunContext,\n private readonly concurrency: number,\n private readonly requestMiddlewares: readonly AgentMiddleware[],\n private readonly includeToolCallDeltas: boolean,\n private readonly cancel: (reason: string) => Error,\n ) {}\n\n async execute(\n toolCalls: ToolCall[],\n onResult?: (result: ToolResultEventPayload) => void,\n onStreamEvent?: (event: AgentToolEventPayload) => void,\n observation?: ToolExecutionObservation,\n ): Promise<ToolResult[]> {\n for (const toolCall of toolCalls) {\n if (toolCall.function.name.length === 0) {\n throw new Error(\n `Completion returned tool call \"${toolCall.id}\" with an empty function name; this indicates invalid provider output or provider mapping.`,\n );\n }\n }\n\n return mapWithConcurrency(toolCalls, this.concurrency, async (toolCall) => {\n const args = JSON.stringify(toolCall.function.arguments ?? {});\n const internalCallId = globalThis.crypto.randomUUID();\n const hookArgs: ToolHookArgs = {\n toolName: toolCall.function.name,\n internalCallId,\n args,\n };\n if (toolCall.callId !== undefined) {\n hookArgs.toolCallId = toolCall.callId;\n }\n const tool = this.agent.getTool(toolCall.function.name);\n const toolDefinition = observation?.toolDefinitions?.find(\n (definition) => definition.name === toolCall.function.name,\n );\n const toolMetadata = toolTraceMetadata(tool);\n\n const toolStartArgs: AgentToolStartArgs = {\n turn: observation?.turn ?? 0,\n toolCall,\n toolName: toolCall.function.name,\n internalCallId,\n args,\n ...(toolCall.callId === undefined ? {} : { toolCallId: toolCall.callId }),\n ...(toolDefinition === undefined ? {} : { toolDefinition }),\n ...(toolMetadata === undefined ? {} : { toolMetadata }),\n };\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 = 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.function.name, 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) {\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 = 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.function.name,\n input: lifecycleSnapshot(prepared.input),\n ...(toolCall.callId === undefined ? {} : { 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 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.function.name}\" 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.function.name,\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.function.name,\n internalCallId,\n args: effectiveArgs,\n result,\n structuredResult,\n };\n if (toolCall.callId !== undefined) {\n resultPayload.toolCallId = toolCall.callId;\n }\n onResult?.(resultPayload);\n return ToolContent.toolResult(toolCall.id, output, {\n callId: toolCall.callId,\n toolName: toolCall.function.name,\n });\n } catch (error) {\n await toolObservation.error(\n toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error),\n );\n throw error;\n }\n });\n }\n\n private async runApprovedToolCall(\n prepared: PreparedToolCall,\n toolCall: ToolCall,\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 emitStreamEvent: async (event) => {\n const streamEventArgs: AgentToolStreamEventArgs = {\n turn: observation?.turn ?? 0,\n toolCall,\n toolName: toolCall.function.name,\n internalCallId: hookArgs.internalCallId,\n args: effectiveArgs,\n event,\n ...(toolCall.callId === undefined ? {} : { 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 toolContext.includeToolCallDeltas = this.includeToolCallDeltas;\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: ToolCall,\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: error instanceof Error ? error.toString() : String(error),\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 ? (structuredResult ?? result) : 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 current =\n typeof replacement.args === \"string\"\n ? replacement.args\n : JSON.stringify(replacement.args);\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: AgentApprovalDecision;\n try {\n decision = await this.approvalHandler(request);\n } catch (error) {\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 await observation?.runObservers.event({\n name: \"tool.approval_resolved\",\n attributes: {\n ...approvalEventAttributes(request, observation.turn),\n approved: decision.approved,\n ...(decision.reason === undefined ? {} : { decisionReason: decision.reason }),\n },\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: Agent,\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 internalCallId: hookArgs.internalCallId,\n run: approvalRun,\n };\n if (hookArgs.toolCallId !== undefined) {\n context.toolCallId = hookArgs.toolCallId;\n }\n return context;\n}\n\nfunction approvalEventAttributes(\n request: ToolApprovalRequest,\n turn: number,\n): Record<string, JsonValue | undefined> {\n return {\n turn,\n approvalId: request.id,\n toolName: request.toolName,\n toolCallId: request.toolCallId,\n internalCallId: request.internalCallId,\n reason: request.reason,\n };\n}\n\nfunction normalizeToolOutputMiddlewareResult(result: ToolOutputMiddlewareResult): {\n result?: string | undefined;\n structuredResult?: ToolResultContent[] | undefined;\n} {\n if (typeof result === \"string\") {\n return { result };\n }\n return result ?? {};\n}\n\nfunction toolTraceMetadata(tool: AnyTool | undefined): JsonObject | undefined {\n if (tool === undefined) {\n return undefined;\n }\n const metadata = (tool as { [MCP_TOOL_METADATA_KEY]?: unknown })[MCP_TOOL_METADATA_KEY];\n const mcpMetadata =\n typeof metadata === \"object\" && metadata !== null\n ? (metadata as { serverName?: unknown })\n : undefined;\n const result: JsonObject = {\n approvalRequired: toolMayRequireApproval(tool.requiresApproval),\n };\n if (typeof mcpMetadata?.serverName === \"string\" && mcpMetadata.serverName.length > 0) {\n result.mcpServerName = mcpMetadata.serverName;\n }\n return result;\n}\n\nfunction toolErrorArgs(\n turn: number,\n toolCall: ToolCall,\n internalCallId: string,\n args: string,\n error: unknown,\n): AgentToolErrorArgs {\n const observerArgs: AgentToolErrorArgs = {\n turn,\n toolCall,\n toolName: toolCall.function.name,\n internalCallId,\n args,\n error,\n ...(toolCall.callId === undefined ? {} : { 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 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 return typeof output === \"string\" ? output : toolResultContentToText(output);\n}\n\nfunction toolOutputToStructuredResult(\n output: NormalizedToolOutput,\n): ToolResultContent[] | undefined {\n return typeof output === \"string\" ? undefined : output;\n}\n\nfunction agentToolEventPayload(\n toolCall: ToolCall,\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.function.name,\n internalCallId,\n agentId: event.agentId,\n event: event.event as AgentChildStreamEvent,\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 { AgentRunCancelledError, MaxTurnsError } from \"../../agent/errors\";\nimport {\n type AgentLifecycle,\n composeAgentLifecycle,\n lifecycleSnapshot,\n} from \"../../agent/lifecycle\";\nimport type {\n AgentApprovalDecision,\n AgentApprovalRequiredEvent,\n AgentApprovalRequiredResult,\n AgentInput,\n AgentResponse,\n AgentRunOptions,\n AgentStreamEvent,\n} from \"../../agent/run-types\";\nimport { getAgentToolState } from \"../../agent/tool-state\";\nimport { isStreamingCompletionModel } from \"../../completion/create-completion\";\nimport {\n AssistantContent,\n assertCompletionRequestSupported,\n type CompletionModel,\n type CompletionResponse,\n type CompletionSource,\n getAssistantGenerationMetadata,\n type JsonObject,\n type JsonValue,\n Message,\n type Message as MessageType,\n type ProviderToolCall,\n type ToolCall,\n type ToolResult,\n textFromAssistantContent,\n Usage,\n} from \"../../completion/index\";\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 { MemoryContext } from \"../../memory/types\";\nimport {\n type ActiveAgentRunObservers,\n type ActiveGenerationObservers,\n startAgentRunObservers,\n} from \"../../observability/group\";\nimport type {\n AgentGenerationEndArgs,\n AgentGenerationModelInfo,\n AgentGenerationStartArgs,\n AgentTraceOptions,\n} from \"../../observability/types\";\nimport {\n type ResolvedRetryOptions,\n resolveRetryOptions,\n retryDelayMs,\n retryErrorAttributes,\n waitForRetry,\n} from \"../../retry\";\nimport type { AgentMiddleware } from \"../../tool/middleware\";\nimport { createAsyncQueue } from \"../async-queue\";\nimport { type CompletionRequestFor, createCompletionRequest } from \"../completion-request\";\nimport { extractRagText } from \"../rag-text\";\nimport { registerAgentApprovalRequestDetails } from \"./approval-details\";\nimport type { ToolApprovalRequest } from \"./approval-request\";\nimport { toolMayRequireApproval } from \"./approval-requirement\";\nimport { AgentRunMemory, type MemoryPreparation } from \"./memory\";\nimport { fetchContextDocuments, fetchToolDefinitions } from \"./retrieval\";\nimport { getInternalAgentRunOptions } from \"./run-options\";\nimport { assertNonnegativeSafeInteger, assertPositiveSafeInteger } from \"./run-validation\";\nimport { CompletionStreamAccumulator } from \"./stream-accumulator\";\nimport { addTurn, addTurnToToolCallDelta, isGenerationDeltaEvent } from \"./stream-events\";\nimport {\n type AgentToolEventPayload,\n ToolCallExecutor,\n type ToolExecutionEventPayload,\n type ToolExecutionObservation,\n type ToolResultEventPayload,\n} from \"./tool-execution\";\n\ntype AgentRunCreateOptions = AgentRunOptions & {\n memoryContext?: MemoryContext | undefined;\n};\n\ntype PendingApproval = {\n request: ToolApprovalRequest;\n resolve(decision: AgentApprovalDecision): void;\n reject(error: unknown): void;\n};\n\ntype DeferredSignal = {\n promise: Promise<void>;\n resolve(): void;\n};\n\ntype StreamingCompletionState = {\n response: CompletionResponse | undefined;\n firstDeltaMs: number | undefined;\n emittedToolCallIds: Set<string>;\n providerErrorUsage: Usage;\n};\n\nfunction deferredSignal(): DeferredSignal {\n let resolve = () => {};\n const promise = new Promise<void>((done) => {\n resolve = done;\n });\n return { promise, resolve };\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\nexport class AgentRun<M extends CompletionModel = CompletionModel> {\n private chatHistory: MessageType[];\n private maxTurnCount: number;\n private activeHook: AgentHook | undefined;\n private readonly activeLifecycle: AgentLifecycle | 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: MessageType[] = [];\n private runState: \"idle\" | \"running\" | \"completed\" | \"errored\" | \"cancelled\" = \"idle\";\n private readonly memoryRecorder: AgentRunMemory;\n private readonly memoryContext: MemoryContext | undefined;\n private pendingApproval: PendingApproval | undefined;\n private approvalSignal = deferredSignal();\n private activeRunId: string | undefined;\n private readonly requestedRunId: string | undefined;\n private currentUsage = Usage.empty();\n private currentMessages: MessageType[] = [];\n private cancellationError: AgentRunCancelledError | undefined;\n private activeGeneration: { turn: number; observers: ActiveGenerationObservers } | undefined;\n\n private constructor(\n private readonly agent: Agent<M>,\n private promptMessage: MessageType,\n initialHistory: MessageType[] = [],\n options: AgentRunCreateOptions = {},\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.requestedRunId = normalizeRequestedRunId(internalOptions?.runId);\n this.activeLifecycle = composeAgentLifecycle(agent.lifecycle, options.lifecycle);\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((tool) => toolMayRequireApproval(tool.requiresApproval))\n ? 1\n : configuredConcurrency;\n this.traceOptions = options.trace;\n this.completionRetryOptions =\n options.retries === undefined ? undefined : resolveRetryOptions(options.retries);\n this.requestMiddlewares = [...(options.middlewares ?? [])];\n this.memoryContext = options.memoryContext;\n this.memoryRecorder = new AgentRunMemory(agent, options.memoryContext, initialHistory);\n }\n\n static fromAgent<M extends CompletionModel>(\n agent: Agent<M>,\n input: AgentInput,\n options: AgentRunCreateOptions = {},\n ): AgentRun<M> {\n const normalized = normalizeAgentInput(input);\n return new AgentRun(agent, normalized.prompt, normalized.history, options);\n }\n\n steer(input: string | MessageType | MessageType[]): boolean {\n if (this.isTerminal() || this.cancellationError !== undefined) {\n return false;\n }\n\n this.steeringMessages.push(...normalizeSteeringInput(input));\n return true;\n }\n\n waitForApproval(): Promise<void> {\n return this.pendingApproval === undefined ? this.approvalSignal.promise : Promise.resolve();\n }\n\n approvalResult(): AgentApprovalRequiredResult {\n const snapshot = this.approvalSnapshot();\n return { status: \"approval_required\", ...snapshot };\n }\n\n approvalEvent(): AgentApprovalRequiredEvent {\n const snapshot = this.approvalSnapshot();\n return { type: \"approval_required\", ...snapshot };\n }\n\n resolveApproval(decision: AgentApprovalDecision): void {\n const pending = this.pendingApproval;\n if (pending === undefined) {\n throw new TypeError(\"Agent run has no pending tool approval.\");\n }\n this.pendingApproval = undefined;\n this.approvalSignal = deferredSignal();\n pending.resolve(decision);\n }\n\n cancel(reason: string): void {\n if (this.isTerminal() || this.cancellationError !== undefined) {\n return;\n }\n const messages =\n this.currentMessages.length === 0 ? [this.promptMessage] : [...this.currentMessages];\n const error = new AgentRunCancelledError([...this.chatHistory, ...messages], reason);\n this.cancellationError = error;\n const pending = this.pendingApproval;\n if (pending !== undefined) {\n this.pendingApproval = undefined;\n this.approvalSignal = deferredSignal();\n pending.reject(error);\n }\n }\n\n async generate(): Promise<AgentResponse> {\n this.startRun();\n const runId = this.requestedRunId ?? globalThis.crypto.randomUUID();\n this.activeRunId = runId;\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\n try {\n const memoryPreparation = await this.memoryRecorder.prepareHistory(runId, newMessages.length);\n this.chatHistory = memoryPreparation.history;\n usage = Usage.add(usage, memoryPreparation.usage);\n runObservers = await this.startRunObservers(runId);\n await this.recordMemoryCompaction(memoryPreparation, runObservers);\n await this.activeLifecycle?.onStart?.({\n runId,\n input: lifecycleSnapshot(this.promptMessage),\n history: lifecycleSnapshot(this.chatHistory),\n maxTurns: this.maxTurnCount,\n });\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 output = inputResult.message ?? \"The request was blocked by a guardrail.\";\n const result: AgentResponse = {\n status: \"completed\",\n runId,\n output,\n usage,\n messages: [this.promptMessage, Message.assistant(output)],\n trace: runObservers.trace,\n guardrails: [...this.guardrailDecisions],\n };\n await this.runLifecycleFinish(result);\n await runObservers.end(result);\n this.runState = \"completed\";\n return result;\n }\n\n newMessages = [this.promptMessage];\n await this.memoryRecorder.commitAcceptedInput(runId, newMessages);\n const pendingTurnMessages = this.memoryRecorder.pendingTurnMessages(newMessages);\n await this.runRunStartHook(newMessages);\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 usage = Usage.add(usage, response.usage);\n this.updateApprovalProgress(runId, usage, 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 ToolCall => 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 if (\n await this.drainSteeringMessages(runId, currentTurns, newMessages, pendingTurnMessages)\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: AgentResponse = {\n status: \"completed\",\n runId,\n output: guardedOutput.output,\n usage,\n messages: [...newMessages],\n trace: runObservers.trace,\n guardrails: [...this.guardrailDecisions],\n ...generationArtifacts(newMessages),\n };\n await this.runRunEndHook(result, newMessages);\n await this.memoryRecorder.commitCompletedRun(\n runId,\n currentTurns,\n newMessages,\n pendingTurnMessages,\n );\n await this.runLifecycleFinish(result);\n await runObservers.end(result);\n this.runState = \"completed\";\n return result;\n }\n\n this.updateApprovalProgress(runId, usage, newMessages);\n const 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 const toolMessage = Message.tool(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 reportedError = await this.reportRunFailure(\n error,\n runId,\n usage,\n newMessages,\n runObservers,\n );\n this.runState = reportedError instanceof AgentRunCancelledError ? \"cancelled\" : \"errored\";\n throw reportedError;\n }\n }\n\n async *events(includeToolCallDeltas = true): AsyncIterable<AgentStreamEvent> {\n if (!this.agent.model.capabilities.streaming || !isStreamingCompletionModel(this.agent.model)) {\n throw new Error(\"This completion model does not support streaming\");\n }\n\n this.startRun();\n const runId = this.requestedRunId ?? globalThis.crypto.randomUUID();\n this.activeRunId = runId;\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\n try {\n const memoryPreparation = await this.memoryRecorder.prepareHistory(runId, newMessages.length);\n this.chatHistory = memoryPreparation.history;\n usage = Usage.add(usage, memoryPreparation.usage);\n runObservers = await this.startRunObservers(runId);\n await this.recordMemoryCompaction(memoryPreparation, runObservers);\n await this.activeLifecycle?.onStart?.({\n runId,\n input: lifecycleSnapshot(this.promptMessage),\n history: lifecycleSnapshot(this.chatHistory),\n maxTurns: this.maxTurnCount,\n });\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 output = inputResult.message ?? \"The request was blocked by a guardrail.\";\n const result: AgentResponse = {\n status: \"completed\",\n runId,\n output,\n usage,\n messages: [this.promptMessage, Message.assistant(output)],\n trace: runObservers.trace,\n guardrails: [...this.guardrailDecisions],\n };\n await this.runLifecycleFinish(result);\n await runObservers.end(result);\n this.runState = \"completed\";\n yield {\n type: \"final\",\n runId,\n output: result.output,\n usage: result.usage,\n messages: result.messages,\n trace: result.trace,\n guardrails: result.guardrails,\n };\n return;\n }\n\n newMessages = [this.promptMessage];\n await this.memoryRecorder.commitAcceptedInput(runId, newMessages);\n const pendingTurnMessages = this.memoryRecorder.pendingTurnMessages(newMessages);\n await this.runRunStartHook(newMessages);\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 = this.shouldBufferStreamResponseEvents();\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 includeToolCallDeltas,\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 const generationEndArgs: AgentGenerationEndArgs = {\n turn: currentTurns,\n response,\n ...(firstDeltaMs === undefined ? {} : { firstDeltaMs }),\n };\n this.activeGeneration = undefined;\n await generationObservers.end(generationEndArgs);\n response = await this.runCompletionResponseMiddlewares(request, response, currentTurns);\n usage = Usage.add(usage, response.usage);\n this.updateApprovalProgress(runId, usage, 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 ToolCall => 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;\n }\n }\n yield {\n type: \"turn_end\",\n turn: currentTurns,\n response,\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 if (\n await this.drainSteeringMessages(runId, currentTurns, newMessages, pendingTurnMessages)\n ) {\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;\n }\n } else {\n for (const toolCall of toolCalls) {\n if (!emittedToolCallIds.has(toolCall.id)) {\n yield { type: \"tool_call\", turn: currentTurns, toolCall };\n }\n }\n }\n this.updateApprovalProgress(runId, usage, newMessages);\n yield {\n type: \"turn_end\",\n turn: currentTurns,\n response,\n firstDeltaMs,\n };\n\n const toolExecution = this.executeStreamingToolCalls(runId, toolCalls, newMessages, {\n turn: currentTurns,\n runObservers,\n toolDefinitions: request.tools,\n includeToolCallDeltas,\n });\n for await (const result of toolExecution.events) {\n yield { turn: currentTurns, ...result };\n }\n const toolResults = await toolExecution.results;\n const toolMessage = Message.tool(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 reportedError = await this.reportRunFailure(\n error,\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 throw reportedError;\n } finally {\n if (this.runState === \"running\") {\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 }\n }\n }\n\n private async runCompletion(\n request: CompletionRequestFor<M>,\n turn: number,\n runObservers: ActiveAgentRunObservers,\n ): Promise<CompletionResponse> {\n assertCompletionRequestSupported(this.agent.model, request);\n const providerRequest = this.providerTraceRequest(request);\n const generationObservers = await runObservers.startGeneration(\n this.generationStartArgs(turn, request, providerRequest),\n );\n try {\n for (let attempt = 1; ; attempt += 1) {\n let response: CompletionResponse;\n try {\n response = await this.agent.model.completion(request);\n } catch (error) {\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 );\n continue;\n }\n await generationObservers.end({ turn, response });\n return response;\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<CompletionRequestFor<M>> {\n const ragText = extractRagText(prompt);\n const documents = await fetchContextDocuments(this.agent, ragText);\n const toolDefinitions = await fetchToolDefinitions(this.agent, ragText);\n const request = createCompletionRequest([...history, prompt], {\n model: this.agent.model,\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 additionalParams: this.agent.additionalParams,\n toolChoice: this.agent.toolChoice,\n outputSchema: this.agent.outputSchema,\n });\n return (await this.runCompletionRequestMiddlewares(request, turn)) as CompletionRequestFor<M>;\n }\n\n private async *streamCompletion(args: {\n request: CompletionRequestFor<M>;\n turn: number;\n includeToolCallDeltas: boolean;\n bufferResponseEvents: boolean;\n bufferOutputDeltas: boolean;\n generationStartedAt: number;\n generationObservers: ActiveGenerationObservers;\n runObservers: ActiveAgentRunObservers;\n state: StreamingCompletionState;\n }): AsyncIterable<AgentStreamEvent> {\n const model = this.agent.model;\n if (!isStreamingCompletionModel(model)) {\n throw new TypeError(\"Streaming completion requires a streaming-capable model.\");\n }\n const accumulator = new CompletionStreamAccumulator();\n for (let attempt = 1; ; attempt += 1) {\n let hasProviderProgress = false;\n try {\n for await (const event of model.streamCompletion(args.request)) {\n if (event.type === \"error\") {\n if (event.usage !== undefined) {\n args.state.providerErrorUsage = Usage.add(args.state.providerErrorUsage, event.usage);\n }\n throw event.error;\n }\n hasProviderProgress = true;\n if (args.state.firstDeltaMs === undefined && isGenerationDeltaEvent(event.type)) {\n args.state.firstDeltaMs = Date.now() - args.generationStartedAt;\n }\n const mapped = accumulator.accept(event);\n if (args.includeToolCallDeltas && 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.id);\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);\n }\n }\n }\n args.state.response = accumulator.response();\n return;\n } catch (error) {\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 );\n }\n }\n }\n\n private async *completeStreamingRun(args: {\n runId: string;\n turn: number;\n request: CompletionRequestFor<M>;\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> {\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;\n }\n }\n if (!args.emittedTurnEnd) {\n yield {\n type: \"turn_end\",\n turn: args.turn,\n response,\n firstDeltaMs: args.firstDeltaMs,\n };\n }\n\n const result: AgentResponse = {\n status: \"completed\",\n runId: args.runId,\n output: guardedOutput.output,\n usage: args.usage,\n messages: [...args.newMessages],\n trace: args.runObservers.trace,\n guardrails: [...this.guardrailDecisions],\n ...generationArtifacts(args.newMessages),\n };\n await this.runRunEndHook(result, args.newMessages);\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(result);\n this.runState = \"completed\";\n yield {\n type: \"final\",\n runId: args.runId,\n output: result.output,\n usage: result.usage,\n contextUsage: result.contextUsage,\n messages: result.messages,\n trace: result.trace,\n guardrails: result.guardrails,\n sources: result.sources,\n providerToolCalls: result.providerToolCalls,\n };\n }\n\n private generatedAssistantMessage(\n response: CompletionResponse,\n request: CompletionRequestFor<M>,\n ): MessageType {\n const metadata: JsonObject = {\n anvia: {\n generation: {\n provider: this.agent.model.provider,\n model: request.model ?? this.agent.model.defaultModel,\n usage: { ...response.usage },\n ...(response.contextUsage === undefined ? {} : { contextUsage: response.contextUsage }),\n ...(response.sources === undefined ? {} : { sources: response.sources }),\n ...(response.providerToolCalls === undefined\n ? {}\n : { providerToolCalls: response.providerToolCalls }),\n },\n },\n };\n return Message.assistant(response.choice, {\n ...(response.messageId === undefined ? {} : { id: response.messageId }),\n metadata,\n });\n }\n\n private providerTraceRequest(\n request: CompletionRequestFor<M>,\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: CompletionRequestFor<M>,\n providerRequest: JsonObject | undefined,\n ): AgentGenerationStartArgs & { modelInfo: AgentGenerationModelInfo } {\n return {\n turn,\n request,\n modelInfo: {\n provider: this.agent.model.provider,\n defaultModel: this.agent.model.defaultModel,\n capabilities: this.agent.model.capabilities,\n },\n ...(providerRequest === undefined ? {} : { providerRequest }),\n };\n }\n\n private retryOptionsForFailure(\n error: unknown,\n attempt: number,\n turn: number,\n streaming: boolean,\n ): ResolvedRetryOptions | undefined {\n const options = this.completionRetryOptions;\n if (options === undefined || attempt >= options.maxAttempts) {\n return undefined;\n }\n const shouldRetry = options.shouldRetry({\n error,\n attempt,\n maxAttempts: options.maxAttempts,\n turn,\n streaming,\n });\n return shouldRetry ? options : undefined;\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 ): Promise<void> {\n const delayMs = retryDelayMs(options, attempt);\n await runObservers.event({\n name: \"completion.retry\",\n level: \"WARNING\",\n attributes: {\n turn,\n attempt,\n nextAttempt: attempt + 1,\n maxAttempts: options.maxAttempts,\n delayMs,\n streaming,\n ...retryErrorAttributes(error),\n },\n });\n await waitForRetry(delayMs);\n }\n\n private async executeToolCalls(\n runId: string,\n toolCalls: ToolCall[],\n newMessages: MessageType[],\n onResult?: (result: ToolResultEventPayload) => void,\n onStreamEvent?: (event: AgentToolEventPayload) => void,\n observation?: ToolExecutionObservation,\n ): Promise<ToolResult[]> {\n const executor = new ToolCallExecutor(\n this.agent,\n this.activeHook,\n (request) => this.suspendForApproval(request),\n this.activeLifecycle,\n {\n runId,\n sessionId: this.memoryContext?.sessionId,\n metadata: this.memoryContext?.metadata,\n },\n this.concurrency,\n this.requestMiddlewares,\n observation?.includeToolCallDeltas ?? false,\n (reason) => this.cancelled(newMessages, reason),\n );\n return executor.execute(toolCalls, onResult, onStreamEvent, observation);\n }\n\n private executeStreamingToolCalls(\n runId: string,\n toolCalls: ToolCall[],\n newMessages: MessageType[],\n observation: ToolExecutionObservation,\n ): {\n events: AsyncIterable<ToolExecutionEventPayload>;\n results: Promise<ToolResult[]>;\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 suspendForApproval(request: ToolApprovalRequest): Promise<AgentApprovalDecision> {\n if (this.cancellationError !== undefined) {\n return Promise.reject(this.cancellationError);\n }\n if (this.pendingApproval !== undefined) {\n throw new Error(\"Agent run already has a pending tool approval.\");\n }\n return new Promise<AgentApprovalDecision>((resolve, reject) => {\n this.pendingApproval = { request, resolve, reject };\n this.approvalSignal.resolve();\n });\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 approvalSnapshot(): Omit<AgentApprovalRequiredResult, \"status\"> {\n const pending = this.pendingApproval;\n const runId = this.activeRunId;\n if (pending === undefined || runId === undefined) {\n throw new TypeError(\"Agent run has no pending tool approval.\");\n }\n const approval = {\n id: pending.request.id,\n toolName: pending.request.toolName,\n input: lifecycleSnapshot(pending.request.args),\n ...(pending.request.toolCallId === undefined\n ? {}\n : { toolCallId: pending.request.toolCallId }),\n ...(pending.request.reason === undefined ? {} : { reason: pending.request.reason }),\n };\n registerAgentApprovalRequestDetails(approval, pending.request);\n return {\n runId,\n approval,\n usage: lifecycleSnapshot(this.currentUsage),\n messages: lifecycleSnapshot(this.currentMessages),\n };\n }\n\n private updateApprovalProgress(runId: string, usage: Usage, messages: MessageType[]): void {\n this.activeRunId = runId;\n this.currentUsage = usage;\n this.currentMessages = [...messages];\n }\n\n private async runLifecycleFinish(result: AgentResponse): Promise<void> {\n await this.activeLifecycle?.onFinish?.({\n runId: result.runId,\n output: result.output,\n usage: lifecycleSnapshot(result.usage),\n messages: lifecycleSnapshot(result.messages),\n });\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 runObservers?.error({\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 // Error hooks are diagnostic cleanup and must not replace the run failure.\n }\n await this.runLifecycleError(error, runId, usage, messages);\n return error;\n }\n\n private async runOutputGuardrailsForResponse(\n runId: string,\n usage: Usage,\n response: CompletionResponse,\n messages: MessageType[],\n runObservers: ActiveAgentRunObservers,\n ): Promise<{\n output: string;\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 output = result.blocked\n ? (result.message ?? \"The response was blocked by a guardrail.\")\n : result.outputText;\n if (output === originalOutput) {\n return { output, response, decisions: result.decisions };\n }\n return {\n output,\n response: {\n ...response,\n choice: [AssistantContent.text(output)],\n },\n decisions: result.decisions,\n };\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 conflictRetries: compaction.conflictRetries,\n inputTokens: preparation.usage.inputTokens,\n outputTokens: preparation.usage.outputTokens,\n totalTokens: preparation.usage.totalTokens,\n },\n });\n }\n\n private guardrailRunContext(runId: string): GuardrailRunContext {\n const context: GuardrailRunContext = {\n agentId: this.agent.id,\n runId,\n };\n if (this.memoryContext !== undefined) {\n context.sessionId = this.memoryContext.sessionId;\n if (this.memoryContext.metadata !== undefined) {\n context.metadata = this.memoryContext.metadata;\n }\n }\n return context;\n }\n\n private async startRunObservers(runId: string): Promise<ActiveAgentRunObservers> {\n const failOnObserverError =\n this.traceOptions?.failOnObserverError === true ||\n this.agent.observers.some((registration) => registration.failOnObserverError === true);\n return startAgentRunObservers(\n this.agent.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 failOnObserverError,\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(result: AgentResponse, newMessages: MessageType[]): Promise<void> {\n const action = await this.activeHook?.onRunEnd?.({\n output: result.output,\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: CompletionRequestFor<M>,\n turn: number,\n ): Promise<CompletionRequestFor<M>> {\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 as CompletionRequestFor<M>;\n }\n }\n return current;\n }\n\n private async runCompletionResponseMiddlewares(\n request: CompletionRequestFor<M>,\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 ): Promise<boolean> {\n const messages = this.steeringMessages.splice(0);\n if (messages.length === 0) {\n return false;\n }\n\n newMessages.push(...messages);\n await this.memoryRecorder.commitMessages(runId, turn, messages, pendingTurnMessages);\n return true;\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 (\n this.runState === \"completed\" || this.runState === \"errored\" || this.runState === \"cancelled\"\n );\n }\n\n private cancelled(newMessages: MessageType[], reason: string): AgentRunCancelledError {\n return new AgentRunCancelledError([...this.chatHistory, ...newMessages], reason);\n }\n}\n\nfunction normalizeAgentInput(prompt: AgentInput): {\n prompt: MessageType;\n history: MessageType[];\n} {\n if (typeof prompt === \"string\") {\n return { prompt: Message.user(prompt), history: [] };\n }\n if (!Array.isArray(prompt)) {\n return { prompt, history: [] };\n }\n if (prompt.length === 0) {\n throw new TypeError(\"Agent input transcript must contain at least one message.\");\n }\n const activePrompt = prompt.at(-1);\n if (activePrompt === undefined) {\n throw new TypeError(\"Agent input transcript must contain at least one message.\");\n }\n return {\n prompt: activePrompt,\n history: prompt.slice(0, -1),\n };\n}\n\nfunction normalizeSteeringInput(input: string | MessageType | MessageType[]): MessageType[] {\n if (typeof input === \"string\") {\n return [Message.user(input)];\n }\n return Array.isArray(input) ? [...input] : [input];\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.content === 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.content) {\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 contextUsage?: import(\"../../completion/index\").ContextUsage;\n} {\n const sources = new Map<string, CompletionSource>();\n const providerToolCalls = new Map<string, ProviderToolCall>();\n let contextUsage: import(\"../../completion/index\").ContextUsage | undefined;\n for (const message of messages) {\n const metadata = getAssistantGenerationMetadata(message);\n if (metadata !== undefined) {\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 return {\n ...(sources.size === 0 ? {} : { sources: [...sources.values()] }),\n ...(providerToolCalls.size === 0 ? {} : { providerToolCalls: [...providerToolCalls.values()] }),\n ...(contextUsage === undefined ? {} : { contextUsage }),\n };\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 return message.content\n .flatMap((content) => {\n if (content.type === \"text\") {\n return [content.text];\n }\n if (content.type === \"document\" && content.source.type === \"text\") {\n return [content.source.text];\n }\n return [];\n })\n .join(\"\\n\");\n}\n\nfunction guardrailDecisionAttributes(\n decision: GuardrailDecisionRecord,\n): Record<string, JsonValue | undefined> {\n const attributes: Record<string, JsonValue | undefined> = {\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","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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEO,IAAM,gBAAN,cAA4B,MAAM;AAAA,EACvC,YACW,UACA,aACA,QACT;AACA,UAAM,2BAA2B,QAAQ,EAAE;AAJlC;AACA;AACA;AAGT,SAAK,OAAO;AAAA,EACd;AAAA,EANW;AAAA,EACA;AAAA,EACA;AAKb;AAEO,IAAM,yBAAN,cAAqC,MAAM;AAAA,EAChD,YACW,aACA,QACT;AACA,UAAM,wBAAwB,MAAM,EAAE;AAH7B;AACA;AAGT,SAAK,OAAO;AAAA,EACd;AAAA,EALW;AAAA,EACA;AAKb;;;ACNA,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;;;AC9BO,SAAS,WACd,MACwB;AACxB,SAAO;AACT;AAEO,SAAS,UAAU,QAA4B;AACpD,SAAO,EAAE,MAAM,aAAa,OAAO;AACrC;AAEO,SAAS,SAAS,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