@anvia/core 1.0.0-rc.2 → 1.0.0-rc.4
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 +77 -10
- package/dist/agent/index.d.ts +20 -13
- package/dist/agent/index.js +36 -15
- package/dist/{agent-yBG8e9Jj.d.ts → agent-CXScUOpX.d.ts} +12 -15
- package/dist/chunk-3RM57ZT2.js +31 -0
- package/dist/chunk-3RM57ZT2.js.map +1 -0
- package/dist/{chunk-DBSCKTUL.js → chunk-5GXSQYQT.js} +1744 -838
- package/dist/chunk-5GXSQYQT.js.map +1 -0
- package/dist/{chunk-KIDGIJM7.js → chunk-AZB6N7P4.js} +94 -86
- package/dist/chunk-AZB6N7P4.js.map +1 -0
- package/dist/{chunk-KR3RCCHJ.js → chunk-D2ECOWN5.js} +26 -11
- package/dist/chunk-D2ECOWN5.js.map +1 -0
- package/dist/{chunk-EINTGEGY.js → chunk-FXAIYTRE.js} +101 -26
- package/dist/chunk-FXAIYTRE.js.map +1 -0
- package/dist/{chunk-FMHLROPQ.js → chunk-GQL5KRAH.js} +13 -33
- package/dist/chunk-GQL5KRAH.js.map +1 -0
- package/dist/{chunk-D37WMSP6.js → chunk-J2W63PJI.js} +50 -10
- package/dist/chunk-J2W63PJI.js.map +1 -0
- package/dist/{chunk-OJH6HWHX.js → chunk-KFR4CDGK.js} +8 -2
- package/dist/chunk-KFR4CDGK.js.map +1 -0
- package/dist/{chunk-TIZYTPJO.js → chunk-PK5LKOFL.js} +33 -2
- package/dist/chunk-PK5LKOFL.js.map +1 -0
- package/dist/{chunk-XKYYBABH.js → chunk-RFHQY2IO.js} +2 -2
- package/dist/chunk-TRQ3XRFD.js +54 -0
- package/dist/chunk-TRQ3XRFD.js.map +1 -0
- package/dist/{chunk-CWM7B2OO.js → chunk-VKYZZXP5.js} +10 -2
- package/dist/chunk-VKYZZXP5.js.map +1 -0
- package/dist/{chunk-77AIYARB.js → chunk-XYTPYUGB.js} +29 -19
- package/dist/chunk-XYTPYUGB.js.map +1 -0
- package/dist/{chunk-4WI3VGZK.js → chunk-ZCPOIDAQ.js} +3 -3
- package/dist/{client-B8DT1vUG.d.ts → client-DvUatElp.d.ts} +4 -3
- package/dist/completion/index.d.ts +3 -3
- package/dist/completion/index.js +2 -2
- package/dist/documents/index.d.ts +34 -0
- package/dist/documents/index.js +315 -0
- package/dist/documents/index.js.map +1 -0
- package/dist/{dynamic-tools-KwEGRbHp.d.ts → dynamic-tools-AEBOTgu1.d.ts} +3 -3
- package/dist/embeddings/index.js +2 -1
- package/dist/evals/index.d.ts +19 -11
- package/dist/evals/index.js +88 -55
- package/dist/evals/index.js.map +1 -1
- package/dist/extractor/index.d.ts +1 -1
- package/dist/extractor/index.js +3 -3
- package/dist/guardrails/index.d.ts +6 -129
- package/dist/guardrails/index.js +1 -1
- package/dist/image-generation/index.d.ts +1 -1
- package/dist/index.d.ts +15 -14
- package/dist/index.js +49 -28
- package/dist/interactions-csssHYcN.d.ts +174 -0
- package/dist/internal/agent.d.ts +18 -22
- package/dist/internal/agent.js +45 -14
- package/dist/internal/agent.js.map +1 -1
- package/dist/mcp/index.d.ts +4 -4
- package/dist/mcp/index.js +6 -5
- package/dist/memory/index.d.ts +3 -3
- package/dist/memory/index.js +3 -3
- package/dist/{message-schema-Cn7ezRfJ.d.ts → message-schema-B2M7AYzR.d.ts} +1 -1
- package/dist/observability/index.d.ts +8 -7
- package/dist/observability/index.js +3 -3
- package/dist/pipeline/index.d.ts +18 -18
- package/dist/pipeline/index.js +20 -29
- package/dist/pipeline/index.js.map +1 -1
- package/dist/skills/index.d.ts +4 -4
- package/dist/skills/index.js +6 -5
- package/dist/speech-generation/index.d.ts +1 -1
- package/dist/text-C_6eKrbC.d.ts +32 -0
- package/dist/{think-tool-6H2QNQzQ.d.ts → think-tool-D8frXxwV.d.ts} +16 -2
- package/dist/tool/index.d.ts +6 -6
- package/dist/tool/index.js +9 -4
- package/dist/{tool--Mz4v1eL.d.ts → tool-r62gf3QY.d.ts} +3 -2
- package/dist/transcription/index.d.ts +1 -1
- package/dist/{types-Dld1TpWj.d.ts → types-C3gv9EX6.d.ts} +1 -1
- package/dist/{types-3x3mOLHU.d.ts → types-CElwurHZ.d.ts} +56 -35
- package/dist/types-CIPaIbZo.d.ts +105 -0
- package/dist/{types-CQ_ioXWK.d.ts → types-D9rKQ_as.d.ts} +24 -2
- package/dist/{types-BVzM4RsC.d.ts → types-DbolvLtZ.d.ts} +1 -1
- package/dist/{types-DiJqJejp.d.ts → types-RT3cuyRk.d.ts} +1 -1
- package/dist/vector-store/index.d.ts +7 -6
- package/dist/vector-store/index.js +6 -3
- package/package.json +6 -6
- package/dist/chunk-77AIYARB.js.map +0 -1
- package/dist/chunk-CWM7B2OO.js.map +0 -1
- package/dist/chunk-D37WMSP6.js.map +0 -1
- package/dist/chunk-DBSCKTUL.js.map +0 -1
- package/dist/chunk-EINTGEGY.js.map +0 -1
- package/dist/chunk-FMHLROPQ.js.map +0 -1
- package/dist/chunk-KIDGIJM7.js.map +0 -1
- package/dist/chunk-KR3RCCHJ.js.map +0 -1
- package/dist/chunk-OJH6HWHX.js.map +0 -1
- package/dist/chunk-TIZYTPJO.js.map +0 -1
- package/dist/loaders/index.d.ts +0 -87
- package/dist/loaders/index.js +0 -299
- package/dist/loaders/index.js.map +0 -1
- package/dist/middleware-C7PdmKF7.d.ts +0 -56
- /package/dist/{chunk-XKYYBABH.js.map → chunk-RFHQY2IO.js.map} +0 -0
- /package/dist/{chunk-4WI3VGZK.js.map → chunk-ZCPOIDAQ.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agent/interactions.ts","../src/agent/tool-state.ts","../src/hooks/control.ts","../src/agent/vector-context.ts","../src/internal/agent-runtime/run-options.ts","../src/agent/lifecycle.ts","../src/agent/output-schema.ts","../src/internal/async-queue.ts","../src/internal/rag-text.ts","../src/internal/agent-runtime/continuation-state.ts","../src/internal/agent-runtime/interaction-suspension.ts","../src/internal/agent-runtime/memory.ts","../src/internal/agent-runtime/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/agent-stream.ts","../src/agent/agent-tool.ts","../src/agent/ids.ts","../src/memory/options.ts","../src/agent/resolve-options.ts","../src/agent/snapshot.ts","../src/agent/tool-catalog.ts","../src/agent/agent.ts"],"sourcesContent":["import { z } from \"zod\";\nimport {\n isJsonValue,\n type JsonObject,\n type JsonValue,\n type ToolQuestionAnswer,\n} from \"../completion\";\n\nexport type AgentQuestionChoice = Readonly<{\n label: string;\n value: string;\n}>;\n\nexport type AgentQuestionPrompt = Readonly<{\n id: string;\n text: string;\n choices?: readonly AgentQuestionChoice[];\n allowCustom?: boolean;\n}>;\n\nexport type AgentQuestionAnswer = ToolQuestionAnswer;\n\ntype AgentInteractionRequestBase = Readonly<{\n id: string;\n toolName: string;\n toolCallId: string;\n callId?: string;\n internalCallId: string;\n}>;\n\nexport type AgentToolApprovalRequest = AgentInteractionRequestBase &\n Readonly<{\n type: \"tool-approval\";\n input: JsonValue;\n reason?: string;\n }>;\n\nexport type AgentToolQuestionRequest = AgentInteractionRequestBase &\n Readonly<{\n type: \"tool-question\";\n questions: readonly AgentQuestionPrompt[];\n }>;\n\nexport type AgentInteractionRequest = AgentToolApprovalRequest | AgentToolQuestionRequest;\n\nexport type AgentInteractionResponse =\n | Readonly<{\n type: \"tool-approval\";\n approved: boolean;\n reason?: string;\n }>\n | Readonly<{\n type: \"tool-question\";\n answers: readonly AgentQuestionAnswer[];\n }>;\n\nexport type AgentContinuation = Readonly<{\n version: 1;\n agentId: string;\n sourceRunId: string;\n interaction: AgentInteractionRequest;\n state: JsonObject;\n}>;\n\nconst nonblank = z.string().trim().min(1);\nconst jsonValueSchema = z.custom<JsonValue>(isJsonValue, {\n message: \"Expected a strict JSON value\",\n});\nconst jsonObjectSchema = z.custom<JsonObject>(\n (value) =>\n typeof value === \"object\" && value !== null && !Array.isArray(value) && isJsonValue(value),\n { message: \"Expected a strict JSON object\" },\n);\n\nconst questionChoiceSchema = z\n .object({\n label: nonblank,\n value: nonblank,\n })\n .strict();\n\nconst questionPromptSchema = z\n .object({\n id: nonblank,\n text: nonblank,\n choices: z.array(questionChoiceSchema).min(1).optional(),\n allowCustom: z.boolean().optional(),\n })\n .strict()\n .superRefine((question, context) => {\n if (question.choices === undefined && question.allowCustom === false) {\n context.addIssue({\n code: \"custom\",\n message: \"A free-text question cannot disable custom answers.\",\n path: [\"allowCustom\"],\n });\n }\n const values = new Set<string>();\n for (const [index, choice] of (question.choices ?? []).entries()) {\n if (values.has(choice.value)) {\n context.addIssue({\n code: \"custom\",\n message: \"Question choice values must be unique.\",\n path: [\"choices\", index, \"value\"],\n });\n }\n values.add(choice.value);\n }\n });\n\nconst questionAnswerSchema = z\n .object({\n questionId: nonblank,\n value: nonblank,\n })\n .strict();\n\nconst interactionBase = {\n id: nonblank,\n toolName: nonblank,\n toolCallId: nonblank,\n callId: z.string().optional(),\n internalCallId: nonblank,\n};\n\nconst approvalRequestSchema = z\n .object({\n type: z.literal(\"tool-approval\"),\n ...interactionBase,\n input: jsonValueSchema,\n reason: z.string().optional(),\n })\n .strict();\n\nconst questionRequestSchema = z\n .object({\n type: z.literal(\"tool-question\"),\n ...interactionBase,\n questions: z.array(questionPromptSchema).min(1),\n })\n .strict()\n .superRefine((request, context) => {\n const ids = new Set<string>();\n for (const [index, question] of request.questions.entries()) {\n if (ids.has(question.id)) {\n context.addIssue({\n code: \"custom\",\n message: \"Question IDs must be unique.\",\n path: [\"questions\", index, \"id\"],\n });\n }\n ids.add(question.id);\n }\n });\n\nexport const agentInteractionRequestSchema = z.discriminatedUnion(\"type\", [\n approvalRequestSchema,\n questionRequestSchema,\n]);\n\nexport const agentInteractionResponseSchema = z.discriminatedUnion(\"type\", [\n z\n .object({\n type: z.literal(\"tool-approval\"),\n approved: z.boolean(),\n reason: z.string().optional(),\n })\n .strict(),\n z\n .object({\n type: z.literal(\"tool-question\"),\n answers: z.array(questionAnswerSchema),\n })\n .strict(),\n]);\n\nexport const agentContinuationSchema = z\n .object({\n version: z.literal(1),\n agentId: nonblank,\n sourceRunId: nonblank,\n interaction: agentInteractionRequestSchema,\n state: jsonObjectSchema,\n })\n .strict();\n\nexport function parseAgentInteractionRequest(value: unknown): AgentInteractionRequest {\n return freeze(agentInteractionRequestSchema.parse(value)) as AgentInteractionRequest;\n}\n\nexport function parseAgentInteractionResponse(value: unknown): AgentInteractionResponse {\n return freeze(agentInteractionResponseSchema.parse(value)) as AgentInteractionResponse;\n}\n\nexport function parseAgentQuestionPrompts(value: unknown): readonly AgentQuestionPrompt[] {\n const request = questionRequestSchema.parse({\n type: \"tool-question\",\n id: \"validation\",\n toolName: \"validation\",\n toolCallId: \"validation\",\n internalCallId: \"validation\",\n questions: value,\n });\n return freeze(request.questions) as readonly AgentQuestionPrompt[];\n}\n\nexport function parseAgentContinuation(value: unknown): AgentContinuation {\n return freeze(agentContinuationSchema.parse(value)) as AgentContinuation;\n}\n\nexport function assertAgentInteractionResponse(\n request: AgentInteractionRequest,\n response: AgentInteractionResponse,\n): void {\n if (request.type !== response.type) {\n throw new TypeError(\"Interaction response type does not match the pending request.\");\n }\n if (request.type === \"tool-question\" && response.type === \"tool-question\") {\n assertQuestionAnswers(request, response.answers);\n }\n}\n\nfunction assertQuestionAnswers(\n request: AgentToolQuestionRequest,\n answers: readonly AgentQuestionAnswer[],\n): void {\n const parsed = answers.map((answer) => questionAnswerSchema.parse(answer));\n const byId = new Map(parsed.map((answer) => [answer.questionId, answer]));\n if (byId.size !== parsed.length) {\n throw new TypeError(\"Question answers must not contain duplicate question IDs.\");\n }\n if (byId.size !== request.questions.length) {\n throw new TypeError(\"Question responses must answer every question exactly once.\");\n }\n for (const question of request.questions) {\n const answer = byId.get(question.id);\n if (answer === undefined) {\n throw new TypeError(`Question response is missing an answer for \"${question.id}\".`);\n }\n const choices = question.choices;\n if (\n choices !== undefined &&\n question.allowCustom !== true &&\n !choices.some((choice) => choice.value === answer.value)\n ) {\n throw new TypeError(`Question \"${question.id}\" requires one of its configured choices.`);\n }\n }\n}\n\nfunction freeze<T>(value: T): T {\n if (typeof value !== \"object\" || value === null || Object.isFrozen(value)) return value;\n for (const child of Object.values(value)) freeze(child);\n return Object.freeze(value);\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 configuredTools: readonly AnyTool[];\n staticTools: readonly AnyTool[];\n providerTools: readonly ProviderTool[];\n toolIndexes: readonly ToolIndex[];\n};\n\ntype StoredAgentToolState = {\n publicState: AgentToolState;\n toolsByName: Map<string, AnyTool>;\n};\n\nconst agentToolStates = new WeakMap<object, StoredAgentToolState>();\n\nexport function registerAgentToolState(\n agent: object,\n publicState: AgentToolState,\n toolsByName: Map<string, AnyTool>,\n): void {\n agentToolStates.set(agent, { publicState, toolsByName });\n}\n\nexport function getAgentToolState(agent: object): AgentToolState {\n return getStoredAgentToolState(agent).publicState;\n}\n\nexport function getRegisteredAgentTool(agent: object, toolName: string): AnyTool | undefined {\n return getStoredAgentToolState(agent).toolsByName.get(toolName);\n}\n\nfunction getStoredAgentToolState(agent: object): StoredAgentToolState {\n const state = agentToolStates.get(agent);\n if (state === undefined) {\n throw new TypeError(\"Agent tool state is unavailable.\");\n }\n return state;\n}\n","import type {\n AgentHook,\n HookAction,\n RunControl,\n ToolApprovalRequestOptions,\n ToolCallControl,\n ToolCallHookAction,\n} from \"./types\";\n\nexport function createHook<RawResponse = unknown>(\n hook: AgentHook<RawResponse>,\n): AgentHook<RawResponse> {\n return hook;\n}\n\nexport function cancelRun(reason: string): HookAction {\n return { type: \"terminate\", reason };\n}\n\nexport function skipTool(reason: string): ToolCallHookAction {\n return { type: \"skip\", reason };\n}\n\nexport function requestToolApproval(options: ToolApprovalRequestOptions = {}): ToolCallHookAction {\n const action: ToolCallHookAction = {\n type: \"approval_request\" as const,\n };\n if (options.reason !== undefined) {\n action.reason = options.reason;\n }\n if (options.rejectMessage !== undefined) {\n action.rejectMessage = options.rejectMessage;\n }\n return action;\n}\n\nexport const runControl: RunControl = {\n continue() {\n return { type: \"continue\" };\n },\n cancel(reason: string) {\n return cancelRun(reason);\n },\n};\n\nexport const toolCallControl: ToolCallControl = {\n run() {\n return { type: \"continue\" };\n },\n skip(reason: string) {\n return skipTool(reason);\n },\n cancel(reason: string) {\n return { type: \"terminate\", reason };\n },\n requestApproval(options) {\n return requestToolApproval(options);\n },\n};\n","import type { Document } from \"../completion\";\nimport type { EmbeddingModel, SparseEmbeddingModel } from \"../embeddings\";\nimport { assertFiniteMinScore, assertPositiveSearchLimit } from \"../internal/vector-search-options\";\nimport type { RetrySetting } from \"../retry\";\nimport type {\n HybridVectorStore,\n VectorFilter,\n VectorFusion,\n VectorSearchResult,\n VectorStore,\n} from \"../vector-store\";\n\nexport type VectorContextBaseOptions<T = unknown> = {\n topK: number;\n minScore?: number | undefined;\n filter?: VectorFilter | undefined;\n retries?: RetrySetting | undefined;\n format?(result: VectorSearchResult<T>): Document;\n};\n\nexport type CreateVectorContextOptions<T = unknown> = VectorContextBaseOptions<T> & {\n store: VectorStore<T>;\n model: EmbeddingModel;\n models?: never;\n};\n\nexport type CreateHybridVectorContextOptions<T = unknown> = VectorContextBaseOptions<T> & {\n store: HybridVectorStore<T>;\n model?: never;\n models: { dense: EmbeddingModel; sparse: SparseEmbeddingModel };\n fusion?: VectorFusion | undefined;\n};\n\nexport type VectorContext<T = unknown> = (\n | CreateVectorContextOptions<T>\n | CreateHybridVectorContextOptions<T>\n) & {\n readonly kind: \"vector-context\";\n};\n\nexport function createVectorContext<T>(options: CreateVectorContextOptions<T>): VectorContext<T>;\nexport function createVectorContext<T>(\n options: CreateHybridVectorContextOptions<T>,\n): VectorContext<T>;\nexport function createVectorContext<T>(\n options: CreateVectorContextOptions<T> | CreateHybridVectorContextOptions<T>,\n): VectorContext<T> {\n const topK = assertPositiveSearchLimit(options.topK);\n const minScore = assertFiniteMinScore(options.minScore);\n let context: VectorContext<T> = {\n ...options,\n topK,\n kind: \"vector-context\" as const,\n };\n if (minScore !== undefined) {\n context = { ...context, minScore };\n }\n return Object.freeze(context);\n}\n\nexport function isVectorContext(value: unknown): value is VectorContext {\n if (typeof value !== \"object\" || value === null) return false;\n const candidate = value as {\n kind?: unknown;\n store?: { search?: unknown };\n model?: unknown;\n models?: { dense?: unknown; sparse?: unknown };\n };\n if (candidate.kind !== \"vector-context\" || typeof candidate.store?.search !== \"function\") {\n return false;\n }\n return (\n candidate.model !== undefined ||\n (candidate.models?.dense !== undefined && candidate.models.sparse !== undefined)\n );\n}\n","import type { Message } from \"../../completion\";\nimport type { AgentHook } from \"../../hooks\";\nimport type { MemoryCompactionInfo } from \"../../memory\";\n\nconst internalAgentRunOptions = Symbol(\"internalAgentRunOptions\");\n\nexport type InternalAgentRunOptions = {\n hook?: AgentHook | undefined;\n onFailure?: ((failure: { error: unknown; messages: readonly Message[] }) => void) | undefined;\n onMemoryCompaction?: ((compaction: MemoryCompactionInfo) => void | Promise<void>) | undefined;\n runId?: string | undefined;\n};\n\ntype AgentRunOptionsWithInternal = {\n [internalAgentRunOptions]?: InternalAgentRunOptions;\n};\n\nexport function withInternalAgentRunOptions<T extends object>(\n options: T,\n internal: InternalAgentRunOptions,\n): T {\n return {\n ...options,\n [internalAgentRunOptions]: internal,\n };\n}\n\nexport function getInternalAgentRunOptions(options: object): InternalAgentRunOptions | undefined {\n return (options as AgentRunOptionsWithInternal)[internalAgentRunOptions];\n}\n","import type { CompletionResponse, Message, Usage } from \"../completion\";\nimport type { DeepReadonly, MaybePromise } from \"../internal/type-utils\";\nimport type { MemoryCompactionInfo } from \"../memory\";\nimport type { AgentInteractionRequest } from \"./interactions\";\n\nexport type AgentLifecycleRunEvent = {\n runId: string;\n};\n\nexport type AgentStartEvent = AgentLifecycleRunEvent & {\n input: DeepReadonly<Message>;\n history: DeepReadonly<Message[]>;\n maxTurns: number;\n};\n\nexport type AgentStepFinishEvent<RawResponse = unknown> = AgentLifecycleRunEvent & {\n step: number;\n response: DeepReadonly<CompletionResponse<RawResponse>>;\n usage: DeepReadonly<Usage>;\n};\n\nexport type AgentToolStartEvent = AgentLifecycleRunEvent & {\n step: number;\n toolName: string;\n toolCallId?: string | undefined;\n input: unknown;\n};\n\ntype AgentToolFinishEventBase = AgentToolStartEvent & {\n durationMs: number;\n};\n\nexport type AgentToolFinishEvent =\n | (AgentToolFinishEventBase & { success: true; output: unknown })\n | (AgentToolFinishEventBase & { success: false; error: unknown });\n\ntype AgentFinishEventBase = AgentLifecycleRunEvent & {\n text: string;\n usage: DeepReadonly<Usage>;\n messages: DeepReadonly<Message[]>;\n memoryCompaction?: DeepReadonly<MemoryCompactionInfo> | undefined;\n};\n\nexport type AgentFinishEvent<Output = string> =\n | (AgentFinishEventBase & {\n status: \"completed\";\n output: DeepReadonly<Output>;\n })\n | (AgentFinishEventBase & {\n status: \"blocked\";\n stage: \"input\" | \"output\";\n })\n | (AgentFinishEventBase & {\n status: \"suspended\";\n interaction: DeepReadonly<AgentInteractionRequest>;\n });\n\nexport type AgentErrorEvent = AgentLifecycleRunEvent & {\n error: unknown;\n usage: DeepReadonly<Usage>;\n messages: DeepReadonly<Message[]>;\n};\n\nexport type AgentLifecycle<Output = string, RawResponse = unknown> = {\n onStart?(event: AgentStartEvent): MaybePromise<void>;\n onStepFinish?(event: AgentStepFinishEvent<RawResponse>): MaybePromise<void>;\n onToolStart?(event: AgentToolStartEvent): MaybePromise<void>;\n onToolFinish?(event: AgentToolFinishEvent): MaybePromise<void>;\n onFinish?(event: AgentFinishEvent<Output>): MaybePromise<void>;\n onError?(event: AgentErrorEvent): MaybePromise<void>;\n};\n\nexport function composeAgentLifecycle<Output = string, RawResponse = unknown>(\n first: AgentLifecycle<Output, RawResponse> | undefined,\n second: AgentLifecycle<Output, RawResponse> | undefined,\n): AgentLifecycle<Output, RawResponse> | undefined {\n if (first === undefined) return second;\n if (second === undefined) return first;\n\n return {\n async onStart(event) {\n await first.onStart?.(lifecycleSnapshot(event));\n await second.onStart?.(lifecycleSnapshot(event));\n },\n async onStepFinish(event) {\n await first.onStepFinish?.(lifecycleSnapshot(event));\n await second.onStepFinish?.(lifecycleSnapshot(event));\n },\n async onToolStart(event) {\n await first.onToolStart?.(lifecycleSnapshot(event));\n await second.onToolStart?.(lifecycleSnapshot(event));\n },\n async onToolFinish(event) {\n await first.onToolFinish?.(lifecycleSnapshot(event));\n await second.onToolFinish?.(lifecycleSnapshot(event));\n },\n async onFinish(event) {\n await first.onFinish?.(lifecycleSnapshot(event));\n await second.onFinish?.(lifecycleSnapshot(event));\n },\n async onError(event) {\n await first.onError?.(lifecycleSnapshot(event));\n await second.onError?.(lifecycleSnapshot(event));\n },\n };\n}\n\nexport function lifecycleSnapshot<T>(value: T): T {\n try {\n return globalThis.structuredClone(value);\n } catch {\n return cloneLifecycleFallback(value, new WeakMap<object, object>());\n }\n}\n\nfunction cloneLifecycleFallback<T>(value: T, seen: WeakMap<object, object>): T {\n if (typeof value !== \"object\" || value === null) {\n return value;\n }\n const existing = seen.get(value);\n if (existing !== undefined) {\n return existing as T;\n }\n if (Array.isArray(value)) {\n const clone: unknown[] = [];\n seen.set(value, clone);\n clone.push(...value.map((item) => cloneLifecycleFallback(item, seen)));\n return clone as T;\n }\n if (Object.getPrototypeOf(value) !== Object.prototype) {\n return value;\n }\n const clone: Record<string, unknown> = {};\n seen.set(value, clone);\n for (const [key, item] of Object.entries(value)) {\n clone[key] = cloneLifecycleFallback(item, seen);\n }\n return clone as T;\n}\n","import type { JsonObject } from \"../completion\";\nimport { toProviderJsonSchema, type ZodSchema } from \"../schema/zod-schema\";\n\nconst providerOutputSchemas = new WeakMap<object, JsonObject>();\n\nexport function registerAgentProviderOutputSchema(\n agent: object,\n schema: ZodSchema | undefined,\n): void {\n if (schema !== undefined) {\n providerOutputSchemas.set(agent, toProviderJsonSchema(schema));\n }\n}\n\nexport function getAgentProviderOutputSchema(agent: object): JsonObject | undefined {\n return providerOutputSchemas.get(agent);\n}\n","type AsyncQueueWaiter<T> = {\n resolve: (result: IteratorResult<T>) => void;\n reject: (error: unknown) => void;\n};\n\nexport type AsyncQueue<T> = AsyncIterable<T> & {\n enqueue(value: T): void;\n close(): void;\n throw(error: unknown): void;\n};\n\nexport function createAsyncQueue<T>(): AsyncQueue<T> {\n const values: T[] = [];\n const waiters: AsyncQueueWaiter<T>[] = [];\n let closed = false;\n let error: unknown;\n\n function flush(): void {\n while (waiters.length > 0 && values.length > 0) {\n const waiter = waiters.shift();\n const value = values.shift() as T;\n if (waiter !== undefined) {\n waiter.resolve({ value, done: false });\n }\n }\n\n if (values.length > 0 || waiters.length === 0 || !closed) {\n return;\n }\n\n while (waiters.length > 0) {\n const waiter = waiters.shift();\n if (waiter === undefined) {\n continue;\n }\n if (error !== undefined) {\n waiter.reject(error);\n } else {\n waiter.resolve({ value: undefined, done: true });\n }\n }\n }\n\n return {\n enqueue(value: T): void {\n if (closed) {\n return;\n }\n values.push(value);\n flush();\n },\n close(): void {\n closed = true;\n flush();\n },\n throw(thrown: unknown): void {\n closed = true;\n error = thrown;\n flush();\n },\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return {\n next(): Promise<IteratorResult<T>> {\n if (values.length > 0) {\n const value = values.shift() as T;\n return Promise.resolve({ value, done: false });\n }\n if (error !== undefined) {\n return Promise.reject(error);\n }\n if (closed) {\n return Promise.resolve({ value: undefined, done: true });\n }\n return new Promise((resolve, reject) => {\n waiters.push({ resolve, reject });\n });\n },\n };\n },\n };\n}\n","import type { Message as MessageType } from \"../completion/index\";\n\nexport function extractRagText(message: MessageType): string | undefined {\n if (message.role === \"user\") {\n if (typeof message.content === \"string\") {\n return message.content;\n }\n return message.content.flatMap((item) => (item.type === \"text\" ? [item.text] : [])).join(\"\\n\");\n }\n\n if (message.role === \"tool\") {\n return message.content\n .flatMap((item) => {\n if (item.type !== \"tool-result\") {\n return [];\n }\n const output = item.output;\n if (output.type === \"text\" || output.type === \"error-text\") {\n return [output.value];\n }\n if (output.type === \"content\") {\n return output.value.flatMap((part) => (part.type === \"text\" ? [part.text] : []));\n }\n return [];\n })\n .join(\"\\n\");\n }\n\n return undefined;\n}\n","import type { AgentInteractionRequest, AgentQuestionAnswer } from \"../../agent/interactions\";\nimport { parseAgentQuestionPrompts } from \"../../agent/interactions\";\nimport {\n isJsonValue,\n type JsonObject,\n type JsonValue,\n type Message,\n parseMessages,\n type ToolCallPart,\n type ToolResultPart,\n} from \"../../completion\";\nimport type { MemoryScope } from \"../../memory\";\nimport type { PendingToolExecution } from \"./interaction-suspension\";\n\nexport type QueuedSteering = {\n id: string;\n messages: Message[];\n};\n\nexport type AgentContinuationState = {\n kind: \"anvia.agent-continuation\";\n history: Message[];\n messages: Message[];\n pending: PendingToolExecution;\n remainingToolCalls: ToolCallPart[];\n steering: QueuedSteering[];\n memoryScope?: MemoryScope;\n};\n\nexport function serializeContinuationState(state: AgentContinuationState): JsonObject {\n const value = structuredClone(state) as unknown;\n if (!isJsonValue(value) || Array.isArray(value) || value === null) {\n throw new TypeError(\"Agent continuation state must be strict JSON.\");\n }\n return value as JsonObject;\n}\n\nexport function parseContinuationState(\n value: JsonObject,\n interaction: AgentInteractionRequest,\n): AgentContinuationState {\n requireOnlyKeys(value, [\n \"kind\",\n \"history\",\n \"messages\",\n \"pending\",\n \"remainingToolCalls\",\n \"steering\",\n \"memoryScope\",\n ]);\n if (value.kind !== \"anvia.agent-continuation\") {\n throw new TypeError(\"Agent continuation has an unsupported internal state.\");\n }\n const history = parseMessages(value.history);\n const messages = parseMessages(value.messages);\n const pending = parsePending(value.pending);\n const remainingToolCalls = parseToolCalls(value.remainingToolCalls);\n const steering = parseSteering(value.steering);\n if (\n pending.toolCall.toolCallId !== interaction.toolCallId ||\n pending.toolCall.toolName !== interaction.toolName ||\n pending.toolCall.callId !== interaction.callId ||\n pending.internalCallId !== interaction.internalCallId\n ) {\n throw new TypeError(\"Agent continuation interaction does not match its pending tool call.\");\n }\n if (interaction.type === \"tool-approval\" && !jsonEqual(interaction.input, pending.input)) {\n throw new TypeError(\"Agent continuation approval input does not match its pending tool input.\");\n }\n if (interaction.type === \"tool-question\") {\n const questions =\n object(pending.input) && \"questions\" in pending.input\n ? parseAgentQuestionPrompts(pending.input.questions)\n : undefined;\n if (questions === undefined || !jsonEqual(interaction.questions, questions)) {\n throw new TypeError(\n \"Agent continuation questions do not match its pending question tool input.\",\n );\n }\n }\n const state: AgentContinuationState = {\n kind: \"anvia.agent-continuation\",\n history,\n messages,\n pending,\n remainingToolCalls,\n steering,\n };\n if (value.memoryScope !== undefined) {\n state.memoryScope = parseOptionalJsonObject(value.memoryScope, \"memoryScope\") as MemoryScope;\n }\n return state;\n}\n\nexport function questionResult(\n answers: readonly AgentQuestionAnswer[],\n): Extract<ToolResultPart[\"output\"], { type: \"json\" }> {\n return { type: \"json\", value: { answers: structuredClone([...answers]) } };\n}\n\nfunction parsePending(value: unknown): PendingToolExecution {\n if (!object(value)) throw new TypeError(\"Agent continuation pending state is invalid.\");\n const [toolCall] = parseToolCalls([value.toolCall]);\n if (toolCall === undefined) throw new TypeError(\"Agent continuation pending tool is missing.\");\n if (typeof value.effectiveArgs !== \"string\" || typeof value.internalCallId !== \"string\") {\n throw new TypeError(\"Agent continuation pending execution metadata is invalid.\");\n }\n const pending: PendingToolExecution = {\n toolCall,\n effectiveArgs: value.effectiveArgs,\n input: parseJsonValue(value.input, \"pending input\"),\n internalCallId: value.internalCallId,\n };\n if (typeof value.rejectMessage === \"string\") {\n pending.rejectMessage = value.rejectMessage;\n }\n return pending;\n}\n\nfunction parseJsonValue(value: unknown, name: string): JsonValue {\n if (!isJsonValue(value)) {\n throw new TypeError(`Agent continuation ${name} is invalid.`);\n }\n return structuredClone(value);\n}\n\nfunction parseToolCalls(value: unknown): ToolCallPart[] {\n if (!Array.isArray(value)) throw new TypeError(\"Agent continuation tool calls must be an array.\");\n const message = parseMessages([{ role: \"assistant\", content: value }])[0];\n if (message?.role !== \"assistant\" || typeof message.content === \"string\") {\n throw new TypeError(\"Agent continuation tool calls are invalid.\");\n }\n if (!message.content.every((part) => part.type === \"tool-call\")) {\n throw new TypeError(\"Agent continuation contains a non-tool-call part.\");\n }\n return message.content as ToolCallPart[];\n}\n\nfunction parseSteering(value: unknown): QueuedSteering[] {\n if (!Array.isArray(value)) throw new TypeError(\"Agent continuation steering state is invalid.\");\n return value.map((item) => {\n if (!object(item) || typeof item.id !== \"string\") {\n throw new TypeError(\"Agent continuation steering entry is invalid.\");\n }\n return { id: item.id, messages: parseMessages(item.messages) };\n });\n}\n\nfunction parseOptionalJsonObject(value: unknown, name: string): JsonObject | undefined {\n if (value === undefined) return undefined;\n if (!object(value) || !isJsonValue(value)) {\n throw new TypeError(`Agent continuation ${name} is invalid.`);\n }\n return structuredClone(value);\n}\n\nfunction object(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction requireOnlyKeys(value: JsonObject, allowed: readonly string[]): void {\n const allowedKeys = new Set(allowed);\n const unknown = Object.keys(value).find((key) => !allowedKeys.has(key));\n if (unknown !== undefined) {\n throw new TypeError(`Agent continuation state contains unknown key \"${unknown}\".`);\n }\n}\n\nfunction jsonEqual(left: unknown, right: unknown): boolean {\n if (Object.is(left, right)) return true;\n if (Array.isArray(left)) {\n return (\n Array.isArray(right) &&\n left.length === right.length &&\n left.every((value, index) => jsonEqual(value, right[index]))\n );\n }\n if (object(left)) {\n if (!object(right)) return false;\n const keys = Object.keys(left);\n return (\n keys.length === Object.keys(right).length &&\n keys.every((key) => key in right && jsonEqual(left[key], right[key]))\n );\n }\n return false;\n}\n","import type { AgentInteractionRequest, AgentToolApprovalRequest } from \"../../agent/interactions\";\nimport {\n isJsonValue,\n type JsonValue,\n type ToolCallPart,\n type ToolResultPart,\n} from \"../../completion\";\n\nexport type PendingToolExecution = {\n toolCall: ToolCallPart;\n effectiveArgs: string;\n input: JsonValue;\n internalCallId: string;\n rejectMessage?: string;\n};\n\nexport class AgentInteractionSignal extends Error {\n constructor(\n readonly interaction: AgentInteractionRequest,\n readonly rejectMessage?: string,\n ) {\n super(\"Agent execution requires a human interaction.\");\n this.name = \"AgentInteractionSignal\";\n }\n}\n\nexport class ToolExecutionSuspension extends Error {\n completedResults: ToolResultPart[] = [];\n remainingToolCalls: ToolCallPart[] = [];\n\n constructor(\n readonly interaction: AgentInteractionRequest,\n readonly pending: PendingToolExecution,\n ) {\n super(\"Tool execution suspended for human interaction.\");\n this.name = \"ToolExecutionSuspension\";\n }\n}\n\nexport function approvalInteraction(request: {\n id: string;\n toolName: string;\n toolCallId?: string;\n callId?: string;\n internalCallId: string;\n args: unknown;\n reason?: string | undefined;\n rejectMessage?: string | undefined;\n}): AgentToolApprovalRequest {\n if (request.toolCallId === undefined) {\n throw new TypeError(\"Tool approval requires a canonical toolCallId.\");\n }\n if (!isJsonValue(request.args)) {\n throw new TypeError(\"Tool approval input must be strict JSON.\");\n }\n let interaction: AgentToolApprovalRequest = {\n type: \"tool-approval\",\n id: request.id,\n toolName: request.toolName,\n toolCallId: request.toolCallId,\n internalCallId: request.internalCallId,\n input: request.args,\n };\n if (request.callId !== undefined) interaction = { ...interaction, callId: request.callId };\n if (request.reason !== undefined) interaction = { ...interaction, reason: request.reason };\n return interaction;\n}\n","import type { Agent } from \"../../agent/agent\";\nimport type { AgentMemory } from \"../../agent/types\";\nimport { type Message as MessageType, Usage } from \"../../completion/index\";\nimport {\n createMemoryCompactionSummary,\n cumulativeCompactedMessageCount,\n} from \"../../memory/compaction\";\nimport { MemoryCompactionConflictError, MemoryCompactionError } from \"../../memory/errors\";\nimport type { MemoryCompactionInfo, MemorySavePolicy, MemoryScope } from \"../../memory/types\";\nimport { throwIfAborted } from \"../abort\";\n\nexport type MemoryPreparation = {\n history: MessageType[];\n usage: ReturnType<typeof Usage.empty>;\n compaction?: MemoryCompactionInfo | undefined;\n};\n\ntype MemoryAgent = Pick<Agent, \"memory\">;\n\nexport class AgentRunMemory {\n constructor(\n private readonly agent: MemoryAgent,\n private readonly memoryScope: MemoryScope | undefined,\n private readonly initialHistory: MessageType[],\n ) {}\n\n memoryPolicy(): MemorySavePolicy | undefined {\n return this.memory()?.savePolicy;\n }\n\n pendingTurnMessages(newMessages: MessageType[]): MessageType[] {\n return this.memoryPolicy() === \"turn\" ? [...newMessages] : [];\n }\n\n async prepareHistory(\n runId: string,\n incomingMessageCount: number,\n abortSignal?: AbortSignal | undefined,\n ): Promise<MemoryPreparation> {\n const memory = this.memory();\n if (memory === undefined || this.memoryScope === undefined) {\n return {\n history: this.initialHistory,\n usage: Usage.empty(),\n };\n }\n\n const preparation = await this.prepareStoredHistory(\n memory,\n runId,\n incomingMessageCount,\n abortSignal,\n );\n const memoryHistory = preparation.history;\n const chatHistory = [...memoryHistory, ...this.initialHistory];\n return {\n ...preparation,\n history: chatHistory,\n };\n }\n\n async commitAcceptedInput(runId: string, messages: MessageType[]): Promise<void> {\n const memory = this.memory();\n if (\n memory === undefined ||\n this.memoryScope === undefined ||\n memory.savePolicy !== \"message\" ||\n messages.length === 0\n ) {\n return;\n }\n\n await memory.store.append({\n scope: this.memoryScope,\n runId,\n turn: 1,\n messages,\n });\n }\n\n async commitMessages(\n runId: string,\n turn: number,\n messages: MessageType[],\n pendingTurnMessages: MessageType[],\n ): Promise<void> {\n const memory = this.memory();\n if (memory === undefined || this.memoryScope === undefined || messages.length === 0) {\n return;\n }\n if (memory.savePolicy === \"message\") {\n await memory.store.append({\n scope: this.memoryScope,\n runId,\n turn,\n messages,\n });\n } else if (memory.savePolicy === \"turn\") {\n pendingTurnMessages.push(...messages);\n }\n }\n\n async commitCompletedTurn(\n runId: string,\n turn: number,\n pendingTurnMessages: MessageType[],\n ): Promise<void> {\n const memory = this.memory();\n if (\n memory === undefined ||\n this.memoryScope === undefined ||\n memory.savePolicy !== \"turn\" ||\n pendingTurnMessages.length === 0\n ) {\n return;\n }\n await memory.store.append({\n scope: this.memoryScope,\n runId,\n turn,\n messages: [...pendingTurnMessages],\n });\n pendingTurnMessages.length = 0;\n }\n\n async commitCompletedRun(\n runId: string,\n turn: number,\n newMessages: MessageType[],\n pendingTurnMessages: MessageType[],\n ): Promise<void> {\n await this.commitCompletedTurn(runId, turn, pendingTurnMessages);\n const memory = this.memory();\n if (memory === undefined || this.memoryScope === undefined || memory.savePolicy !== \"run\") {\n return;\n }\n await memory.store.append({\n scope: this.memoryScope,\n runId,\n turn,\n messages: [...newMessages],\n });\n }\n\n async recordError(runId: string, error: unknown, newMessages: MessageType[]): Promise<void> {\n const memory = this.memory();\n if (memory === undefined || this.memoryScope === undefined) {\n return;\n }\n await memory.store.recordError?.({\n scope: this.memoryScope,\n runId,\n error,\n messages: [...newMessages],\n });\n }\n\n private memory(): AgentMemory | undefined {\n return this.memoryScope === undefined ? undefined : this.agent.memory;\n }\n\n private async prepareStoredHistory(\n memory: AgentMemory,\n runId: string,\n incomingMessageCount: number,\n abortSignal?: AbortSignal | undefined,\n ): Promise<MemoryPreparation> {\n const scope = this.memoryScope;\n if (scope === undefined) {\n return { history: [], usage: Usage.empty() };\n }\n const options = memory.compaction;\n const capability = memory.store.compaction;\n if (options === undefined || capability === undefined) {\n return {\n history: await memory.store.load({ scope }),\n usage: Usage.empty(),\n };\n }\n\n let usage = Usage.empty();\n const maxAttempts = options.conflictRetries === false ? 1 : options.conflictRetries.maxAttempts;\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n throwIfAborted(abortSignal);\n const snapshot = await capability.snapshot({ scope });\n throwIfAborted(abortSignal);\n const compactedMessageCount = compactedPrefixLength(\n snapshot.messages,\n incomingMessageCount,\n options.trigger.afterMessages,\n options.retention.recentUserTurns,\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 scope,\n messages: prefix,\n abortSignal,\n });\n } catch (error) {\n throw remappedCompactorError(error, usage);\n }\n if (result.usage !== undefined) {\n usage = Usage.add(usage, result.usage);\n }\n 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 throwIfAborted(abortSignal);\n let replacement: Awaited<ReturnType<typeof capability.replacePrefix>>;\n try {\n replacement = await capability.replacePrefix({\n scope,\n revision: snapshot.revision,\n messageCount: compactedMessageCount,\n replacement: summary,\n runId: `memory-compaction:${runId}:${attempt}`,\n });\n } catch (error) {\n throw new MemoryCompactionError(\"Memory compaction prefix replacement failed.\", {\n cause: error,\n usage,\n });\n }\n if (replacement.status === \"committed\") {\n 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 attempts: attempt,\n usage,\n },\n };\n }\n throwIfAborted(abortSignal);\n }\n\n throw new MemoryCompactionConflictError(maxAttempts, usage);\n }\n}\n\nfunction compactedPrefixLength(\n messages: MessageType[],\n incomingMessageCount: number,\n afterMessages: number,\n recentUserTurns: number,\n): number {\n if (messages.length + incomingMessageCount <= afterMessages) {\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 the trigger threshold.\n if (userMessageIndexes.length <= recentUserTurns) {\n return 0;\n }\n return userMessageIndexes[userMessageIndexes.length - recentUserTurns] ?? 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 { getAgentToolState } from \"../../agent/tool-state\";\nimport { isVectorContext } from \"../../agent/vector-context\";\nimport type { CompletionModel, Document, ToolDefinition } from \"../../completion/index\";\nimport { retrieveDocuments } from \"../../vector-store\";\n\nexport async function fetchContextDocuments<Output, M extends CompletionModel, ContextDocument>(\n agent: Agent<Output, M, ContextDocument>,\n ragText: string | undefined,\n abortSignal?: AbortSignal | undefined,\n): Promise<Document[]> {\n const documents: Document[] = [];\n for (const input of agent.context) {\n if (!isVectorContext(input)) {\n documents.push(input);\n continue;\n }\n if (ragText === undefined || ragText.length === 0) continue;\n const request = {\n query: ragText,\n topK: input.topK,\n minScore: input.minScore,\n filter: input.filter,\n retries: input.retries,\n abortSignal,\n };\n const results =\n \"models\" in input && input.models !== undefined\n ? await retrieveDocuments({\n ...request,\n store: input.store,\n models: input.models,\n fusion: input.fusion,\n })\n : await retrieveDocuments({ ...request, store: input.store, model: input.model });\n for (const result of results) {\n const formatted = input.format?.(result);\n if (formatted !== undefined) {\n documents.push(formatted);\n continue;\n }\n const metadata = formatMetadata(result.metadata);\n const document: Document = {\n id: result.id,\n text:\n typeof result.document === \"string\"\n ? result.document\n : JSON.stringify(result.document, null, 2),\n };\n if (metadata !== undefined) document.additionalProps = metadata;\n documents.push(document);\n }\n }\n return documents;\n}\n\nexport async function fetchToolDefinitions<Output, M extends CompletionModel, ContextDocument>(\n agent: Agent<Output, M, ContextDocument>,\n ragText: string | undefined,\n abortSignal?: AbortSignal | undefined,\n): Promise<ToolDefinition[]> {\n const state = getAgentToolState(agent);\n const staticDefinitions = await Promise.all(\n state.staticTools.map((tool) => tool.definition(ragText ?? \"\")),\n );\n if (ragText === undefined || ragText.length === 0 || state.toolIndexes.length === 0) {\n return staticDefinitions;\n }\n\n const definitions = [...staticDefinitions];\n const names = new Set(staticDefinitions.map((definition) => definition.name));\n for (const index of state.toolIndexes) {\n const results = await index.search({ query: ragText, abortSignal });\n for (const result of results) {\n const toolName = result.document.toolName;\n if (names.has(toolName)) continue;\n const tool = index.tools.find((candidate) => candidate.name === toolName);\n if (tool === undefined) continue;\n names.add(toolName);\n definitions.push(await tool.definition(ragText));\n }\n }\n return definitions;\n}\n\nfunction formatMetadata(\n metadata: Record<string, unknown> | undefined,\n): Record<string, string> | undefined {\n if (metadata === undefined) return undefined;\n return Object.fromEntries(Object.entries(metadata).map(([key, value]) => [key, String(value)]));\n}\n","export function assertNonnegativeSafeInteger(value: number, name: string): number {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new TypeError(`${name} must be a nonnegative safe integer.`);\n }\n return value;\n}\n\nexport function assertPositiveSafeInteger(value: number, name: string): number {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new TypeError(`${name} must be a positive safe integer.`);\n }\n return value;\n}\n","import type { AgentDeltaEvent } from \"../../agent/run-types\";\nimport type {\n AssistantContentPart,\n CompletionModelStreamEvent,\n CompletionResponse,\n CompletionSource,\n JsonValue,\n ProviderToolCall,\n ReasoningDetail,\n ToolCallPart,\n} from \"../../completion/index\";\nimport { Usage } from \"../../completion/index\";\n\ntype ReasoningState = {\n id?: string;\n text: string;\n details?: ReasoningDetail[];\n};\n\ntype PartialToolCall = {\n id: string;\n callId?: string;\n name: string;\n argumentsText: string;\n signature?: string;\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: CompletionModelStreamEvent<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: AssistantContentPart[] = [];\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: ToolCallPart): void {\n if (!this.toolCalls.has(toolCall.toolCallId)) {\n this.orderedParts.push({ type: \"tool_call\", key: toolCall.toolCallId });\n }\n const partial: PartialToolCall = {\n id: toolCall.toolCallId,\n name: toolCall.toolName,\n argumentsText: JSON.stringify(toolCall.input ?? {}),\n };\n if (toolCall.callId !== undefined) {\n partial.callId = toolCall.callId;\n }\n if (toolCall.signature !== undefined) {\n partial.signature = toolCall.signature;\n }\n this.toolCalls.set(toolCall.toolCallId, 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, ToolCallPart>();\n const finalByCallId = new Map<string, ToolCallPart>();\n for (const content of finalResponse.choice) {\n if (content.type !== \"tool-call\") {\n continue;\n }\n finalById.set(content.toolCallId, content);\n if (content.callId !== undefined) {\n finalByCallId.set(content.callId, content);\n }\n }\n\n const matchedFinalToolCalls = new Set<ToolCallPart>();\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.toolCallId) ??\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<CompletionModelStreamEvent<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 let accumulated: CompletionResponse<RawResponse> = { ...withMessageId };\n if (sources.length > 0) accumulated = { ...accumulated, sources };\n if (providerToolCalls.length > 0) {\n accumulated = { ...accumulated, providerToolCalls };\n }\n return accumulated;\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<CompletionModelStreamEvent<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.details ??= [];\n const last = reasoning.details.at(-1);\n if (contentType === \"text\") {\n if (last?.type === \"text\") {\n let detail: ReasoningDetail = {\n ...last,\n text: `${last.text}${event.delta}`,\n };\n if (event.signature !== undefined) detail = { ...detail, signature: event.signature };\n reasoning.details[reasoning.details.length - 1] = detail;\n } else {\n reasoning.details.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 reasoning.details[reasoning.details.length - 1] = {\n ...last,\n text: `${last.text}${event.delta}`,\n };\n } else {\n reasoning.details.push({ type: \"summary\", text: event.delta });\n }\n return;\n }\n\n if (contentType === \"encrypted\") {\n reasoning.details.push({ type: \"encrypted\", data: event.delta });\n return;\n }\n\n reasoning.details.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): AssistantContentPart {\n const content =\n reasoning.details === undefined\n ? { type: \"reasoning\" as const, text: reasoning.text }\n : { type: \"reasoning\" as const, text: reasoning.text, details: reasoning.details };\n return reasoning.id === undefined ? content : { ...content, id: reasoning.id };\n}\n\nfunction toolCallContent(toolCall: PartialToolCall, finalToolCall?: ToolCallPart): ToolCallPart {\n const argumentsValue =\n finalToolCall !== undefined && !isEmptyToolArguments(finalToolCall.input)\n ? finalToolCall.input\n : parseToolArguments(toolCall.id, toolCall.argumentsText);\n let content: ToolCallPart = {\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.name,\n input: argumentsValue,\n };\n if (toolCall.callId !== undefined) content = { ...content, callId: toolCall.callId };\n if (toolCall.signature !== undefined) content = { ...content, signature: toolCall.signature };\n return content;\n}\n\nfunction matchingFinalToolCall(\n accumulated: PartialToolCall,\n finalChoice: AssistantContentPart[] | undefined,\n): ToolCallPart | undefined {\n const byId = finalChoice?.find(\n (content): content is ToolCallPart =>\n content.type === \"tool-call\" && content.toolCallId === accumulated.id,\n );\n if (byId !== undefined || accumulated.callId === undefined) {\n return byId;\n }\n return finalChoice?.find(\n (content): content is ToolCallPart =>\n content.type === \"tool-call\" && content.callId === accumulated.callId,\n );\n}\n\nfunction mergeFinalToolCall(accumulated: ToolCallPart, finalToolCall: ToolCallPart): ToolCallPart {\n const input = isEmptyToolArguments(finalToolCall.input) ? accumulated.input : finalToolCall.input;\n return {\n ...accumulated,\n ...finalToolCall,\n input,\n };\n}\n\nfunction reasoningDeltaEvent(\n event: Extract<CompletionModelStreamEvent, { 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 { CompletionModelStreamEvent } from \"../../completion/types\";\n\nexport function addTurn(turn: number, event: AgentDeltaEvent): AgentStreamEvent {\n if (event.type === \"text_delta\") {\n return { type: \"text_delta\", turn, delta: event.delta };\n }\n if (event.type === \"reasoning_delta\") {\n const mapped: AgentStreamEvent = { type: \"reasoning_delta\", turn, delta: event.delta };\n if (event.id !== undefined) mapped.id = event.id;\n if (event.contentType !== undefined) mapped.contentType = event.contentType;\n if (event.signature !== undefined) mapped.signature = event.signature;\n return mapped;\n }\n if (event.type === \"source\") {\n return { type: \"source\", turn, source: event.source };\n }\n if (event.type === \"provider_tool_call\") {\n return { type: \"provider_tool_call\", turn, toolCall: event.toolCall };\n }\n return { type: \"tool_call\", turn, toolCall: event.toolCall };\n}\n\nexport function addTurnToToolCallDelta(\n turn: number,\n event: Extract<CompletionModelStreamEvent, { type: \"tool_call_delta\" }>,\n): AgentToolCallDeltaEvent {\n const mapped: AgentToolCallDeltaEvent = {\n type: \"tool_call_delta\",\n turn,\n id: event.id,\n };\n if (event.callId !== undefined) mapped.callId = event.callId;\n if (event.name !== undefined) mapped.name = event.name;\n if (event.argumentsDelta !== undefined) mapped.argumentsDelta = event.argumentsDelta;\n if (event.argumentsMode !== undefined) mapped.argumentsMode = event.argumentsMode;\n if (event.signature !== undefined) mapped.signature = event.signature;\n return mapped;\n}\n\nexport function isGenerationDeltaEvent(type: string): boolean {\n return (\n type === \"text_delta\" ||\n type === \"reasoning_delta\" ||\n type === \"tool_call_delta\" ||\n type === \"tool_call\" ||\n type === \"source\" ||\n type === \"provider_tool_call\"\n );\n}\n","import type { Agent } from \"../../agent/agent\";\nimport { parseAgentQuestionPrompts } from \"../../agent/interactions\";\nimport { type AgentLifecycle, lifecycleSnapshot } from \"../../agent/lifecycle\";\nimport type { AgentChildStreamEvent } from \"../../agent/run-types\";\nimport type {\n JsonObject,\n JsonValue,\n ToolCallPart,\n ToolDefinition,\n ToolResultContentPart,\n ToolResultOutput,\n ToolResultPart,\n} from \"../../completion\";\nimport type { AgentHook, ToolApprovalRequestOptions, ToolHookArgs } from \"../../hooks\";\nimport { runControl, toolCallControl } from \"../../hooks\";\nimport { isMcpTool } from \"../../mcp\";\nimport type { ActiveAgentRunObservers, ActiveToolObservers } from \"../../observability/group\";\nimport type {\n AgentToolEndArgs,\n AgentToolErrorArgs,\n AgentToolStartArgs,\n AgentToolStreamEventArgs,\n AgentToolSuspendedArgs,\n} from \"../../observability/types\";\nimport type {\n AnyTool,\n NormalizedToolOutput,\n ToolApprovalContext,\n ToolApprovalRunContext,\n ToolCallContext,\n ToolCallStreamEvent,\n ToolRequiresApproval,\n} from \"../../tool\";\nimport { parseToolArgs, toolResultContentToText } from \"../../tool\";\nimport type {\n AgentMiddleware,\n ToolOutputMiddlewareArgs,\n ToolOutputMiddlewareResult,\n} from \"../../tool/middleware\";\nimport { isQuestionTool } from \"../../tool/question-tool\";\nimport { isSkillTool } from \"../../tool/skill-tool-marker\";\nimport { throwIfAborted } from \"../abort\";\nimport { mapWithConcurrency } from \"../concurrency\";\nimport type { ToolApprovalRequest } from \"./approval-request\";\nimport { assertToolApprovalRequirement, toolMayRequireApproval } from \"./approval-requirement\";\nimport {\n AgentInteractionSignal,\n type PendingToolExecution,\n ToolExecutionSuspension,\n} from \"./interaction-suspension\";\nimport {\n type PreparedToolCall,\n prepareToolCall as prepareRegisteredToolCall,\n prepareToolCallFromInput,\n} from \"./prepared-tool-call\";\n\nexport type ToolResultEventPayload = {\n type: \"tool_result\";\n toolName: string;\n toolCallId: string;\n callId?: string;\n internalCallId: string;\n args: string;\n output: ToolResultOutput;\n result: string;\n structuredResult?: readonly ToolResultContentPart[] | undefined;\n};\n\nexport type AgentToolEventPayload = {\n type: \"agent_tool_event\";\n toolName: string;\n toolCallId?: string;\n internalCallId: string;\n agentId: string;\n agentName?: string;\n event: AgentChildStreamEvent<unknown, unknown>;\n};\n\nexport type ToolExecutionEventPayload = ToolResultEventPayload | AgentToolEventPayload;\n\nexport type ToolExecutionObservation = {\n turn: number;\n runObservers: ActiveAgentRunObservers;\n toolDefinitions?: ToolDefinition[];\n};\n\nexport type ToolExecutionRunContext = {\n runId: string;\n sessionId?: string | undefined;\n metadata?: JsonObject | undefined;\n};\n\nexport type ToolApprovalDecision =\n | { approved: true; reason?: string }\n | { approved: false; reason?: string };\n\nexport type ToolApprovalHandler = (request: ToolApprovalRequest) => Promise<ToolApprovalDecision>;\n\ntype ToolExecutionAgent = Pick<Agent, \"id\" | \"getTool\" | \"callTool\" | \"middlewares\">;\ntype ToolExecutionLifecycle = Pick<AgentLifecycle, \"onToolStart\" | \"onToolFinish\">;\n\nexport class ToolCallExecutor {\n constructor(\n private readonly agent: ToolExecutionAgent,\n private readonly activeHook: AgentHook | undefined,\n private readonly approvalHandler: ToolApprovalHandler,\n private readonly lifecycle: ToolExecutionLifecycle | undefined,\n private readonly runContext: ToolExecutionRunContext,\n private readonly concurrency: number,\n private readonly requestMiddlewares: readonly AgentMiddleware[],\n private readonly abortSignal: AbortSignal,\n private readonly cancel: (reason: string) => Error,\n ) {}\n\n async execute(\n toolCalls: readonly ToolCallPart[],\n onResult?: (result: ToolResultEventPayload) => void,\n onStreamEvent?: (event: AgentToolEventPayload) => void,\n observation?: ToolExecutionObservation,\n ): Promise<ToolResultPart[]> {\n for (const toolCall of toolCalls) {\n if (toolCall.toolName.length === 0) {\n throw new Error(\n `Completion returned tool call \"${toolCall.toolCallId}\" with an empty tool name; this indicates invalid provider output or provider mapping.`,\n );\n }\n }\n\n const executeOne = async (toolCall: ToolCallPart): Promise<ToolResultPart> => {\n throwIfAborted(this.abortSignal);\n const args = JSON.stringify(toolCall.input);\n const internalCallId = globalThis.crypto.randomUUID();\n const hookArgs: ToolHookArgs = {\n toolName: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n internalCallId,\n args,\n };\n if (toolCall.callId !== undefined) {\n hookArgs.callId = toolCall.callId;\n }\n const tool = this.agent.getTool(toolCall.toolName);\n const toolDefinition = observation?.toolDefinitions?.find(\n (definition) => definition.name === toolCall.toolName,\n );\n const toolMetadata = toolTraceMetadata(tool);\n\n let toolStartArgs: AgentToolStartArgs = {\n turn: observation?.turn ?? 0,\n toolCall,\n toolName: toolCall.toolName,\n internalCallId,\n args,\n };\n if (toolCall.callId !== undefined) {\n toolStartArgs = { ...toolStartArgs, toolCallId: toolCall.callId };\n }\n if (toolDefinition !== undefined) toolStartArgs = { ...toolStartArgs, toolDefinition };\n if (toolMetadata !== undefined) toolStartArgs = { ...toolStartArgs, toolMetadata };\n const toolObservers = await observation?.runObservers.startTool(toolStartArgs);\n const toolObservation = new ToolObserverScope(toolObservers);\n\n let output: NormalizedToolOutput | undefined;\n let skipped = false;\n let toolExecutionFailed = false;\n let effectiveArgs = args;\n\n try {\n const callAction = await this.activeHook?.onToolCall?.({\n ...hookArgs,\n tool: toolCallControl,\n });\n if (callAction?.type === \"terminate\") {\n throw this.cancel(callAction.reason);\n }\n if (callAction?.type === \"skip\") {\n output = { type: \"text\", value: callAction.reason };\n skipped = true;\n } else {\n try {\n effectiveArgs = await this.runToolInputMiddlewares({\n ...hookArgs,\n turn: observation?.turn ?? 0,\n originalArgs: args,\n });\n hookArgs.args = effectiveArgs;\n\n let prepared: PreparedToolCall | undefined;\n try {\n prepared = this.prepareToolCall(tool, toolCall.toolName, effectiveArgs);\n } catch (error) {\n const outcome = await this.handleToolError(\n toolCall,\n hookArgs,\n effectiveArgs,\n error,\n toolObservation,\n observation,\n );\n output = outcome.output;\n toolExecutionFailed = outcome.failed;\n }\n if (prepared !== undefined && isQuestionTool(tool)) {\n try {\n const questions = parseAgentQuestionPrompts(\n (prepared.input as { questions?: unknown }).questions,\n );\n const interaction = {\n type: \"tool-question\",\n id: globalThis.crypto.randomUUID(),\n toolName: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n internalCallId,\n questions,\n } as const;\n if (toolCall.callId !== undefined) {\n Object.assign(interaction, { callId: toolCall.callId });\n }\n throw new AgentInteractionSignal(interaction);\n } catch (error) {\n if (error instanceof AgentInteractionSignal) throw error;\n const outcome = await this.handleToolError(\n toolCall,\n hookArgs,\n effectiveArgs,\n error,\n toolObservation,\n observation,\n );\n output = outcome.output;\n toolExecutionFailed = outcome.failed;\n prepared = undefined;\n }\n }\n if (prepared !== undefined) {\n const approvalContext = createApprovalContext(\n prepared.input,\n hookArgs,\n this.agent,\n this.runContext,\n );\n const approvalDecision =\n callAction?.type === \"approval_request\"\n ? await this.requestApproval(approvalContext, callAction, observation)\n : ((await this.evaluateToolApproval(tool, approvalContext, observation)) ?? {\n approved: true as const,\n });\n if (!approvalDecision.approved) {\n output = { type: \"execution-denied\", reason: approvalDecision.result };\n skipped = true;\n } else {\n const step = observation?.turn ?? 0;\n const lifecycleEvent = {\n runId: this.runContext.runId,\n step,\n toolName: toolCall.toolName,\n input: lifecycleSnapshot(prepared.input),\n };\n if (toolCall.callId !== undefined) {\n Object.assign(lifecycleEvent, { toolCallId: toolCall.callId });\n }\n await this.lifecycle?.onToolStart?.(lifecycleEvent);\n const startedAt = Date.now();\n const outcome = await this.runApprovedToolCall(\n prepared,\n toolCall,\n hookArgs,\n effectiveArgs,\n toolObservation,\n observation,\n onStreamEvent,\n );\n output = outcome.output;\n toolExecutionFailed = outcome.failed;\n const durationMs = Date.now() - startedAt;\n await this.lifecycle?.onToolFinish?.(\n outcome.failed\n ? {\n ...lifecycleEvent,\n durationMs,\n success: false,\n error: lifecycleSnapshot(outcome.error),\n }\n : {\n ...lifecycleEvent,\n durationMs,\n success: true,\n output: lifecycleSnapshot(output),\n },\n );\n }\n }\n } catch (error) {\n if (error instanceof AgentInteractionSignal) {\n await toolObservation.suspend({\n ...toolStartArgs,\n interaction: error.interaction,\n });\n throw error;\n }\n await toolObservation.error(\n toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error),\n );\n throw error;\n }\n }\n\n if (output === undefined) {\n throw new Error(`Tool \"${toolCall.toolName}\" did not produce an execution result.`);\n }\n let result = toolOutputToText(output);\n let structuredResult = toolOutputToStructuredResult(output);\n if (!isSkillTool(tool)) {\n const middlewareReplacement = await this.runToolResultMiddlewares({\n ...hookArgs,\n args: effectiveArgs,\n result,\n originalResult: result,\n structuredResult,\n originalStructuredResult: structuredResult,\n turn: observation?.turn ?? 0,\n });\n if (middlewareReplacement !== undefined) {\n output = middlewareReplacement;\n result = toolOutputToText(middlewareReplacement);\n structuredResult = toolOutputToStructuredResult(middlewareReplacement);\n }\n }\n\n const resultAction = await this.activeHook?.onToolResult?.({\n ...hookArgs,\n args: effectiveArgs,\n result,\n structuredResult,\n run: runControl,\n });\n if (!toolExecutionFailed) {\n await toolObservation.end({\n turn: observation?.turn ?? 0,\n toolCall,\n toolName: toolCall.toolName,\n internalCallId,\n args: effectiveArgs,\n result,\n structuredResult,\n skipped,\n toolCallId: toolCall.callId,\n });\n }\n if (resultAction?.type === \"terminate\") {\n throw this.cancel(resultAction.reason);\n }\n\n const resultPayload: ToolResultEventPayload = {\n type: \"tool_result\",\n toolName: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n internalCallId,\n args: effectiveArgs,\n output,\n result,\n structuredResult,\n };\n if (toolCall.callId !== undefined) resultPayload.callId = toolCall.callId;\n onResult?.(resultPayload);\n let resultPart: ToolResultPart = {\n type: \"tool-result\" as const,\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n output,\n };\n if (toolCall.callId !== undefined) {\n resultPart = { ...resultPart, callId: toolCall.callId };\n }\n return resultPart;\n } catch (error) {\n if (error instanceof AgentInteractionSignal) {\n const pending: PendingToolExecution = {\n toolCall,\n effectiveArgs,\n input:\n error.interaction.type === \"tool-approval\"\n ? error.interaction.input\n : parseToolArgs(effectiveArgs),\n internalCallId,\n };\n if (error.rejectMessage !== undefined) pending.rejectMessage = error.rejectMessage;\n throw new ToolExecutionSuspension(error.interaction, pending);\n }\n await toolObservation.error(\n toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error),\n );\n throw error;\n }\n };\n\n if (this.concurrency === 1) {\n const results: ToolResultPart[] = [];\n for (const toolCall of toolCalls) {\n try {\n results.push(await executeOne(toolCall));\n } catch (error) {\n if (error instanceof ToolExecutionSuspension) {\n error.completedResults = [...results];\n error.remainingToolCalls = toolCalls.slice(results.length + 1);\n }\n throw error;\n }\n }\n return results;\n }\n return mapWithConcurrency(toolCalls, this.concurrency, executeOne);\n }\n\n async executeResumed(\n pending: PendingToolExecution,\n onResult?: (result: ToolResultEventPayload) => void,\n onStreamEvent?: (event: AgentToolEventPayload) => void,\n observation?: ToolExecutionObservation,\n ): Promise<ToolResultPart> {\n throwIfAborted(this.abortSignal);\n const { toolCall, internalCallId, effectiveArgs } = pending;\n const tool = this.agent.getTool(toolCall.toolName);\n if (tool === undefined) {\n throw new Error(\n `Cannot resume tool interaction because tool \"${toolCall.toolName}\" is no longer registered.`,\n );\n }\n if (isQuestionTool(tool)) {\n throw new TypeError(\"Question interactions are resolved from their submitted answers.\");\n }\n\n const hookArgs: ToolHookArgs = {\n toolName: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n internalCallId,\n args: effectiveArgs,\n };\n if (toolCall.callId !== undefined) hookArgs.callId = toolCall.callId;\n const toolDefinition = observation?.toolDefinitions?.find(\n (definition) => definition.name === toolCall.toolName,\n );\n const toolMetadata = toolTraceMetadata(tool);\n let toolStartArgs: AgentToolStartArgs = {\n turn: observation?.turn ?? 0,\n toolCall,\n toolName: toolCall.toolName,\n internalCallId,\n args: effectiveArgs,\n };\n if (toolCall.callId !== undefined) {\n toolStartArgs = { ...toolStartArgs, toolCallId: toolCall.callId };\n }\n if (toolDefinition !== undefined) toolStartArgs = { ...toolStartArgs, toolDefinition };\n if (toolMetadata !== undefined) toolStartArgs = { ...toolStartArgs, toolMetadata };\n const observers = await observation?.runObservers.startTool(toolStartArgs);\n const toolObservation = new ToolObserverScope(observers);\n let output: NormalizedToolOutput;\n let failed = false;\n\n try {\n const prepared = prepareToolCallFromInput(tool, pending.input);\n const step = observation?.turn ?? 0;\n const lifecycleEvent = {\n runId: this.runContext.runId,\n step,\n toolName: toolCall.toolName,\n input: lifecycleSnapshot(prepared.input),\n };\n if (toolCall.callId !== undefined) {\n Object.assign(lifecycleEvent, { toolCallId: toolCall.callId });\n }\n await this.lifecycle?.onToolStart?.(lifecycleEvent);\n const startedAt = Date.now();\n const outcome = await this.runApprovedToolCall(\n prepared,\n toolCall,\n hookArgs,\n effectiveArgs,\n toolObservation,\n observation,\n onStreamEvent,\n );\n output = outcome.output;\n failed = outcome.failed;\n const durationMs = Date.now() - startedAt;\n await this.lifecycle?.onToolFinish?.(\n outcome.failed\n ? {\n ...lifecycleEvent,\n durationMs,\n success: false,\n error: lifecycleSnapshot(outcome.error),\n }\n : {\n ...lifecycleEvent,\n durationMs,\n success: true,\n output: lifecycleSnapshot(output),\n },\n );\n\n let result = toolOutputToText(output);\n let structuredResult = toolOutputToStructuredResult(output);\n if (!isSkillTool(tool)) {\n const replacement = await this.runToolResultMiddlewares({\n ...hookArgs,\n args: effectiveArgs,\n result,\n originalResult: result,\n structuredResult,\n originalStructuredResult: structuredResult,\n turn: step,\n });\n if (replacement !== undefined) {\n output = replacement;\n result = toolOutputToText(replacement);\n structuredResult = toolOutputToStructuredResult(replacement);\n }\n }\n const resultAction = await this.activeHook?.onToolResult?.({\n ...hookArgs,\n result,\n structuredResult,\n run: runControl,\n });\n if (!failed) {\n await toolObservation.end({\n turn: step,\n toolCall,\n toolName: toolCall.toolName,\n internalCallId,\n args: effectiveArgs,\n result,\n structuredResult,\n skipped: false,\n toolCallId: toolCall.callId,\n });\n }\n if (resultAction?.type === \"terminate\") {\n throw this.cancel(resultAction.reason);\n }\n const resultPayload: ToolResultEventPayload = {\n type: \"tool_result\",\n toolName: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n internalCallId,\n args: effectiveArgs,\n output,\n result,\n structuredResult,\n };\n if (toolCall.callId !== undefined) resultPayload.callId = toolCall.callId;\n onResult?.(resultPayload);\n let resultPart: ToolResultPart = {\n type: \"tool-result\",\n toolName: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n output,\n };\n if (toolCall.callId !== undefined) resultPart = { ...resultPart, callId: toolCall.callId };\n return resultPart;\n } catch (error) {\n await toolObservation.error(\n toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error),\n );\n throw error;\n }\n }\n\n async resolveResumed(\n pending: PendingToolExecution,\n initialOutput: NormalizedToolOutput,\n onResult?: (result: ToolResultEventPayload) => void,\n observation?: ToolExecutionObservation,\n ): Promise<ToolResultPart> {\n throwIfAborted(this.abortSignal);\n const { toolCall, internalCallId, effectiveArgs } = pending;\n const tool = this.agent.getTool(toolCall.toolName);\n if (tool === undefined) {\n throw new Error(\n `Cannot resume tool interaction because tool \"${toolCall.toolName}\" is no longer registered.`,\n );\n }\n\n const hookArgs: ToolHookArgs = {\n toolName: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n internalCallId,\n args: effectiveArgs,\n };\n if (toolCall.callId !== undefined) hookArgs.callId = toolCall.callId;\n const toolDefinition = observation?.toolDefinitions?.find(\n (definition) => definition.name === toolCall.toolName,\n );\n const toolMetadata = toolTraceMetadata(tool);\n let toolStartArgs: AgentToolStartArgs = {\n turn: observation?.turn ?? 0,\n toolCall,\n toolName: toolCall.toolName,\n internalCallId,\n args: effectiveArgs,\n };\n if (toolCall.callId !== undefined) {\n toolStartArgs = { ...toolStartArgs, toolCallId: toolCall.callId };\n }\n if (toolDefinition !== undefined) toolStartArgs = { ...toolStartArgs, toolDefinition };\n if (toolMetadata !== undefined) toolStartArgs = { ...toolStartArgs, toolMetadata };\n const observers = await observation?.runObservers.startTool(toolStartArgs);\n const toolObservation = new ToolObserverScope(observers);\n\n try {\n let output = initialOutput;\n let result = toolOutputToText(output);\n let structuredResult = toolOutputToStructuredResult(output);\n if (!isSkillTool(tool)) {\n const replacement = await this.runToolResultMiddlewares({\n ...hookArgs,\n args: effectiveArgs,\n result,\n originalResult: result,\n structuredResult,\n originalStructuredResult: structuredResult,\n turn: observation?.turn ?? 0,\n });\n if (replacement !== undefined) {\n output = replacement;\n result = toolOutputToText(replacement);\n structuredResult = toolOutputToStructuredResult(replacement);\n }\n }\n const resultAction = await this.activeHook?.onToolResult?.({\n ...hookArgs,\n result,\n structuredResult,\n run: runControl,\n });\n await toolObservation.end({\n turn: observation?.turn ?? 0,\n toolCall,\n toolName: toolCall.toolName,\n internalCallId,\n args: effectiveArgs,\n result,\n structuredResult,\n skipped: true,\n toolCallId: toolCall.callId,\n });\n if (resultAction?.type === \"terminate\") {\n throw this.cancel(resultAction.reason);\n }\n const resultPayload: ToolResultEventPayload = {\n type: \"tool_result\",\n toolName: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n internalCallId,\n args: effectiveArgs,\n output,\n result,\n structuredResult,\n };\n if (toolCall.callId !== undefined) resultPayload.callId = toolCall.callId;\n onResult?.(resultPayload);\n let resultPart: ToolResultPart = {\n type: \"tool-result\",\n toolName: toolCall.toolName,\n toolCallId: toolCall.toolCallId,\n output,\n };\n if (toolCall.callId !== undefined) resultPart = { ...resultPart, callId: toolCall.callId };\n return resultPart;\n } catch (error) {\n await toolObservation.error(\n toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error),\n );\n throw error;\n }\n }\n\n private async runApprovedToolCall(\n prepared: PreparedToolCall,\n toolCall: ToolCallPart,\n hookArgs: ToolHookArgs,\n effectiveArgs: string,\n toolObservation: ToolObserverScope,\n observation: ToolExecutionObservation | undefined,\n onStreamEvent?: (event: AgentToolEventPayload) => void,\n ): Promise<\n | { output: NormalizedToolOutput; failed: false }\n | { output: NormalizedToolOutput; failed: true; error: unknown }\n > {\n try {\n const toolContext: ToolCallContext = {\n abortSignal: this.abortSignal,\n emitStreamEvent: async (event) => {\n let streamEventArgs: AgentToolStreamEventArgs = {\n turn: observation?.turn ?? 0,\n toolCall,\n toolName: toolCall.toolName,\n internalCallId: hookArgs.internalCallId,\n args: effectiveArgs,\n event,\n };\n if (toolCall.callId !== undefined) {\n streamEventArgs = { ...streamEventArgs, toolCallId: toolCall.callId };\n }\n await toolObservation.streamEvent(streamEventArgs);\n const payload = agentToolEventPayload(toolCall, hookArgs.internalCallId, event);\n if (payload !== undefined) {\n onStreamEvent?.(payload);\n }\n },\n };\n return {\n output: await prepared.call(toolContext),\n failed: false,\n };\n } catch (error) {\n return this.handleToolError(\n toolCall,\n hookArgs,\n effectiveArgs,\n error,\n toolObservation,\n observation,\n );\n }\n }\n\n private prepareToolCall(\n tool: AnyTool | undefined,\n toolName: string,\n args: string,\n ): PreparedToolCall {\n if (tool !== undefined) {\n return prepareRegisteredToolCall(tool, args);\n }\n const input = parseToolArgs(args);\n return {\n input,\n call: (context) => this.agent.callTool(toolName, args, context),\n };\n }\n\n private async handleToolError(\n toolCall: ToolCallPart,\n hookArgs: ToolHookArgs,\n args: string,\n error: unknown,\n toolObservation: ToolObserverScope,\n observation: ToolExecutionObservation | undefined,\n ): Promise<{ output: NormalizedToolOutput; failed: true; error: unknown }> {\n const errorAction = await this.activeHook?.onToolError?.({\n ...hookArgs,\n args,\n error,\n run: runControl,\n });\n await toolObservation.error(\n toolErrorArgs(observation?.turn ?? 0, toolCall, hookArgs.internalCallId, args, error),\n );\n if (errorAction?.type === \"terminate\") {\n throw this.cancel(errorAction.reason);\n }\n return {\n output: {\n type: \"error-text\",\n value: error instanceof Error ? error.toString() : String(error),\n },\n failed: true,\n error,\n };\n }\n\n private async runToolResultMiddlewares(\n args: ToolOutputMiddlewareArgs,\n ): Promise<NormalizedToolOutput | undefined> {\n let result = args.result;\n let structuredResult = args.structuredResult;\n let replaced = false;\n for (const middleware of this.activeMiddlewares()) {\n const outputReplacement = await middleware.onToolOutput?.({\n ...args,\n result,\n structuredResult,\n });\n if (outputReplacement !== undefined) {\n const normalized = normalizeToolOutputMiddlewareResult(outputReplacement);\n if (normalized.result !== undefined) {\n result = normalized.result;\n structuredResult = undefined;\n }\n if (normalized.structuredResult !== undefined) {\n structuredResult = normalized.structuredResult;\n result = toolResultContentToText(normalized.structuredResult);\n }\n replaced = true;\n }\n }\n return replaced\n ? structuredResult === undefined\n ? { type: \"text\", value: result }\n : { type: \"content\", value: structuredResult }\n : undefined;\n }\n\n private async runToolInputMiddlewares(\n args: ToolHookArgs & { turn: number; originalArgs: string },\n ): Promise<string> {\n let current = args.args;\n for (const middleware of this.activeMiddlewares()) {\n const replacement = await middleware.onToolInput?.({\n ...args,\n args: current,\n });\n if (replacement?.args !== undefined) {\n 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: ToolApprovalDecision;\n try {\n decision = await this.approvalHandler(request);\n } catch (error) {\n if (error instanceof AgentInteractionSignal) {\n throw error;\n }\n await observation?.runObservers.event({\n name: \"tool.approval_failed\",\n level: \"ERROR\",\n attributes: {\n ...approvalEventAttributes(request, observation.turn),\n errorName: error instanceof Error ? error.name : typeof error,\n },\n });\n throw error;\n }\n const attributes: JsonObject = {\n ...approvalEventAttributes(request, observation?.turn ?? 0),\n approved: decision.approved,\n };\n if (decision.reason !== undefined) attributes.decisionReason = decision.reason;\n await observation?.runObservers.event({\n name: \"tool.approval_resolved\",\n attributes,\n });\n if (decision.approved) {\n return { approved: true };\n }\n return {\n approved: false,\n result: decision.reason ?? request.rejectMessage ?? \"Tool approval was rejected.\",\n };\n }\n}\n\nfunction createApprovalContext(\n input: unknown,\n hookArgs: ToolHookArgs,\n agent: Pick<Agent, \"id\">,\n run: ToolExecutionRunContext,\n): ToolApprovalContext {\n const approvalRun: ToolApprovalRunContext = {\n agentId: agent.id,\n runId: run.runId,\n };\n if (run.sessionId !== undefined) {\n approvalRun.sessionId = run.sessionId;\n }\n if (run.metadata !== undefined) {\n approvalRun.metadata = run.metadata;\n }\n const context: ToolApprovalContext = {\n toolName: hookArgs.toolName,\n args: lifecycleSnapshot(input),\n rawArgs: hookArgs.args,\n toolCallId: hookArgs.toolCallId,\n internalCallId: hookArgs.internalCallId,\n run: approvalRun,\n };\n if (hookArgs.callId !== undefined) {\n context.callId = hookArgs.callId;\n }\n return context;\n}\n\nfunction approvalEventAttributes(\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?: readonly ToolResultContentPart[] | 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 result: JsonObject = {\n approvalRequired: toolMayRequireApproval(tool.requiresApproval),\n };\n if (isMcpTool(tool)) {\n result.mcpServerName = tool.mcp.serverName;\n result.mcpRemoteName = tool.mcp.remoteName;\n }\n return result;\n}\n\nfunction toolErrorArgs(\n turn: number,\n toolCall: ToolCallPart,\n internalCallId: string,\n args: string,\n error: unknown,\n): AgentToolErrorArgs {\n let observerArgs: AgentToolErrorArgs = {\n turn,\n toolCall,\n toolName: toolCall.toolName,\n internalCallId,\n args,\n error,\n };\n if (toolCall.callId !== undefined) {\n observerArgs = { ...observerArgs, toolCallId: toolCall.callId };\n }\n return observerArgs;\n}\n\nclass ToolObserverScope {\n private terminal = false;\n\n constructor(private readonly observers: ActiveToolObservers | undefined) {}\n\n streamEvent(args: AgentToolStreamEventArgs): Promise<void> | undefined {\n return this.observers?.streamEvent(args);\n }\n\n async end(args: AgentToolEndArgs): Promise<void> {\n if (this.terminal) return;\n this.terminal = true;\n await this.observers?.end(args);\n }\n\n async suspend(args: AgentToolSuspendedArgs): Promise<void> {\n if (this.terminal) return;\n this.terminal = true;\n await this.observers?.suspend(args);\n }\n\n async error(args: AgentToolErrorArgs): Promise<void> {\n if (this.terminal) return;\n this.terminal = true;\n await this.observers?.error(args);\n }\n}\n\nfunction toolOutputToText(output: NormalizedToolOutput): string {\n switch (output.type) {\n case \"text\":\n case \"error-text\":\n return output.value;\n case \"json\":\n case \"error-json\":\n return JSON.stringify(output.value);\n case \"content\":\n return toolResultContentToText(output.value);\n case \"execution-denied\":\n return output.reason ?? \"Tool execution was denied.\";\n }\n}\n\nfunction toolOutputToStructuredResult(\n output: NormalizedToolOutput,\n): readonly ToolResultContentPart[] | undefined {\n return output.type === \"content\" ? output.value : undefined;\n}\n\nfunction agentToolEventPayload(\n toolCall: ToolCallPart,\n internalCallId: string,\n event: ToolCallStreamEvent,\n): AgentToolEventPayload | undefined {\n if (typeof event.agentId !== \"string\" || event.agentId.length === 0) {\n return undefined;\n }\n const payload: AgentToolEventPayload = {\n type: \"agent_tool_event\" as const,\n toolName: toolCall.toolName,\n internalCallId,\n agentId: event.agentId,\n event: event.event as AgentChildStreamEvent<unknown, unknown>,\n };\n if (toolCall.callId !== undefined) {\n payload.toolCallId = toolCall.callId;\n }\n if (event.agentName !== undefined) {\n payload.agentName = event.agentName;\n }\n return payload;\n}\n","import type { Agent } from \"../../agent/agent\";\nimport { AgentRunCancelledError, AgentStreamClosedError, MaxTurnsError } from \"../../agent/errors\";\nimport {\n type AgentInteractionResponse,\n assertAgentInteractionResponse,\n parseAgentContinuation,\n parseAgentInteractionResponse,\n} from \"../../agent/interactions\";\nimport {\n type AgentFinishEvent,\n type AgentLifecycle,\n composeAgentLifecycle,\n lifecycleSnapshot,\n} from \"../../agent/lifecycle\";\nimport { getAgentProviderOutputSchema } from \"../../agent/output-schema\";\nimport type {\n AgentBlockedResult,\n AgentInput,\n AgentResponse,\n AgentResult,\n AgentRunOptions,\n AgentRunSettings,\n AgentSteerInput,\n AgentSteerReceipt,\n AgentStreamEvent,\n AgentSuspendedResult,\n} from \"../../agent/run-types\";\nimport { getAgentToolState } from \"../../agent/tool-state\";\nimport { isStreamingCompletionModel } from \"../../completion/generate-completion\";\nimport {\n assertCompletionRequestSupported,\n type CompletionModel,\n type CompletionRequest,\n type CompletionResponse,\n type CompletionSource,\n getAssistantGenerationMetadata,\n type JsonObject,\n type JsonValue,\n type Message as MessageType,\n type ProviderToolCall,\n parseMessage,\n parseMessages,\n type ToolCallPart,\n type ToolInteractionResponsePart,\n type ToolResultPart,\n textFromAssistantContent,\n Usage,\n} from \"../../completion/index\";\nimport {\n appendGuardrailPolicies,\n type GuardrailDecisionRecord,\n type GuardrailPolicy,\n type GuardrailRunContext,\n hasEnforcedOutputGuardrails,\n runInputGuardrails,\n runOutputGuardrails,\n} from \"../../guardrails\";\nimport type { AgentHook } from \"../../hooks\";\nimport { runControl } from \"../../hooks\";\nimport { MemoryCompactionError } from \"../../memory/errors\";\nimport type { MemoryCompactionInfo, MemoryScope } from \"../../memory/types\";\nimport type { ModelCallOptions } from \"../../model-call-options\";\nimport {\n type ActiveAgentRunObservers,\n type ActiveGenerationObservers,\n startAgentRunObservers,\n} from \"../../observability/group\";\nimport type {\n AgentGenerationEndArgs,\n AgentGenerationModelInfo,\n AgentGenerationStartArgs,\n AgentTraceOptions,\n} from \"../../observability/types\";\nimport {\n type ResolvedRetryOptions,\n resolveRetryOptions,\n retryDelayMs,\n retryErrorAttributes,\n retryOptionsForFailure,\n waitForRetry,\n} from \"../../retry\";\nimport type { AgentMiddleware } from \"../../tool/middleware\";\nimport { isQuestionTool } from \"../../tool/question-tool\";\nimport { abortError, throwIfAborted } from \"../abort\";\nimport { createAsyncQueue } from \"../async-queue\";\nimport { createCompletionRequest } from \"../completion-request\";\nimport { extractRagText } from \"../rag-text\";\nimport { toolMayRequireApproval } from \"./approval-requirement\";\nimport {\n type AgentContinuationState,\n parseContinuationState,\n type QueuedSteering,\n questionResult,\n serializeContinuationState,\n} from \"./continuation-state\";\nimport {\n AgentInteractionSignal,\n approvalInteraction,\n ToolExecutionSuspension,\n} from \"./interaction-suspension\";\nimport { AgentRunMemory, type MemoryPreparation } from \"./memory\";\nimport { fetchContextDocuments, fetchToolDefinitions } from \"./retrieval\";\nimport { getInternalAgentRunOptions, type InternalAgentRunOptions } 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<Output, RawResponse> = AgentRunSettings<Output, RawResponse> & {\n memoryScope?: MemoryScope | undefined;\n continuationState?: AgentContinuationState | undefined;\n interactionResponse?: AgentInteractionResponse | undefined;\n sourceRunId?: string | undefined;\n interactionId?: string | undefined;\n};\n\ntype StreamingCompletionState = {\n response: CompletionResponse | undefined;\n firstDeltaMs: number | undefined;\n emittedToolCallIds: Set<string>;\n providerErrorUsage: Usage;\n};\n\nasync function settleFailureCleanup(\n operations: Array<() => void | Promise<void> | undefined>,\n): Promise<void> {\n for (const operation of operations) {\n try {\n await operation();\n } catch {\n // Cleanup failures must not replace the primary run failure.\n }\n }\n}\n\ntype RawResponseOf<Model> =\n Model extends CompletionModel<infer RawResponse> ? RawResponse : unknown;\n\ntype AgentTerminalResult<Output> = AgentResult<Output>;\n\nexport class AgentRun<Output = string, M extends CompletionModel = CompletionModel> {\n private chatHistory: MessageType[];\n private maxTurnCount: number;\n private activeHook: AgentHook | undefined;\n private readonly activeLifecycle: AgentLifecycle<Output, unknown> | undefined;\n private guardrailPolicies: GuardrailPolicy[];\n private guardrailDecisions: GuardrailDecisionRecord[] = [];\n private readonly concurrency: number;\n private traceOptions: AgentTraceOptions | undefined;\n private completionRetryOptions: ResolvedRetryOptions | undefined;\n private readonly requestMiddlewares: AgentMiddleware[];\n private readonly steeringMessages: QueuedSteering[] = [];\n private runState: \"idle\" | \"running\" | \"closing\" | \"completed\" | \"errored\" | \"cancelled\" = \"idle\";\n private readonly memoryRecorder: AgentRunMemory;\n private readonly memoryScope: MemoryScope | undefined;\n private readonly onInternalFailure: InternalAgentRunOptions[\"onFailure\"];\n private readonly onInternalMemoryCompaction: InternalAgentRunOptions[\"onMemoryCompaction\"];\n private memoryCompaction: MemoryCompactionInfo | undefined;\n private readonly requestedRunId: string | undefined;\n private readonly continuationState: AgentContinuationState | undefined;\n private readonly interactionResponse: AgentInteractionResponse | undefined;\n private readonly resumedFrom: { runId: string; interactionId: string } | undefined;\n private currentMessages: MessageType[] = [];\n private cancellationError: AgentRunCancelledError | undefined;\n private activeGeneration: { turn: number; observers: ActiveGenerationObservers } | undefined;\n private readonly abortController = new AbortController();\n private removeExternalAbortListener: (() => void) | undefined;\n\n private constructor(\n private readonly agent: Agent<Output, M>,\n private promptMessage: MessageType,\n initialHistory: MessageType[] = [],\n options: AgentRunCreateOptions<Output, RawResponseOf<M>> = {},\n ) {\n this.chatHistory = initialHistory;\n this.maxTurnCount = assertNonnegativeSafeInteger(\n options.maxTurns ?? agent.defaultMaxTurns ?? 0,\n \"maxTurns\",\n );\n const internalOptions = getInternalAgentRunOptions(options);\n this.activeHook = internalOptions?.hook;\n this.onInternalFailure = internalOptions?.onFailure;\n this.onInternalMemoryCompaction = internalOptions?.onMemoryCompaction;\n this.requestedRunId = normalizeRequestedRunId(internalOptions?.runId);\n this.activeLifecycle = composeAgentLifecycle(agent.lifecycle, options.lifecycle) as\n | AgentLifecycle<Output, unknown>\n | undefined;\n this.guardrailPolicies =\n options.guardrails === undefined\n ? [...agent.guardrails]\n : appendGuardrailPolicies([...agent.guardrails], options.guardrails);\n const configuredConcurrency = assertPositiveSafeInteger(\n options.toolConcurrency ?? 1,\n \"toolConcurrency\",\n );\n this.concurrency =\n this.activeHook !== undefined ||\n agent.tools.some(\n (tool) => toolMayRequireApproval(tool.requiresApproval) || isQuestionTool(tool),\n )\n ? 1\n : configuredConcurrency;\n this.traceOptions = options.trace;\n const retrySetting = options.retries === undefined ? agent.retries : options.retries;\n this.completionRetryOptions =\n retrySetting === undefined || retrySetting === false\n ? undefined\n : resolveRetryOptions(retrySetting);\n this.requestMiddlewares = [...(options.middlewares ?? [])];\n this.memoryScope = options.memoryScope;\n this.memoryRecorder = new AgentRunMemory(agent, options.memoryScope, initialHistory);\n this.continuationState = options.continuationState;\n this.interactionResponse = options.interactionResponse;\n if (options.continuationState !== undefined) {\n this.steeringMessages.push(\n ...options.continuationState.steering.map((entry) => ({\n id: entry.id,\n messages: [...entry.messages],\n })),\n );\n }\n this.resumedFrom =\n options.sourceRunId === undefined || options.interactionId === undefined\n ? undefined\n : { runId: options.sourceRunId, interactionId: options.interactionId };\n this.linkExternalAbortSignal(options.abortSignal);\n }\n\n static fromAgent<Output, M extends CompletionModel>(\n agent: Agent<Output, M>,\n options: AgentRunOptions<Output, RawResponseOf<M>>,\n ): AgentRun<Output, M> {\n const normalized = normalizeAgentInput(agent.id, options);\n if (normalized.scope !== undefined && agent.memory === undefined) {\n throw new TypeError(`Agent \"${agent.id}\" cannot use a session without a memory store.`);\n }\n return new AgentRun(agent, normalized.prompt, normalized.history, {\n ...options,\n memoryScope: normalized.scope,\n continuationState: normalized.continuationState,\n interactionResponse: normalized.interactionResponse,\n sourceRunId: normalized.sourceRunId,\n interactionId: normalized.interactionId,\n });\n }\n\n steer(input: AgentSteerInput): AgentSteerReceipt {\n if (this.isTerminal() || this.cancellationError !== undefined) {\n throw new AgentStreamClosedError();\n }\n const receipt: AgentSteerReceipt = Object.freeze({\n id: globalThis.crypto.randomUUID(),\n status: \"queued\",\n });\n this.steeringMessages.push({ id: receipt.id, messages: normalizeSteeringInput(input) });\n return receipt;\n }\n\n cancel(reason: string): 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.setCancellationError(error);\n }\n\n private setCancellationError(error: AgentRunCancelledError): void {\n this.cancellationError = error;\n if (!this.abortController.signal.aborted) this.abortController.abort(error);\n }\n\n async generate(): Promise<AgentTerminalResult<Output>> {\n this.startRun();\n const runId = this.requestedRunId ?? globalThis.crypto.randomUUID();\n let usage = Usage.empty();\n let currentTurns = 0;\n let lastPrompt = this.promptMessage;\n let newMessages: MessageType[] = [this.promptMessage];\n let runObservers: ActiveAgentRunObservers | undefined;\n let pendingTurnMessages: MessageType[] = [];\n\n try {\n this.throwIfCancelled();\n const memoryPreparation =\n this.continuationState === undefined\n ? await this.memoryRecorder.prepareHistory(\n runId,\n newMessages.length,\n this.abortController.signal,\n )\n : undefined;\n if (memoryPreparation !== undefined) {\n this.chatHistory = memoryPreparation.history;\n usage = Usage.add(usage, memoryPreparation.usage);\n this.memoryCompaction = memoryPreparation.compaction;\n await this.notifyInternalMemoryCompaction(memoryPreparation.compaction);\n }\n runObservers = await this.startRunObservers(runId);\n if (memoryPreparation !== undefined) {\n await this.recordMemoryCompaction(memoryPreparation, runObservers);\n }\n this.throwIfCancelled();\n await this.activeLifecycle?.onStart?.({\n runId,\n input: lifecycleSnapshot(this.promptMessage),\n history: lifecycleSnapshot(this.chatHistory),\n maxTurns: this.maxTurnCount,\n });\n if (this.continuationState === undefined) {\n const inputResult = await runInputGuardrails(this.guardrailPolicies, {\n prompt: this.promptMessage,\n history: this.chatHistory,\n inputText: textFromMessage(this.promptMessage),\n run: this.guardrailRunContext(runId),\n });\n for (const decision of inputResult.decisions) {\n await this.recordGuardrailDecision(decision, runObservers);\n }\n this.promptMessage = inputResult.prompt;\n if (inputResult.blocked) {\n const text = inputResult.message ?? \"The request was blocked by a guardrail.\";\n const result: AgentBlockedResult = {\n status: \"blocked\",\n stage: \"input\",\n runId,\n text,\n usage,\n messages: [this.promptMessage, { role: \"assistant\", content: text }],\n trace: runObservers.trace,\n guardrails: [...this.guardrailDecisions],\n ...this.memoryCompactionResult(),\n };\n if (this.resumedFrom !== undefined) result.resumedFrom = this.resumedFrom;\n this.runState = \"closing\";\n await this.runLifecycleFinish(result);\n await runObservers.end(result);\n this.runState = \"completed\";\n this.disposeAbortLink();\n return result;\n }\n }\n\n newMessages = [this.promptMessage];\n await this.memoryRecorder.commitAcceptedInput(runId, newMessages);\n pendingTurnMessages = this.memoryRecorder.pendingTurnMessages(newMessages);\n await this.runRunStartHook(newMessages);\n if (this.continuationState !== undefined) {\n await runObservers.event({\n name: \"agent.interaction_response\",\n attributes: {\n sourceRunId: this.resumedFrom?.runId,\n interactionId: this.resumedFrom?.interactionId,\n interactionType: this.interactionResponse?.type,\n },\n });\n try {\n const toolResults = await this.resolveContinuationTools(\n runId,\n newMessages,\n undefined,\n undefined,\n {\n turn: 1,\n runObservers,\n },\n );\n const toolMessage: MessageType = { role: \"tool\", content: toolResults };\n newMessages.push(toolMessage);\n await this.memoryRecorder.commitMessages(runId, 1, [toolMessage], pendingTurnMessages);\n await this.drainSteeringMessages(runId, 1, newMessages, pendingTurnMessages);\n await this.memoryRecorder.commitCompletedTurn(runId, 1, pendingTurnMessages);\n } catch (error) {\n if (error instanceof ToolExecutionSuspension) {\n return this.finishSuspension({\n runId,\n turn: 1,\n usage,\n newMessages,\n pendingTurnMessages,\n runObservers,\n suspension: error,\n uncommittedMessages: [],\n });\n }\n throw error;\n }\n }\n while (currentTurns <= this.maxTurnCount + 1) {\n const prompt = newMessages.at(-1);\n if (prompt === undefined) {\n throw new Error(\"AgentRun requires at least one message\");\n }\n\n lastPrompt = prompt;\n currentTurns += 1;\n\n const historyForRequest = [...this.chatHistory, ...newMessages.slice(0, -1)];\n await this.runTurnStartHook(currentTurns, prompt, historyForRequest, newMessages);\n await this.runCompletionCallHook(prompt, historyForRequest, newMessages);\n\n const request = await this.createTurnRequest(prompt, historyForRequest, currentTurns);\n\n let response: CompletionResponse;\n try {\n response = await this.runCompletion(request, currentTurns, runObservers);\n } catch (error) {\n await settleFailureCleanup([\n () => this.runCompletionErrorHook(prompt, error, newMessages),\n ]);\n throw error;\n }\n response = await this.runCompletionResponseMiddlewares(request, response, currentTurns);\n usage = Usage.add(usage, response.usage);\n this.updateRunProgress(newMessages);\n await this.runCompletionResponseHook(prompt, response, newMessages);\n await this.runTurnEndHook(currentTurns, response, newMessages);\n await this.activeLifecycle?.onStepFinish?.({\n runId,\n step: currentTurns,\n response: lifecycleSnapshot(response),\n usage: lifecycleSnapshot(usage),\n });\n\n const toolCalls = response.choice.filter(\n (item): item is ToolCallPart => item.type === \"tool-call\",\n );\n const assistantMessage = this.generatedAssistantMessage(response, request);\n newMessages.push(assistantMessage);\n if (toolCalls.length === 0) {\n if (this.steeringMessages.length > 0) {\n await this.memoryRecorder.commitMessages(\n runId,\n currentTurns,\n [assistantMessage],\n pendingTurnMessages,\n );\n }\n const appliedSteering = await this.drainSteeringMessages(\n runId,\n currentTurns,\n newMessages,\n pendingTurnMessages,\n { closeWhenEmpty: true },\n );\n if (appliedSteering.length > 0) {\n for (const receipt of appliedSteering) {\n await runObservers.event({\n name: \"agent.steering_applied\",\n attributes: { id: receipt.id, turn: currentTurns },\n });\n }\n await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);\n continue;\n }\n\n const guardedOutput = await this.runOutputGuardrailsForResponse(\n runId,\n usage,\n response,\n newMessages,\n runObservers,\n );\n response = guardedOutput.response;\n const finalAssistantMessage = this.generatedAssistantMessage(response, request);\n newMessages[newMessages.length - 1] = finalAssistantMessage;\n await this.memoryRecorder.commitMessages(\n runId,\n currentTurns,\n [finalAssistantMessage],\n pendingTurnMessages,\n );\n const result = this.createTerminalResult(\n runId,\n guardedOutput.text,\n guardedOutput.blocked,\n usage,\n newMessages,\n runObservers,\n );\n if (result.status === \"completed\") {\n await this.runRunEndHook(result, newMessages);\n }\n await this.memoryRecorder.commitCompletedRun(\n runId,\n currentTurns,\n newMessages,\n pendingTurnMessages,\n );\n await this.runLifecycleFinish(result);\n await runObservers.end(result);\n this.runState = \"completed\";\n this.disposeAbortLink();\n return result;\n }\n\n this.updateRunProgress(newMessages);\n let toolResults: ToolResultPart[];\n try {\n toolResults = await this.executeToolCalls(\n runId,\n toolCalls,\n newMessages,\n undefined,\n undefined,\n {\n turn: currentTurns,\n runObservers,\n toolDefinitions: request.tools,\n },\n );\n } catch (error) {\n if (error instanceof ToolExecutionSuspension) {\n return this.finishSuspension({\n runId,\n turn: currentTurns,\n usage,\n newMessages,\n pendingTurnMessages,\n runObservers,\n suspension: error,\n uncommittedMessages: [assistantMessage],\n });\n }\n throw error;\n }\n const toolMessage: MessageType = { role: \"tool\", content: toolResults };\n newMessages.push(toolMessage);\n await this.memoryRecorder.commitMessages(\n runId,\n currentTurns,\n [assistantMessage, toolMessage],\n pendingTurnMessages,\n );\n await this.drainSteeringMessages(runId, currentTurns, newMessages, pendingTurnMessages);\n await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);\n }\n\n throw new MaxTurnsError(this.maxTurnCount, [...this.chatHistory, ...newMessages], lastPrompt);\n } catch (error) {\n if (error instanceof MemoryCompactionError && error.usage !== undefined) {\n usage = Usage.add(usage, error.usage);\n }\n this.runState = \"closing\";\n const runError = this.normalizeRunError(error);\n const reportedError = await this.reportRunFailure(\n runError,\n runId,\n usage,\n newMessages,\n runObservers,\n );\n this.runState = reportedError instanceof AgentRunCancelledError ? \"cancelled\" : \"errored\";\n this.disposeAbortLink();\n throw reportedError;\n }\n }\n\n async *events(): AsyncIterable<AgentStreamEvent<Output, RawResponseOf<M>>> {\n this.startRun();\n const runId = this.requestedRunId ?? globalThis.crypto.randomUUID();\n let usage = Usage.empty();\n let currentTurns = 0;\n let lastPrompt = this.promptMessage;\n let newMessages: MessageType[] = [this.promptMessage];\n const bufferOutputDeltas = hasEnforcedOutputGuardrails(this.guardrailPolicies);\n let runObservers: ActiveAgentRunObservers | undefined;\n let pendingTurnMessages: MessageType[] = [];\n\n try {\n this.throwIfCancelled();\n const memoryPreparation =\n this.continuationState === undefined\n ? await this.memoryRecorder.prepareHistory(\n runId,\n newMessages.length,\n this.abortController.signal,\n )\n : undefined;\n if (memoryPreparation !== undefined) {\n this.chatHistory = memoryPreparation.history;\n usage = Usage.add(usage, memoryPreparation.usage);\n this.memoryCompaction = memoryPreparation.compaction;\n await this.notifyInternalMemoryCompaction(memoryPreparation.compaction);\n }\n runObservers = await this.startRunObservers(runId);\n if (memoryPreparation !== undefined) {\n await this.recordMemoryCompaction(memoryPreparation, runObservers);\n }\n if (memoryPreparation?.compaction !== undefined) {\n yield { type: \"memory_compaction\", ...memoryPreparation.compaction };\n }\n this.throwIfCancelled();\n await this.activeLifecycle?.onStart?.({\n runId,\n input: lifecycleSnapshot(this.promptMessage),\n history: lifecycleSnapshot(this.chatHistory),\n maxTurns: this.maxTurnCount,\n });\n if (this.continuationState === undefined) {\n const inputResult = await runInputGuardrails(this.guardrailPolicies, {\n prompt: this.promptMessage,\n history: this.chatHistory,\n inputText: textFromMessage(this.promptMessage),\n run: this.guardrailRunContext(runId),\n });\n for (const decision of inputResult.decisions) {\n await this.recordGuardrailDecision(decision, runObservers);\n yield { type: \"guardrail_decision\", decision };\n }\n this.promptMessage = inputResult.prompt;\n if (inputResult.blocked) {\n const text = inputResult.message ?? \"The request was blocked by a guardrail.\";\n const result: AgentBlockedResult = {\n status: \"blocked\",\n stage: \"input\",\n runId,\n text,\n usage,\n messages: [this.promptMessage, { role: \"assistant\", content: text }],\n trace: runObservers.trace,\n guardrails: [...this.guardrailDecisions],\n ...this.memoryCompactionResult(),\n };\n if (this.resumedFrom !== undefined) result.resumedFrom = this.resumedFrom;\n this.runState = \"closing\";\n await this.runLifecycleFinish(result);\n await runObservers.end(result);\n this.runState = \"completed\";\n this.disposeAbortLink();\n yield { type: \"final\", result };\n return;\n }\n }\n\n newMessages = [this.promptMessage];\n await this.memoryRecorder.commitAcceptedInput(runId, newMessages);\n pendingTurnMessages = this.memoryRecorder.pendingTurnMessages(newMessages);\n await this.runRunStartHook(newMessages);\n if (this.continuationState !== undefined) {\n const responsePart =\n this.promptMessage.role === \"tool\" ? this.promptMessage.content[0] : undefined;\n if (responsePart === undefined || responsePart.type === \"tool-result\") {\n throw new TypeError(\"Agent continuation response message is invalid.\");\n }\n yield {\n type: \"interaction_response\",\n response: responsePart,\n sourceRunId: this.resumedFrom?.runId ?? this.continuationState.kind,\n };\n try {\n const execution = this.executeContinuationToolStream(runId, newMessages, {\n turn: 1,\n runObservers,\n });\n for await (const event of execution.events) {\n yield { turn: 1, ...event };\n }\n const toolResults = await execution.results;\n const toolMessage: MessageType = { role: \"tool\", content: toolResults };\n newMessages.push(toolMessage);\n await this.memoryRecorder.commitMessages(runId, 1, [toolMessage], pendingTurnMessages);\n for (const receipt of await this.drainSteeringMessages(\n runId,\n 1,\n newMessages,\n pendingTurnMessages,\n )) {\n yield { type: \"steering_applied\", id: receipt.id, turn: 1 };\n }\n await this.memoryRecorder.commitCompletedTurn(runId, 1, pendingTurnMessages);\n } catch (error) {\n if (error instanceof ToolExecutionSuspension) {\n const result = await this.finishSuspension({\n runId,\n turn: 1,\n usage,\n newMessages,\n pendingTurnMessages,\n runObservers,\n suspension: error,\n uncommittedMessages: [],\n });\n yield { type: \"final\", result };\n return;\n }\n throw error;\n }\n }\n while (currentTurns <= this.maxTurnCount + 1) {\n const prompt = newMessages.at(-1);\n if (prompt === undefined) {\n throw new Error(\"AgentRun requires at least one message\");\n }\n\n lastPrompt = prompt;\n currentTurns += 1;\n\n const historyForRequest = [...this.chatHistory, ...newMessages.slice(0, -1)];\n yield {\n type: \"turn_start\",\n turn: currentTurns,\n prompt,\n history: historyForRequest,\n };\n await this.runTurnStartHook(currentTurns, prompt, historyForRequest, newMessages);\n await this.runCompletionCallHook(prompt, historyForRequest, newMessages);\n\n const request = await this.createTurnRequest(prompt, historyForRequest, currentTurns);\n\n assertCompletionRequestSupported(this.agent.model, request, { streaming: true });\n const providerRequest = this.providerTraceRequest(request, { stream: true });\n const generationStartArgs = this.generationStartArgs(\n currentTurns,\n request,\n providerRequest,\n );\n const generationObservers = await runObservers.startGeneration(generationStartArgs);\n this.activeGeneration = { turn: currentTurns, observers: generationObservers };\n const generationStartedAt = Date.now();\n yield {\n type: \"generation_start\",\n turn: currentTurns,\n request,\n modelInfo: generationStartArgs.modelInfo,\n };\n const bufferResponseEvents = 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 bufferResponseEvents,\n bufferOutputDeltas,\n generationStartedAt,\n generationObservers,\n runObservers,\n state: completionState,\n })) {\n yield event;\n }\n } finally {\n usage = Usage.add(usage, completionState.providerErrorUsage);\n }\n if (completionState.response === undefined) {\n throw new Error(\"Streaming completion ended without a response.\");\n }\n response = completionState.response;\n } catch (error) {\n await settleFailureCleanup([\n () => this.closeActiveGeneration(error),\n () => this.runCompletionErrorHook(prompt, error, newMessages),\n ]);\n throw error;\n }\n const { firstDeltaMs, emittedToolCallIds } = completionState;\n\n let generationEndArgs: AgentGenerationEndArgs = {\n turn: currentTurns,\n response,\n };\n if (firstDeltaMs !== undefined) {\n generationEndArgs = { ...generationEndArgs, firstDeltaMs };\n }\n this.activeGeneration = undefined;\n await generationObservers.end(generationEndArgs);\n response = await this.runCompletionResponseMiddlewares(request, response, currentTurns);\n usage = Usage.add(usage, response.usage);\n this.updateRunProgress(newMessages);\n await this.runCompletionResponseHook(prompt, response, newMessages);\n await this.runTurnEndHook(currentTurns, response, newMessages);\n await this.activeLifecycle?.onStepFinish?.({\n runId,\n step: currentTurns,\n response: lifecycleSnapshot(response),\n usage: lifecycleSnapshot(usage),\n });\n\n const toolCalls = response.choice.filter(\n (item): item is ToolCallPart => item.type === \"tool-call\",\n );\n const assistantMessage = this.generatedAssistantMessage(response, request);\n newMessages.push(assistantMessage);\n\n if (toolCalls.length === 0) {\n let emittedTurnEnd = false;\n if (!bufferOutputDeltas) {\n if (bufferResponseEvents) {\n for (const event of responseStreamEvents(currentTurns, response)) {\n yield event as AgentStreamEvent<Output, RawResponseOf<M>>;\n }\n }\n yield {\n type: \"turn_end\",\n turn: currentTurns,\n response: response as CompletionResponse<RawResponseOf<M>>,\n firstDeltaMs,\n };\n emittedTurnEnd = true;\n }\n if (this.steeringMessages.length > 0) {\n await this.memoryRecorder.commitMessages(\n runId,\n currentTurns,\n [assistantMessage],\n pendingTurnMessages,\n );\n }\n const appliedSteering = await this.drainSteeringMessages(\n runId,\n currentTurns,\n newMessages,\n pendingTurnMessages,\n { closeWhenEmpty: true },\n );\n for (const receipt of appliedSteering) {\n yield { type: \"steering_applied\", id: receipt.id, turn: currentTurns };\n }\n if (appliedSteering.length > 0) {\n await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);\n continue;\n }\n\n for await (const event of this.completeStreamingRun({\n runId,\n turn: currentTurns,\n request,\n response,\n firstDeltaMs,\n usage,\n newMessages,\n pendingTurnMessages,\n runObservers,\n bufferResponseEvents,\n bufferOutputDeltas,\n emittedTurnEnd,\n })) {\n yield event;\n }\n return;\n }\n\n if (bufferResponseEvents) {\n for (const event of responseStreamEvents(currentTurns, response)) {\n yield event as AgentStreamEvent<Output, RawResponseOf<M>>;\n }\n } else {\n for (const toolCall of toolCalls) {\n if (!emittedToolCallIds.has(toolCall.toolCallId)) {\n yield { type: \"tool_call\", turn: currentTurns, toolCall };\n }\n }\n }\n this.updateRunProgress(newMessages);\n yield {\n type: \"turn_end\",\n turn: currentTurns,\n response: response as CompletionResponse<RawResponseOf<M>>,\n firstDeltaMs,\n };\n\n let toolResults: ToolResultPart[];\n try {\n const toolExecution = this.executeStreamingToolCalls(runId, toolCalls, newMessages, {\n turn: currentTurns,\n runObservers,\n toolDefinitions: request.tools,\n });\n for await (const result of toolExecution.events) {\n yield { turn: currentTurns, ...result };\n }\n toolResults = await toolExecution.results;\n } catch (error) {\n if (error instanceof ToolExecutionSuspension) {\n const result = await this.finishSuspension({\n runId,\n turn: currentTurns,\n usage,\n newMessages,\n pendingTurnMessages,\n runObservers,\n suspension: error,\n uncommittedMessages: [assistantMessage],\n });\n yield { type: \"final\", result };\n return;\n }\n throw error;\n }\n const toolMessage: MessageType = { role: \"tool\", content: toolResults };\n newMessages.push(toolMessage);\n await this.memoryRecorder.commitMessages(\n runId,\n currentTurns,\n [assistantMessage, toolMessage],\n pendingTurnMessages,\n );\n for (const receipt of await this.drainSteeringMessages(\n runId,\n currentTurns,\n newMessages,\n pendingTurnMessages,\n )) {\n yield { type: \"steering_applied\", id: receipt.id, turn: currentTurns };\n }\n await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);\n }\n\n throw new MaxTurnsError(this.maxTurnCount, [...this.chatHistory, ...newMessages], lastPrompt);\n } catch (error) {\n if (error instanceof MemoryCompactionError && error.usage !== undefined) {\n usage = Usage.add(usage, error.usage);\n }\n this.runState = \"closing\";\n const runError = this.normalizeRunError(error);\n const reportedError = await this.reportRunFailure(\n runError,\n runId,\n usage,\n newMessages,\n runObservers,\n );\n this.runState = reportedError instanceof AgentRunCancelledError ? \"cancelled\" : \"errored\";\n const finalUsage = usage;\n yield { type: \"error\", error: reportedError, usage: finalUsage };\n this.disposeAbortLink();\n return;\n } finally {\n if (this.runState === \"running\" || this.runState === \"closing\") {\n const cancellation =\n this.cancellationError ??\n new AgentRunCancelledError([...this.chatHistory, ...newMessages], \"Agent stream closed.\");\n this.cancellationError = cancellation;\n await settleFailureCleanup([() => this.closeActiveGeneration(cancellation)]);\n await this.reportRunFailure(cancellation, runId, usage, newMessages, runObservers);\n this.runState = \"cancelled\";\n this.disposeAbortLink();\n }\n }\n }\n\n private async runCompletion(\n request: CompletionRequest,\n turn: number,\n runObservers: ActiveAgentRunObservers,\n ): Promise<CompletionResponse> {\n assertCompletionRequestSupported(this.agent.model, request);\n 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 this.throwIfCancelled();\n response = await this.agent.model.completion(request, this.modelCallOptions());\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<CompletionRequest> {\n const ragText = extractRagText(prompt);\n const abortSignal = this.abortController.signal;\n const documents = await fetchContextDocuments(this.agent, ragText, abortSignal);\n const toolDefinitions = await fetchToolDefinitions(this.agent, ragText, abortSignal);\n const request = createCompletionRequest(providerMessages([...history, prompt]), {\n instructions: this.agent.instructions,\n documents,\n tools: [...toolDefinitions, ...getAgentToolState(this.agent).providerTools],\n temperature: this.agent.temperature,\n maxTokens: this.agent.maxTokens,\n providerOptions: this.agent.providerOptions,\n toolChoice: this.agent.toolChoice,\n outputSchema: getAgentProviderOutputSchema(this.agent),\n });\n return this.runCompletionRequestMiddlewares(request, turn);\n }\n\n private async *streamCompletion(args: {\n request: CompletionRequest;\n turn: number;\n bufferResponseEvents: boolean;\n bufferOutputDeltas: boolean;\n generationStartedAt: number;\n generationObservers: ActiveGenerationObservers;\n runObservers: ActiveAgentRunObservers;\n state: StreamingCompletionState;\n }): AsyncIterable<AgentStreamEvent<Output, RawResponseOf<M>>> {\n const model = this.agent.model;\n if (!isStreamingCompletionModel(model)) {\n throw new TypeError(\"Streaming completion requires a streaming-capable model.\");\n }\n const accumulator = new CompletionStreamAccumulator();\n for (let attempt = 1; ; attempt += 1) {\n let hasProviderProgress = false;\n try {\n this.throwIfCancelled();\n for await (const event of model.streamCompletion(args.request, this.modelCallOptions())) {\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 (event.type === \"tool_call_delta\") {\n yield addTurnToToolCallDelta(args.turn, event);\n }\n if (mapped !== undefined) {\n await args.generationObservers.update?.({ turn: args.turn, delta: mapped });\n if (mapped.type === \"tool_call\") {\n args.state.emittedToolCallIds.add(mapped.toolCall.toolCallId);\n }\n const shouldBuffer =\n args.bufferResponseEvents ||\n (args.bufferOutputDeltas &&\n (mapped.type === \"text_delta\" || mapped.type === \"reasoning_delta\"));\n if (!shouldBuffer) {\n yield addTurn(args.turn, mapped) as AgentStreamEvent<Output, RawResponseOf<M>>;\n }\n }\n }\n 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: CompletionRequest;\n response: CompletionResponse;\n firstDeltaMs: number | undefined;\n usage: Usage;\n newMessages: MessageType[];\n pendingTurnMessages: MessageType[];\n runObservers: ActiveAgentRunObservers;\n bufferResponseEvents: boolean;\n bufferOutputDeltas: boolean;\n emittedTurnEnd: boolean;\n }): AsyncIterable<AgentStreamEvent<Output, RawResponseOf<M>>> {\n const guardedOutput = await this.runOutputGuardrailsForResponse(\n args.runId,\n args.usage,\n args.response,\n args.newMessages,\n args.runObservers,\n );\n for (const decision of guardedOutput.decisions) {\n yield { type: \"guardrail_decision\", decision };\n }\n\n const response = guardedOutput.response;\n const assistantMessage = this.generatedAssistantMessage(response, args.request);\n args.newMessages[args.newMessages.length - 1] = assistantMessage;\n await this.memoryRecorder.commitMessages(\n args.runId,\n args.turn,\n [assistantMessage],\n args.pendingTurnMessages,\n );\n if (!args.emittedTurnEnd && (args.bufferResponseEvents || args.bufferOutputDeltas)) {\n for (const event of responseStreamEvents(args.turn, response, args.bufferResponseEvents)) {\n yield event as AgentStreamEvent<Output, RawResponseOf<M>>;\n }\n }\n if (!args.emittedTurnEnd) {\n yield {\n type: \"turn_end\",\n turn: args.turn,\n response: response as CompletionResponse<RawResponseOf<M>>,\n firstDeltaMs: args.firstDeltaMs,\n };\n }\n\n const result = this.createTerminalResult(\n args.runId,\n guardedOutput.text,\n guardedOutput.blocked,\n args.usage,\n args.newMessages,\n args.runObservers,\n );\n if (result.status === \"completed\") {\n await this.runRunEndHook(result, args.newMessages);\n }\n await this.memoryRecorder.commitCompletedRun(\n args.runId,\n args.turn,\n args.newMessages,\n args.pendingTurnMessages,\n );\n await this.runLifecycleFinish(result);\n await args.runObservers.end(result);\n this.runState = \"completed\";\n this.disposeAbortLink();\n yield { type: \"final\", result };\n }\n\n private async finishSuspension(args: {\n runId: string;\n turn: number;\n usage: Usage;\n newMessages: MessageType[];\n pendingTurnMessages: MessageType[];\n runObservers: ActiveAgentRunObservers;\n suspension: ToolExecutionSuspension;\n uncommittedMessages: MessageType[];\n }): Promise<AgentSuspendedResult> {\n const partialToolMessage: MessageType | undefined =\n args.suspension.completedResults.length === 0\n ? undefined\n : { role: \"tool\", content: [...args.suspension.completedResults] };\n if (partialToolMessage !== undefined) {\n args.newMessages.push(partialToolMessage);\n args.uncommittedMessages.push(partialToolMessage);\n }\n await this.memoryRecorder.commitMessages(\n args.runId,\n args.turn,\n args.uncommittedMessages,\n args.pendingTurnMessages,\n );\n await this.memoryRecorder.commitCompletedRun(\n args.runId,\n args.turn,\n args.newMessages,\n args.pendingTurnMessages,\n );\n\n this.runState = \"closing\";\n\n const continuationState: AgentContinuationState = {\n kind: \"anvia.agent-continuation\",\n history: [...this.chatHistory],\n messages: [...args.newMessages],\n pending: args.suspension.pending,\n remainingToolCalls: [...args.suspension.remainingToolCalls],\n steering: this.steeringMessages.map((entry) => ({\n id: entry.id,\n messages: [...entry.messages],\n })),\n };\n if (this.memoryScope !== undefined) continuationState.memoryScope = this.memoryScope;\n const continuation = parseAgentContinuation({\n version: 1,\n agentId: this.agent.id,\n sourceRunId: args.runId,\n interaction: args.suspension.interaction,\n state: serializeContinuationState(continuationState),\n });\n const result: AgentSuspendedResult = {\n status: \"suspended\",\n runId: args.runId,\n text: latestAssistantText([...this.chatHistory, ...args.newMessages]),\n usage: args.usage,\n messages: [...args.newMessages],\n trace: args.runObservers.trace,\n guardrails: [...this.guardrailDecisions],\n interaction: continuation.interaction,\n continuation,\n ...generationArtifacts([...this.chatHistory, ...args.newMessages]),\n ...this.memoryCompactionResult(),\n };\n if (this.resumedFrom !== undefined) result.resumedFrom = this.resumedFrom;\n await this.runLifecycleFinish(result);\n await args.runObservers.end(result);\n this.runState = \"completed\";\n this.currentMessages = [...args.newMessages];\n this.disposeAbortLink();\n return result;\n }\n\n private generatedAssistantMessage(\n response: CompletionResponse,\n _request: CompletionRequest,\n ): MessageType {\n const generation: JsonObject = {\n provider: this.agent.model.provider,\n modelId: this.agent.model.modelId,\n usage: { ...response.usage },\n };\n if (response.contextUsage !== undefined) generation.contextUsage = response.contextUsage;\n if (response.sources !== undefined) generation.sources = response.sources;\n if (response.providerToolCalls !== undefined) {\n generation.providerToolCalls = response.providerToolCalls;\n }\n const metadata: JsonObject = { anvia: { generation } };\n let message: MessageType = {\n role: \"assistant\",\n content: response.choice,\n metadata,\n };\n if (response.messageId !== undefined) message = { ...message, id: response.messageId };\n return message;\n }\n\n private providerTraceRequest(\n request: CompletionRequest,\n options: { stream?: boolean | undefined } = {},\n ): JsonObject | undefined {\n try {\n return this.agent.model.traceRequest?.(request, options);\n } catch (error) {\n return {\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n private generationStartArgs(\n turn: number,\n request: CompletionRequest,\n providerRequest: JsonObject | undefined,\n ): AgentGenerationStartArgs & { modelInfo: AgentGenerationModelInfo } {\n let args: AgentGenerationStartArgs & { modelInfo: AgentGenerationModelInfo } = {\n turn,\n request,\n modelInfo: {\n provider: this.agent.model.provider,\n modelId: this.agent.model.modelId,\n capabilities: this.agent.model.capabilities,\n },\n };\n if (providerRequest !== undefined) args = { ...args, providerRequest };\n return args;\n }\n\n private retryOptionsForFailure(\n error: unknown,\n attempt: number,\n turn: number,\n streaming: boolean,\n ): ResolvedRetryOptions | undefined {\n if (this.abortController.signal.aborted) return undefined;\n return retryOptionsForFailure(this.completionRetryOptions, {\n error,\n attempt,\n turn,\n streaming,\n });\n }\n\n private async scheduleCompletionRetry(\n error: unknown,\n attempt: number,\n turn: number,\n streaming: boolean,\n options: ResolvedRetryOptions,\n runObservers: ActiveAgentRunObservers,\n ): 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, this.abortController.signal);\n }\n\n private async executeToolCalls(\n runId: string,\n toolCalls: ToolCallPart[],\n newMessages: MessageType[],\n onResult?: (result: ToolResultEventPayload) => void,\n onStreamEvent?: (event: AgentToolEventPayload) => void,\n observation?: ToolExecutionObservation,\n ): Promise<ToolResultPart[]> {\n const executor = this.createToolExecutor(runId, newMessages);\n return executor.execute(toolCalls, onResult, onStreamEvent, observation);\n }\n\n private createToolExecutor(runId: string, newMessages: MessageType[]): ToolCallExecutor {\n return new ToolCallExecutor(\n this.agent,\n this.activeHook,\n async (request) => {\n throw new AgentInteractionSignal(approvalInteraction(request), request.rejectMessage);\n },\n this.activeLifecycle,\n {\n runId,\n sessionId: this.memoryScope?.sessionId,\n metadata: this.memoryScope?.metadata,\n },\n this.concurrency,\n this.requestMiddlewares,\n this.abortController.signal,\n (reason) => this.cancelled(newMessages, reason),\n );\n }\n\n private async resolveContinuationTools(\n runId: string,\n newMessages: MessageType[],\n onResult: ((result: ToolResultEventPayload) => void) | undefined,\n onStreamEvent: ((event: AgentToolEventPayload) => void) | undefined,\n observation: ToolExecutionObservation,\n ): Promise<ToolResultPart[]> {\n const state = this.continuationState;\n const response = this.interactionResponse;\n if (state === undefined || response === undefined) {\n return [];\n }\n const pending = state.pending;\n const interaction = this.resumedFrom;\n if (interaction === undefined) {\n throw new TypeError(\"Agent continuation is missing its source run linkage.\");\n }\n const executor = this.createToolExecutor(runId, newMessages);\n const results: ToolResultPart[] = [];\n if (response.type === \"tool-approval\") {\n const attributes: JsonObject = {\n approvalId: interaction.interactionId,\n toolName: pending.toolCall.toolName,\n toolCallId: pending.toolCall.toolCallId,\n internalCallId: pending.internalCallId,\n approved: response.approved,\n };\n if (response.reason !== undefined) attributes.decisionReason = response.reason;\n await observation.runObservers.event({\n name: \"tool.approval_resolved\",\n attributes,\n });\n if (response.approved) {\n results.push(await executor.executeResumed(pending, onResult, onStreamEvent, observation));\n } else {\n const output = {\n type: \"execution-denied\" as const,\n reason: response.reason ?? pending.rejectMessage ?? \"Tool approval was rejected.\",\n };\n results.push(await executor.resolveResumed(pending, output, onResult, observation));\n }\n } else {\n const currentTool = this.agent.getTool(pending.toolCall.toolName);\n if (currentTool === undefined || !isQuestionTool(currentTool)) {\n throw new TypeError(\n `Cannot resume question interaction because tool \"${pending.toolCall.toolName}\" is no longer registered as a question tool.`,\n );\n }\n const output = questionResult(response.answers);\n results.push(await executor.resolveResumed(pending, output, onResult, observation));\n }\n try {\n results.push(\n ...(await executor.execute(state.remainingToolCalls, onResult, onStreamEvent, observation)),\n );\n } catch (error) {\n if (error instanceof ToolExecutionSuspension) {\n error.completedResults = [...results, ...error.completedResults];\n }\n throw error;\n }\n return results;\n }\n\n private executeStreamingToolCalls(\n runId: string,\n toolCalls: ToolCallPart[],\n newMessages: MessageType[],\n observation: ToolExecutionObservation,\n ): {\n events: AsyncIterable<ToolExecutionEventPayload>;\n results: Promise<ToolResultPart[]>;\n } {\n const events = createAsyncQueue<ToolExecutionEventPayload>();\n const results = this.executeToolCalls(\n runId,\n toolCalls,\n newMessages,\n (result) => events.enqueue(result),\n (event) => events.enqueue(event),\n observation,\n );\n results.then(\n () => events.close(),\n (error: unknown) => events.throw(error),\n );\n return { events, results };\n }\n\n private executeContinuationToolStream(\n runId: string,\n newMessages: MessageType[],\n observation: ToolExecutionObservation,\n ): {\n events: AsyncIterable<ToolExecutionEventPayload>;\n results: Promise<ToolResultPart[]>;\n } {\n const events = createAsyncQueue<ToolExecutionEventPayload>();\n const results = this.resolveContinuationTools(\n runId,\n newMessages,\n (result) => events.enqueue(result),\n (event) => events.enqueue(event),\n observation,\n );\n results.then(\n () => events.close(),\n (error: unknown) => events.throw(error),\n );\n return { events, results };\n }\n\n private async closeActiveGeneration(error: unknown): Promise<void> {\n const active = this.activeGeneration;\n if (active === undefined) {\n return;\n }\n this.activeGeneration = undefined;\n await active.observers.error({ turn: active.turn, error });\n }\n\n private updateRunProgress(messages: MessageType[]): void {\n this.currentMessages = [...messages];\n }\n\n private async runLifecycleFinish(result: AgentTerminalResult<Output>): Promise<void> {\n const common = {\n runId: result.runId,\n text: result.text,\n usage: lifecycleSnapshot(result.usage),\n messages: lifecycleSnapshot(result.messages),\n };\n if (result.memoryCompaction !== undefined) {\n Object.assign(common, { memoryCompaction: lifecycleSnapshot(result.memoryCompaction) });\n }\n const event =\n result.status === \"completed\"\n ? {\n ...common,\n status: \"completed\",\n output: lifecycleSnapshot(result.output),\n }\n : result.status === \"blocked\"\n ? {\n ...common,\n status: \"blocked\",\n stage: result.stage,\n }\n : {\n ...common,\n status: \"suspended\",\n interaction: lifecycleSnapshot(result.interaction),\n };\n await this.activeLifecycle?.onFinish?.(event as AgentFinishEvent<Output>);\n }\n\n private async runLifecycleError(\n error: unknown,\n runId: string,\n usage: Usage,\n messages: MessageType[],\n ): Promise<unknown | undefined> {\n try {\n await this.activeLifecycle?.onError?.({\n runId,\n error: lifecycleSnapshot(error),\n usage: lifecycleSnapshot(usage),\n messages: lifecycleSnapshot([...this.chatHistory, ...messages]),\n });\n return undefined;\n } catch (lifecycleError) {\n return lifecycleError;\n }\n }\n\n private async reportRunFailure(\n error: unknown,\n runId: string,\n usage: Usage,\n messages: MessageType[],\n runObservers: ActiveAgentRunObservers | undefined,\n ): Promise<unknown> {\n const reportedError = await this.resolveReportedRunError(error, runId, usage, messages);\n await settleFailureCleanup([\n () =>\n this.onInternalFailure?.({\n error: reportedError,\n messages: lifecycleSnapshot(messages),\n }),\n () =>\n runObservers?.error({\n 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 text: string;\n blocked: boolean;\n response: CompletionResponse;\n decisions: GuardrailDecisionRecord[];\n }> {\n const originalOutput = textFromAssistantContent(response.choice);\n const result = await runOutputGuardrails(this.guardrailPolicies, {\n outputText: originalOutput,\n messages: [...this.chatHistory, ...messages],\n usage,\n run: this.guardrailRunContext(runId),\n });\n for (const decision of result.decisions) {\n await this.recordGuardrailDecision(decision, runObservers);\n }\n const text = result.blocked\n ? (result.message ?? \"The response was blocked by a guardrail.\")\n : result.outputText;\n if (text === originalOutput) {\n return { text, blocked: result.blocked, response, decisions: result.decisions };\n }\n return {\n text,\n blocked: result.blocked,\n response: {\n ...response,\n choice: [{ type: \"text\", text }],\n },\n decisions: result.decisions,\n };\n }\n\n private createTerminalResult(\n runId: string,\n text: string,\n blocked: boolean,\n usage: Usage,\n messages: MessageType[],\n runObservers: ActiveAgentRunObservers,\n ): AgentTerminalResult<Output> {\n const common = {\n runId,\n text,\n usage,\n messages: [...messages],\n trace: runObservers.trace,\n guardrails: [...this.guardrailDecisions],\n ...generationArtifacts(messages),\n ...this.memoryCompactionResult(),\n };\n if (this.resumedFrom !== undefined) Object.assign(common, { resumedFrom: this.resumedFrom });\n if (blocked) {\n return { ...common, status: \"blocked\", stage: \"output\" };\n }\n return {\n ...common,\n status: \"completed\",\n output: this.parseOutput(text),\n };\n }\n\n private parseOutput(text: string): Output {\n const schema = this.agent.outputSchema;\n if (schema === undefined) return text as Output;\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch (error) {\n throw new Error(\"Agent expected the model response to be valid JSON.\", { cause: error });\n }\n return schema.parse(json);\n }\n\n private memoryCompactionResult(): {\n memoryCompaction?: MemoryCompactionInfo | undefined;\n } {\n return this.memoryCompaction === undefined\n ? {}\n : { memoryCompaction: lifecycleSnapshot(this.memoryCompaction) };\n }\n\n private async recordGuardrailDecision(\n decision: GuardrailDecisionRecord,\n runObservers: ActiveAgentRunObservers,\n ): Promise<void> {\n this.guardrailDecisions.push(decision);\n await runObservers.event({\n name: \"guardrail.decision\",\n level: decision.action === \"block\" ? \"WARNING\" : \"DEFAULT\",\n attributes: guardrailDecisionAttributes(decision),\n });\n }\n\n private async recordMemoryCompaction(\n preparation: MemoryPreparation,\n runObservers: ActiveAgentRunObservers,\n ): Promise<void> {\n const compaction = preparation.compaction;\n if (compaction === undefined) {\n return;\n }\n await runObservers.event({\n name: \"memory.compaction\",\n attributes: {\n originalMessageCount: compaction.originalMessageCount,\n compactedMessageCount: compaction.compactedMessageCount,\n retainedMessageCount: compaction.retainedMessageCount,\n attempts: compaction.attempts,\n inputTokens: compaction.usage.inputTokens,\n outputTokens: compaction.usage.outputTokens,\n totalTokens: compaction.usage.totalTokens,\n },\n });\n }\n\n private async notifyInternalMemoryCompaction(\n compaction: MemoryCompactionInfo | undefined,\n ): Promise<void> {\n if (compaction === undefined) {\n return;\n }\n await this.onInternalMemoryCompaction?.(lifecycleSnapshot(compaction));\n }\n\n private guardrailRunContext(runId: string): GuardrailRunContext {\n const context: GuardrailRunContext = {\n agentId: this.agent.id,\n runId,\n };\n if (this.memoryScope !== undefined) {\n context.sessionId = this.memoryScope.sessionId;\n if (this.memoryScope.metadata !== undefined) {\n context.metadata = this.memoryScope.metadata;\n }\n }\n return context;\n }\n\n private async startRunObservers(runId: string): Promise<ActiveAgentRunObservers> {\n const observability = this.agent.observability;\n return startAgentRunObservers(\n observability?.observers ?? {},\n {\n runId,\n agentName: this.agent.name,\n agentDescription: this.agent.description,\n instructions: this.agent.instructions,\n trace: this.traceOptions,\n promptRef: this.traceOptions?.promptRef,\n prompt: this.promptMessage,\n history: this.chatHistory,\n maxTurns: this.maxTurnCount,\n },\n {\n primaryTrace: observability?.primaryTrace,\n errorPolicy: observability?.errorPolicy ?? \"ignore\",\n },\n );\n }\n\n private async runCompletionCallHook(\n prompt: MessageType,\n history: MessageType[],\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onCompletionCall?.({\n prompt,\n history,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runRunStartHook(newMessages: MessageType[]): Promise<void> {\n const action = await this.activeHook?.onRunStart?.({\n prompt: this.promptMessage,\n history: this.chatHistory,\n maxTurns: this.maxTurnCount,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runRunEndHook(\n result: AgentResponse<Output>,\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onRunEnd?.({\n status: \"completed\",\n output: result.output,\n text: result.text,\n usage: result.usage,\n messages: result.messages,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runRunErrorHook(\n error: unknown,\n usage: Usage,\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onRunError?.({\n error,\n usage,\n messages: [...this.chatHistory, ...newMessages],\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runTurnStartHook(\n turn: number,\n prompt: MessageType,\n history: MessageType[],\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onTurnStart?.({\n turn,\n prompt,\n history,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runTurnEndHook(\n turn: number,\n response: CompletionResponse,\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onTurnEnd?.({\n turn,\n response,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runCompletionRequestMiddlewares(\n request: CompletionRequest,\n turn: number,\n ): Promise<CompletionRequest> {\n let current = request;\n for (const middleware of this.activeMiddlewares()) {\n const replacement = await middleware.onCompletionRequest?.({\n turn,\n request: current,\n originalRequest: request,\n });\n if (replacement?.request !== undefined) {\n current = replacement.request;\n }\n }\n return current;\n }\n\n private async runCompletionResponseMiddlewares(\n request: CompletionRequest,\n response: CompletionResponse,\n turn: number,\n ): Promise<CompletionResponse> {\n let current = response;\n for (const middleware of this.activeMiddlewares()) {\n const replacement = await middleware.onCompletionResponse?.({\n turn,\n request,\n response: current,\n originalResponse: response,\n });\n if (replacement?.response !== undefined) {\n current = replacement.response;\n }\n }\n return current;\n }\n\n private async runCompletionResponseHook(\n prompt: MessageType,\n response:\n | Awaited<ReturnType<M[\"completion\"]>>\n | Awaited<ReturnType<CompletionModel[\"completion\"]>>,\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onCompletionResponse?.({\n prompt,\n response,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runCompletionErrorHook(\n prompt: MessageType,\n error: unknown,\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onCompletionError?.({\n prompt,\n error,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private activeMiddlewares(): AgentMiddleware[] {\n return [...this.agent.middlewares, ...this.requestMiddlewares];\n }\n\n private shouldBufferStreamResponseEvents(): boolean {\n return (\n this.activeHook?.onCompletionResponse !== undefined ||\n this.activeMiddlewares().some((middleware) => middleware.onCompletionResponse !== undefined)\n );\n }\n\n private async drainSteeringMessages(\n runId: string,\n turn: number,\n newMessages: MessageType[],\n pendingTurnMessages: MessageType[],\n options: { closeWhenEmpty?: boolean } = {},\n ): Promise<QueuedSteering[]> {\n const receipts = this.steeringMessages.splice(0);\n if (receipts.length === 0) {\n if (options.closeWhenEmpty === true) {\n this.runState = \"closing\";\n }\n return [];\n }\n const messages = receipts.flatMap((receipt) => receipt.messages);\n newMessages.push(...messages);\n await this.memoryRecorder.commitMessages(runId, turn, messages, pendingTurnMessages);\n return receipts;\n }\n\n private startRun(): void {\n if (this.runState === \"idle\") {\n this.runState = \"running\";\n return;\n }\n if (this.runState === \"running\") {\n throw new Error(\"Agent stream is already running.\");\n }\n throw new Error(\"Agent stream has already been consumed.\");\n }\n\n private isTerminal(): boolean {\n return this.runState !== \"idle\" && this.runState !== \"running\";\n }\n\n private cancelled(newMessages: MessageType[], reason: string): AgentRunCancelledError {\n if (this.cancellationError !== undefined) return this.cancellationError;\n const error = new AgentRunCancelledError([...this.chatHistory, ...newMessages], reason);\n this.setCancellationError(error);\n return error;\n }\n\n private linkExternalAbortSignal(signal: AbortSignal | undefined): void {\n if (signal === undefined) return;\n const cancelFromSignal = () => {\n if (this.cancellationError !== undefined || this.isTerminal()) return;\n const cause = abortError(signal.reason);\n const reason = abortReason(signal.reason);\n const messages =\n this.currentMessages.length === 0 ? [this.promptMessage] : [...this.currentMessages];\n this.setCancellationError(\n new AgentRunCancelledError([...this.chatHistory, ...messages], reason, { cause }),\n );\n };\n if (signal.aborted) {\n cancelFromSignal();\n return;\n }\n signal.addEventListener(\"abort\", cancelFromSignal, { once: true });\n this.removeExternalAbortListener = () => signal.removeEventListener(\"abort\", cancelFromSignal);\n }\n\n private throwIfCancelled(): void {\n if (this.cancellationError !== undefined) throw this.cancellationError;\n throwIfAborted(this.abortController.signal);\n }\n\n private normalizeRunError(error: unknown): unknown {\n return this.abortController.signal.aborted && this.cancellationError !== undefined\n ? this.cancellationError\n : error;\n }\n\n private modelCallOptions(): ModelCallOptions {\n return { abortSignal: this.abortController.signal };\n }\n\n private disposeAbortLink(): void {\n this.removeExternalAbortListener?.();\n this.removeExternalAbortListener = undefined;\n }\n}\n\nfunction abortReason(reason: unknown): string {\n if (typeof reason === \"string\" && reason.trim().length > 0) return reason;\n if (reason instanceof Error && reason.message.trim().length > 0) return reason.message;\n return \"External abort signal.\";\n}\n\nfunction normalizeAgentInput(\n agentId: string,\n input: AgentInput,\n): {\n prompt: MessageType;\n history: MessageType[];\n scope?: MemoryScope | undefined;\n continuationState?: AgentContinuationState | undefined;\n interactionResponse?: AgentInteractionResponse | undefined;\n sourceRunId?: string | undefined;\n interactionId?: string | undefined;\n} {\n if (typeof input !== \"object\" || input === null || Array.isArray(input)) {\n throw new TypeError(\"Agent runs require one options object with prompt or messages.\");\n }\n const hasContinuation = \"continuation\" in input && input.continuation !== undefined;\n const hasPrompt = \"prompt\" in input && input.prompt !== undefined;\n const hasMessages = \"messages\" in input && input.messages !== undefined;\n if (Number(hasContinuation) + Number(hasPrompt) + Number(hasMessages) !== 1) {\n throw new TypeError(\"Agent runs require exactly one of prompt, messages, or continuation.\");\n }\n if (hasContinuation) {\n if (!(\"response\" in input) || input.response === undefined) {\n throw new TypeError(\"Agent continuation runs require an interaction response.\");\n }\n if (\"session\" in input && input.session !== undefined) {\n throw new TypeError(\"Agent continuations carry their memory scope and cannot use session.\");\n }\n const continuation = parseAgentContinuation(input.continuation);\n if (continuation.agentId !== agentId) {\n throw new TypeError(\n `Agent continuation belongs to \"${continuation.agentId}\", not \"${agentId}\".`,\n );\n }\n const response = parseAgentInteractionResponse(input.response);\n assertAgentInteractionResponse(continuation.interaction, response);\n const state = parseContinuationState(continuation.state, continuation.interaction);\n let responsePart: ToolInteractionResponsePart;\n if (response.type === \"tool-approval\") {\n responsePart = {\n type: \"tool-approval-response\",\n interactionId: continuation.interaction.id,\n toolCallId: continuation.interaction.toolCallId,\n toolName: continuation.interaction.toolName,\n approved: response.approved,\n };\n if (response.reason !== undefined)\n responsePart = { ...responsePart, reason: response.reason };\n } else {\n responsePart = {\n type: \"tool-question-response\",\n interactionId: continuation.interaction.id,\n toolCallId: continuation.interaction.toolCallId,\n toolName: continuation.interaction.toolName,\n answers: response.answers,\n };\n }\n if (continuation.interaction.callId !== undefined) {\n responsePart = { ...responsePart, callId: continuation.interaction.callId };\n }\n const normalized = {\n prompt: parseMessage({ role: \"tool\", content: [responsePart] }),\n history: [...state.history, ...state.messages],\n continuationState: state,\n interactionResponse: response,\n sourceRunId: continuation.sourceRunId,\n interactionId: continuation.interaction.id,\n };\n if (state.memoryScope !== undefined) {\n Object.assign(normalized, { scope: normalizeMemoryScope(state.memoryScope) });\n }\n return normalized;\n }\n if (hasPrompt) {\n const prompt = input.prompt;\n if (\n typeof prompt !== \"string\" &&\n (typeof prompt !== \"object\" || prompt === null || prompt.role !== \"user\")\n ) {\n throw new TypeError(\"Agent prompt must be text or a user message.\");\n }\n const parsedPrompt = parseMessage(\n typeof prompt === \"string\" ? { role: \"user\", content: prompt } : prompt,\n );\n if (parsedPrompt.role !== \"user\") {\n throw new TypeError(\"Agent prompt must be text or a user message.\");\n }\n const normalized = {\n prompt: parsedPrompt,\n history: [],\n };\n if (input.session !== undefined) {\n Object.assign(normalized, { scope: normalizeMemoryScope(input.session) });\n }\n return normalized;\n }\n if (input.session !== undefined) {\n throw new TypeError(\"Agent messages cannot be combined with a persisted session.\");\n }\n const messages = input.messages;\n if (!Array.isArray(messages) || messages.length === 0) {\n throw new TypeError(\"Agent input transcript must contain at least one message.\");\n }\n const parsedMessages = parseMessages(messages);\n const activePrompt = parsedMessages.at(-1);\n if (activePrompt === undefined) {\n throw new TypeError(\"Agent input transcript must contain at least one message.\");\n }\n if (activePrompt.role !== \"user\") {\n throw new TypeError(\"Agent input transcript must end with a user message.\");\n }\n return {\n prompt: activePrompt,\n history: parsedMessages.slice(0, -1),\n };\n}\n\nfunction normalizeSteeringInput(input: AgentSteerInput): MessageType[] {\n if (typeof input !== \"object\" || input === null || Array.isArray(input)) {\n throw new TypeError(\"Agent steering requires one options object with prompt or messages.\");\n }\n const hasPrompt = \"prompt\" in input && input.prompt !== undefined;\n const hasMessages = \"messages\" in input && input.messages !== undefined;\n if (hasPrompt === hasMessages) {\n throw new TypeError(\"Agent steering requires exactly one of prompt or messages.\");\n }\n if (hasPrompt) {\n const prompt = input.prompt;\n if (\n typeof prompt !== \"string\" &&\n (typeof prompt !== \"object\" || prompt === null || prompt.role !== \"user\")\n ) {\n throw new TypeError(\"Agent steering prompt must be text or a user message.\");\n }\n const parsedPrompt = parseMessage(\n typeof prompt === \"string\" ? { role: \"user\", content: prompt } : prompt,\n );\n if (parsedPrompt.role !== \"user\") {\n throw new TypeError(\"Agent steering prompt must be text or a user message.\");\n }\n return [parsedPrompt];\n }\n const messages = input.messages;\n if (!Array.isArray(messages) || messages.length === 0) {\n throw new TypeError(\"Agent steering messages must contain at least one user message.\");\n }\n const parsedMessages = parseMessages(messages);\n if (parsedMessages.some((message) => message.role !== \"user\")) {\n throw new TypeError(\"Agent steering messages must all be user messages.\");\n }\n return parsedMessages;\n}\n\nfunction normalizeMemoryScope(scope: MemoryScope): MemoryScope {\n if (typeof scope !== \"object\" || scope === null) {\n throw new TypeError(\"Agent session must be an object.\");\n }\n if (typeof scope.sessionId !== \"string\" || scope.sessionId.trim().length === 0) {\n throw new TypeError(\"Agent sessionId must be a non-empty string.\");\n }\n const normalized: MemoryScope = {\n sessionId: scope.sessionId.trim(),\n };\n if (scope.userId !== undefined) normalized.userId = scope.userId;\n if (scope.metadata !== undefined) normalized.metadata = scope.metadata;\n return lifecycleSnapshot(normalized);\n}\n\nfunction normalizeRequestedRunId(runId: string | undefined): string | undefined {\n if (runId === undefined) {\n return undefined;\n }\n if (typeof runId !== \"string\" || runId.trim().length === 0) {\n throw new TypeError(\"runId must be a non-empty string.\");\n }\n return runId;\n}\n\nfunction responseStreamEvents(\n turn: number,\n response: CompletionResponse,\n includeProviderArtifacts = true,\n): AgentStreamEvent[] {\n const events: AgentStreamEvent[] = [];\n for (const item of response.choice) {\n if (item.type === \"text\") {\n if (item.text.length > 0) {\n events.push({ type: \"text_delta\", turn, delta: item.text });\n }\n continue;\n }\n\n if (item.type === \"reasoning\") {\n if (item.details === undefined) {\n if (item.text.length > 0) {\n events.push(reasoningDeltaEvent(turn, item.text, { id: item.id }));\n }\n continue;\n }\n\n for (const content of item.details) {\n const delta =\n content.type === \"encrypted\" || content.type === \"redacted\" ? content.data : content.text;\n events.push(\n reasoningDeltaEvent(turn, delta, {\n id: item.id,\n contentType: content.type,\n signature: content.type === \"text\" ? content.signature : undefined,\n }),\n );\n }\n continue;\n }\n\n if (item.type === \"tool-call\") {\n events.push({ type: \"tool_call\", turn, toolCall: item });\n }\n }\n if (includeProviderArtifacts) {\n for (const source of response.sources ?? []) {\n events.push({ type: \"source\", turn, source });\n }\n for (const toolCall of response.providerToolCalls ?? []) {\n events.push({ type: \"provider_tool_call\", turn, toolCall });\n }\n }\n return events;\n}\n\nfunction generationArtifacts(messages: MessageType[]): {\n sources?: CompletionSource[];\n providerToolCalls?: ProviderToolCall[];\n 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 const artifacts: {\n sources?: CompletionSource[];\n providerToolCalls?: ProviderToolCall[];\n contextUsage?: import(\"../../completion/index\").ContextUsage;\n } = {};\n if (sources.size > 0) artifacts.sources = [...sources.values()];\n if (providerToolCalls.size > 0) {\n artifacts.providerToolCalls = [...providerToolCalls.values()];\n }\n if (contextUsage !== undefined) artifacts.contextUsage = contextUsage;\n return artifacts;\n}\n\ntype ReasoningDeltaEvent = Extract<AgentStreamEvent, { type: \"reasoning_delta\" }>;\n\nfunction reasoningDeltaEvent(\n turn: number,\n delta: string,\n details: {\n id?: ReasoningDeltaEvent[\"id\"] | undefined;\n contentType?: ReasoningDeltaEvent[\"contentType\"] | undefined;\n signature?: ReasoningDeltaEvent[\"signature\"] | undefined;\n } = {},\n): ReasoningDeltaEvent {\n const event: ReasoningDeltaEvent = {\n type: \"reasoning_delta\",\n turn,\n delta,\n };\n if (details.id !== undefined) {\n event.id = details.id;\n }\n if (details.contentType !== undefined) {\n event.contentType = details.contentType;\n }\n if (details.signature !== undefined) {\n event.signature = details.signature;\n }\n return event;\n}\n\nfunction textFromMessage(message: MessageType): string {\n if (message.role === \"system\") {\n return message.content;\n }\n if (typeof message.content === \"string\") {\n return message.content;\n }\n return message.content\n .flatMap((content) => {\n if (content.type === \"text\") {\n return [content.text];\n }\n if (content.type === \"file\" && content.data.type === \"text\") {\n return [content.data.text];\n }\n return [];\n })\n .join(\"\\n\");\n}\n\nfunction latestAssistantText(messages: readonly MessageType[]): string {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index];\n if (message?.role === \"assistant\") {\n return typeof message.content === \"string\"\n ? message.content\n : textFromAssistantContent(message.content);\n }\n }\n return \"\";\n}\n\nfunction providerMessages(messages: readonly MessageType[]): MessageType[] {\n const providerMessages: MessageType[] = [];\n for (const message of messages) {\n if (message.role !== \"tool\") {\n providerMessages.push(message);\n continue;\n }\n const results = message.content.filter((part) => part.type === \"tool-result\");\n if (results.length > 0) {\n providerMessages.push({ ...message, content: results });\n }\n }\n return providerMessages;\n}\n\nfunction guardrailDecisionAttributes(\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","import type { CompletionModel } from \"../completion\";\nimport type { AgentRun } from \"../internal/agent-runtime/agent-run\";\nimport type {\n AgentSteerInput,\n AgentSteerReceipt,\n AgentStream,\n AgentStreamEvent,\n} from \"./run-types\";\n\ntype RawResponseOf<Model> =\n Model extends CompletionModel<infer RawResponse> ? RawResponse : unknown;\n\nexport function createAgentStream<Output, M extends CompletionModel>(\n run: AgentRun<Output, M>,\n): AgentStream<AgentStreamEvent<Output, RawResponseOf<M>>> {\n return new DefaultAgentStream(run);\n}\n\nclass DefaultAgentStream<Output, M extends CompletionModel>\n implements AgentStream<AgentStreamEvent<Output, RawResponseOf<M>>>\n{\n private consuming = false;\n private completed = false;\n\n constructor(private readonly run: AgentRun<Output, M>) {}\n\n steer(input: AgentSteerInput): AgentSteerReceipt {\n return this.run.steer(input);\n }\n\n [Symbol.asyncIterator](): AsyncIterator<AgentStreamEvent<Output, RawResponseOf<M>>> {\n return this.consume()[Symbol.asyncIterator]();\n }\n\n private async *consume(): AsyncIterableIterator<AgentStreamEvent<Output, RawResponseOf<M>>> {\n if (this.completed) {\n throw new Error(\"Agent stream has already been consumed.\");\n }\n if (this.consuming) {\n throw new Error(\"Agent stream is already running.\");\n }\n this.consuming = true;\n try {\n for await (const event of this.run.events()) {\n yield event;\n }\n } finally {\n if (!this.completed) {\n this.run.cancel(\"Agent stream consumer closed the stream.\");\n }\n this.consuming = false;\n this.completed = true;\n }\n }\n}\n","import { z } from \"zod\";\nimport { isStreamingCompletionModel } from \"../completion/generate-completion\";\nimport type { CompletionModel } from \"../completion/index\";\nimport { createTool } from \"../tool/create-tool\";\nimport type { Tool, ToolCallContext, ToolCallStreamEvent } from \"../tool/tool\";\nimport type { Agent } from \"./agent\";\nimport { AgentRunBlockedError, AgentToolSuspensionError } from \"./errors\";\nimport type { AgentToolOptions } from \"./types\";\n\nexport function createAgentTool<Output, M extends CompletionModel, ContextDocument>(\n agent: Agent<Output, M, ContextDocument>,\n options: AgentToolOptions,\n): Tool<{ prompt: string }, Output> {\n if (options.suspension !== \"reject\") {\n throw new TypeError('Agent.asTool() requires suspension: \"reject\".');\n }\n const description =\n options.description ?? agent.description ?? `Prompt the ${options.name} agent.`;\n\n return createTool({\n name: options.name,\n description,\n inputSchema: z.object({\n prompt: z.string().describe(\"The prompt to send to the agent.\"),\n }),\n execute: async ({ prompt }, context: ToolCallContext) => {\n if (\n options.stream === true &&\n context.emitStreamEvent !== undefined &&\n agent.model.capabilities.streaming &&\n isStreamingCompletionModel(agent.model)\n ) {\n let completed = false;\n let output!: Output;\n const childStream = agent.stream({\n prompt,\n maxTurns: options.maxTurns,\n abortSignal: context.abortSignal,\n });\n for await (const event of childStream) {\n const streamEvent: ToolCallStreamEvent = {\n agentId: agent.id,\n event,\n };\n if (agent.name !== undefined) {\n streamEvent.agentName = agent.name;\n }\n await context.emitStreamEvent(streamEvent);\n if (event.type === \"error\") {\n throw event.error;\n }\n if (event.type === \"final\") {\n if (event.result.status === \"suspended\") {\n throw new AgentToolSuspensionError(event.result);\n }\n if (event.result.status === \"blocked\") {\n throw new AgentRunBlockedError(event.result);\n }\n output = event.result.output;\n completed = true;\n }\n }\n if (!completed) {\n throw new Error(`Agent tool \"${options.name}\" ended without a final result.`);\n }\n return output;\n }\n const response = await agent.generate({\n prompt,\n maxTurns: options.maxTurns,\n abortSignal: context.abortSignal,\n });\n if (response.status === \"suspended\") {\n throw new AgentToolSuspensionError(response);\n }\n if (response.status === \"blocked\") {\n throw new AgentRunBlockedError(response);\n }\n return response.output;\n },\n });\n}\n","export function normalizeAgentId(id: string): string {\n if (typeof id !== \"string\") {\n throw new TypeError(\"Agent id must be a string.\");\n }\n\n const normalized = id.trim();\n if (normalized.length === 0) {\n throw new TypeError(\"Agent id must be a non-empty string.\");\n }\n\n return normalized;\n}\n","import { assertPositiveInteger } from \"./assert\";\nimport type {\n MemoryCompactionConflictRetryOptions,\n MemoryCompactor,\n MemoryOptions,\n MemorySavePolicy,\n} from \"./types\";\n\ntype ResolvedMemoryOptions = {\n savePolicy: MemorySavePolicy;\n compaction?:\n | {\n trigger: { afterMessages: number };\n retention: { recentUserTurns: number };\n compactor: MemoryCompactor;\n conflictRetries: false | MemoryCompactionConflictRetryOptions;\n }\n | undefined;\n};\n\nexport function resolveMemoryOptions(options: MemoryOptions = {}): ResolvedMemoryOptions {\n const resolved: ResolvedMemoryOptions = {\n savePolicy: options.savePolicy ?? \"message\",\n };\n if (options.compaction !== undefined) {\n assertPositiveInteger(\n options.compaction.trigger.afterMessages,\n \"compaction.trigger.afterMessages\",\n );\n const recentUserTurns = options.compaction.retention?.recentUserTurns ?? 4;\n assertPositiveInteger(recentUserTurns, \"compaction.retention.recentUserTurns\");\n if (typeof options.compaction.compactor !== \"function\") {\n throw new TypeError(\"compaction.compactor must be a function.\");\n }\n const conflictRetries = options.compaction.conflictRetries ?? false;\n if (conflictRetries !== false) {\n assertPositiveInteger(conflictRetries.maxAttempts, \"compaction.conflictRetries.maxAttempts\");\n }\n resolved.compaction = {\n trigger: {\n afterMessages: options.compaction.trigger.afterMessages,\n },\n retention: {\n recentUserTurns,\n },\n compactor: options.compaction.compactor,\n conflictRetries,\n };\n }\n return resolved;\n}\n","import type { CompletionModel, ProviderTool } from \"../completion\";\nimport { isProviderTool } from \"../completion/types\";\nimport { appendGuardrailPolicies } from \"../guardrails\";\nimport { isMcpTool } from \"../mcp\";\nimport { resolveMemoryOptions } from \"../memory/options\";\nimport { isToolIndex, type ToolIndex } from \"../tool/dynamic-tools\";\nimport type { AnyTool } from \"../tool/tool\";\nimport type { AgentMemory, AgentOptions, ResolvedAgentOptions } from \"./types\";\n\nconst resolvedAgentOptions = Symbol(\"resolvedAgentOptions\");\n\ntype InternalAgentOptions<\n Output,\n M extends CompletionModel,\n ContextDocument,\n> = ResolvedAgentOptions<Output, M, ContextDocument> & {\n [resolvedAgentOptions]: true;\n};\n\nexport function resolveAgentOptions<Output, M extends CompletionModel, ContextDocument>(\n options: AgentOptions<Output, M, ContextDocument>,\n): ResolvedAgentOptions<Output, M, ContextDocument> {\n if (isInternalAgentOptions(options)) {\n return options as unknown as ResolvedAgentOptions<Output, M, ContextDocument>;\n }\n\n const toolsByName = new Map<string, AnyTool>();\n const providerTools: ProviderTool[] = [];\n const toolIndexes: ToolIndex[] = [];\n for (const tool of options.tools ?? []) {\n if (isProviderTool(tool)) {\n providerTools.push(tool);\n } else if (isToolIndex(tool)) {\n toolIndexes.push(tool);\n } else if ((tool as { kind?: unknown }).kind === \"tool-index\") {\n throw new TypeError(\"Invalid tool index: search, tools, and a numeric topK are required.\");\n } else if (isMcpTool(tool)) {\n throw new TypeError(\n `MCP tool \"${tool.name}\" must be registered through Agent.mcpServers, not Agent.tools.`,\n );\n } else {\n addUniqueTool(toolsByName, tool, \"local tool\");\n }\n }\n if (options.skills !== undefined) {\n for (const tool of options.skills.tools) {\n if (isMcpTool(tool)) {\n throw new TypeError(\n `MCP tool \"${tool.name}\" must be registered through Agent.mcpServers, not Agent.skills.`,\n );\n }\n addUniqueTool(toolsByName, tool, \"skill tool\");\n }\n }\n const memory = resolveAgentMemory(options);\n const instructions = [options.instructions, options.skills?.instructions]\n .filter((part): part is string => part !== undefined && part.length > 0)\n .join(\"\\n\\n\");\n\n return {\n id: options.id,\n name: options.name,\n description: options.description,\n model: options.model,\n instructions: instructions.length === 0 ? undefined : instructions,\n context: [...(options.context ?? [])],\n temperature: options.temperature,\n maxTokens: options.maxTokens,\n providerOptions: options.providerOptions,\n retries: options.retries,\n tools: [...toolsByName.values()],\n mcpServers: [...(options.mcpServers ?? [])],\n providerTools,\n toolIndexes,\n toolChoice: options.toolChoice,\n defaultMaxTurns: options.maxTurns,\n lifecycle: options.lifecycle,\n outputSchema: options.outputSchema,\n observability: options.observability,\n guardrails:\n options.guardrails === undefined ? [] : appendGuardrailPolicies([], options.guardrails),\n middlewares: [...(options.middlewares ?? [])],\n memory,\n };\n}\n\nexport function markResolvedAgentOptions<Output, M extends CompletionModel, ContextDocument>(\n options: ResolvedAgentOptions<Output, M, ContextDocument>,\n): AgentOptions<Output, M, ContextDocument> {\n return {\n ...options,\n [resolvedAgentOptions]: true,\n } as unknown as AgentOptions<Output, M, ContextDocument>;\n}\n\nfunction isInternalAgentOptions<Output, M extends CompletionModel, ContextDocument>(\n options: AgentOptions<Output, M, ContextDocument>,\n): boolean {\n return (\n (options as unknown as Partial<InternalAgentOptions<Output, M, ContextDocument>>)[\n resolvedAgentOptions\n ] === true\n );\n}\n\nfunction resolveAgentMemory<Output, M extends CompletionModel, ContextDocument>(\n options: AgentOptions<Output, M, ContextDocument>,\n): AgentMemory | undefined {\n if (options.memory === undefined) {\n return undefined;\n }\n const { store, ...memoryOptions } = options.memory;\n const resolvedOptions = resolveMemoryOptions(memoryOptions);\n if (resolvedOptions.compaction !== undefined && store.compaction === undefined) {\n throw new TypeError(\n \"Memory compaction requires a store with the optional compaction capability.\",\n );\n }\n return { store, ...resolvedOptions };\n}\n\nfunction addUniqueTool(tools: Map<string, AnyTool>, tool: AnyTool, source: string): void {\n if (tools.has(tool.name)) {\n throw new TypeError(`Duplicate ${source} name \"${tool.name}\".`);\n }\n tools.set(tool.name, tool);\n}\n","import type { GuardrailPolicy } from \"../guardrails\";\nimport { assertFiniteMinScore, assertPositiveSearchLimit } from \"../internal/vector-search-options\";\nimport type { AgentObservabilityOptions, AgentObserverMap } from \"../observability\";\nimport type { VectorSearchResult } from \"../vector-store\";\nimport type { AgentContextInput, AgentMemory } from \"./types\";\nimport {\n isVectorContext,\n type VectorContext,\n type VectorContextBaseOptions,\n} from \"./vector-context\";\n\nexport function snapshotAgentContext<T>(\n inputs: readonly AgentContextInput<T>[] | undefined,\n): readonly AgentContextInput<T>[] {\n const context = (inputs ?? []).map(snapshotContextInput);\n for (const input of context) {\n if (!isVectorContext(input)) continue;\n assertPositiveSearchLimit(input.topK);\n assertFiniteMinScore(input.minScore);\n }\n return Object.freeze(context);\n}\n\nexport function snapshotAgentObservability(\n observability: AgentObservabilityOptions | undefined,\n): AgentObservabilityOptions | undefined {\n if (observability === undefined) return undefined;\n const observers: Record<string, AgentObserverMap[string]> = {};\n for (const [name, observer] of Object.entries(observability.observers)) {\n if (name.trim().length === 0) {\n throw new TypeError(\"Agent observer names must not be empty.\");\n }\n if (\n typeof observer !== \"object\" ||\n observer === null ||\n typeof observer.startRun !== \"function\"\n ) {\n throw new TypeError(`Agent observer \"${name}\" must implement startRun().`);\n }\n observers[name] = observer;\n }\n if (observability.primaryTrace !== undefined && !(observability.primaryTrace in observers)) {\n throw new TypeError(\n `Agent primaryTrace \"${observability.primaryTrace}\" must name a configured observer.`,\n );\n }\n const errorPolicy = observability.errorPolicy ?? \"ignore\";\n if (errorPolicy !== \"ignore\" && errorPolicy !== \"throw\") {\n throw new TypeError('Agent observability.errorPolicy must be \"ignore\" or \"throw\".');\n }\n let snapshot: AgentObservabilityOptions = {\n observers: Object.freeze(observers),\n errorPolicy,\n };\n if (observability.primaryTrace !== undefined) {\n snapshot = { ...snapshot, primaryTrace: observability.primaryTrace };\n }\n return Object.freeze(snapshot);\n}\n\nexport function snapshotGuardrailPolicies(\n policies: readonly GuardrailPolicy[] | undefined,\n): readonly GuardrailPolicy[] {\n return Object.freeze((policies ?? []).map(snapshotGuardrailPolicy));\n}\n\nexport function snapshotAgentMemory(memory: AgentMemory | undefined): AgentMemory | undefined {\n if (memory === undefined) {\n return undefined;\n }\n const compaction =\n memory.compaction === undefined\n ? undefined\n : Object.freeze({\n ...memory.compaction,\n trigger: Object.freeze({ ...memory.compaction.trigger }),\n retention: Object.freeze({ ...memory.compaction.retention }),\n conflictRetries:\n memory.compaction.conflictRetries === false\n ? false\n : Object.freeze({ ...memory.compaction.conflictRetries }),\n });\n let snapshot: AgentMemory = {\n store: memory.store,\n savePolicy: memory.savePolicy,\n };\n if (compaction !== undefined) {\n snapshot = { ...snapshot, compaction };\n }\n return Object.freeze(snapshot);\n}\n\nexport function cloneFrozenPlainData<T>(value: T): T {\n if (Array.isArray(value)) {\n return Object.freeze(value.map(cloneFrozenPlainData)) as T;\n }\n if (typeof value !== \"object\" || value === null) {\n return value;\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n return value;\n }\n const clone = Object.fromEntries(\n Object.entries(value).map(([key, item]) => [key, cloneFrozenPlainData(item)]),\n );\n return Object.freeze(clone) as T;\n}\n\nfunction snapshotContextInput<T>(input: AgentContextInput<T>): AgentContextInput<T> {\n if (!isVectorContext(input)) {\n let document: AgentContextInput<T> = {\n id: input.id,\n text: input.text,\n };\n if (input.additionalProps !== undefined) {\n document = {\n ...document,\n additionalProps: cloneFrozenPlainData(input.additionalProps),\n };\n }\n return Object.freeze(document);\n }\n const format = input.format;\n let shared: VectorContextBaseOptions<T> & {\n kind: \"vector-context\";\n store: VectorContext<T>[\"store\"];\n } = {\n kind: \"vector-context\" as const,\n store: input.store,\n topK: input.topK,\n };\n if (input.minScore !== undefined) {\n shared = { ...shared, minScore: input.minScore };\n }\n if (input.filter !== undefined) {\n shared = { ...shared, filter: cloneFrozenPlainData(input.filter) };\n }\n if (input.retries !== undefined) {\n shared = { ...shared, retries: cloneFrozenPlainData(input.retries) };\n }\n if (format !== undefined) {\n shared = {\n ...shared,\n format: (result: VectorSearchResult<T>) => format.call(input, result),\n };\n }\n if (!(\"models\" in input) || input.models === undefined) {\n return Object.freeze<VectorContext<T>>({ ...shared, store: input.store, model: input.model });\n }\n let context: VectorContext<T> = {\n ...shared,\n store: input.store,\n models: input.models,\n };\n if (input.fusion !== undefined) {\n context = { ...context, fusion: input.fusion };\n }\n return Object.freeze(context);\n}\n\nfunction snapshotGuardrailPolicy(policy: GuardrailPolicy): GuardrailPolicy {\n return Object.freeze({\n ...policy,\n input: Object.freeze([...policy.input]),\n output: Object.freeze([...policy.output]),\n }) as GuardrailPolicy;\n}\n","import type { JsonValue, ProviderTool } from \"../completion\";\nimport { assertFiniteMinScore, assertPositiveSearchLimit } from \"../internal/vector-search-options\";\nimport { isMcpTool, type McpServer } from \"../mcp\";\nimport { isToolIndex, type ToolIndex } from \"../tool/dynamic-tools\";\nimport type { AnyTool, ToolCallContext } from \"../tool/tool\";\nimport type { VectorInspectRequest } from \"../vector-store\";\nimport { cloneFrozenPlainData } from \"./snapshot\";\nimport type { AgentToolState } from \"./tool-state\";\nimport type { ResolvedAgentOptions } from \"./types\";\n\nexport type PreparedAgentTools = {\n mcpServers: readonly McpServer[];\n tools: readonly AnyTool[];\n publicState: AgentToolState;\n toolsByName: Map<string, AnyTool>;\n};\n\nexport function prepareAgentTools(\n options: Pick<ResolvedAgentOptions, \"tools\" | \"mcpServers\" | \"providerTools\" | \"toolIndexes\">,\n): PreparedAgentTools {\n assertUniqueMcpServerNames(options.mcpServers ?? []);\n const mcpServers = Object.freeze((options.mcpServers ?? []).map(snapshotMcpServer));\n const configuredTools = [...(options.tools ?? [])];\n const staticTools = [...configuredTools, ...mcpServers.flatMap((server) => server.tools)];\n const toolIndexes = (options.toolIndexes ?? []).map(snapshotToolIndex);\n const providerTools = (options.providerTools ?? []).map(snapshotProviderTool);\n assertUniqueAgentToolNames({ staticTools, providerTools, toolIndexes });\n\n const toolsByName = new Map(staticTools.map((tool) => [tool.name, tool]));\n for (const index of toolIndexes) {\n for (const tool of index.tools) {\n toolsByName.set(tool.name, tool);\n }\n }\n const tools = Object.freeze([...toolsByName.values()]);\n const publicState = Object.freeze({\n configuredTools: Object.freeze(configuredTools),\n staticTools: Object.freeze(staticTools),\n providerTools: Object.freeze(providerTools),\n toolIndexes: Object.freeze(toolIndexes),\n });\n return { mcpServers, tools, publicState, toolsByName };\n}\n\nfunction assertUniqueAgentToolNames(options: {\n staticTools: readonly AnyTool[];\n providerTools: readonly ProviderTool[];\n toolIndexes: readonly ToolIndex[];\n}): void {\n const owners = new Map<string, string>();\n for (const tool of options.staticTools) {\n registerToolOwner(owners, tool.name, isMcpTool(tool) ? \"MCP tool\" : \"local or skill tool\");\n }\n for (const tool of options.providerTools) {\n registerToolOwner(owners, tool.name, \"provider tool\");\n }\n for (const [indexPosition, index] of options.toolIndexes.entries()) {\n if (!isToolIndex(index)) {\n throw new TypeError(\"Invalid tool index: search, tools, and a numeric topK are required.\");\n }\n assertPositiveSearchLimit(index.topK);\n assertFiniteMinScore(index.minScore);\n for (const tool of index.tools) {\n if (isMcpTool(tool)) {\n throw new TypeError(\n `MCP tool \"${tool.name}\" must be registered through Agent.mcpServers, not a tool index.`,\n );\n }\n registerToolOwner(owners, tool.name, `tool index ${indexPosition + 1}`);\n }\n }\n}\n\nfunction registerToolOwner(owners: Map<string, string>, name: string, owner: string): void {\n const existing = owners.get(name);\n if (existing !== undefined) {\n throw new TypeError(\n `Tool name collision for \"${name}\" between ${existing} and ${owner}. Tool names must be unique across every Agent tool source.`,\n );\n }\n owners.set(name, owner);\n}\n\nfunction snapshotProviderTool(tool: ProviderTool): ProviderTool {\n let snapshot: ProviderTool = {\n ...tool,\n };\n if (tool.configuration !== undefined) {\n snapshot = { ...snapshot, configuration: cloneFrozenPlainData(tool.configuration) };\n }\n return Object.freeze(snapshot);\n}\n\nfunction snapshotMcpServer(server: McpServer): McpServer {\n if (server.name.trim() === \"\") {\n throw new TypeError(\"MCP server name must not be empty.\");\n }\n for (const tool of server.tools) {\n if (!isMcpTool(tool)) {\n throw new TypeError(`MCP server \"${server.name}\" contains an invalid MCP tool.`);\n }\n if (tool.mcp.serverName !== server.name) {\n throw new TypeError(\n `MCP tool \"${tool.name}\" belongs to server \"${tool.mcp.serverName}\", not \"${server.name}\".`,\n );\n }\n }\n const tools = server.tools.map(snapshotMcpTool);\n let snapshot: McpServer = {\n name: server.name,\n tools: Object.freeze(tools),\n };\n if (server.serverInfo !== undefined) {\n snapshot = { ...snapshot, serverInfo: cloneFrozenPlainData(server.serverInfo) };\n }\n if (server.capabilities !== undefined) {\n snapshot = { ...snapshot, capabilities: cloneFrozenPlainData(server.capabilities) };\n }\n if (server.instructions !== undefined) {\n snapshot = { ...snapshot, instructions: server.instructions };\n }\n return Object.freeze(snapshot);\n}\n\nfunction snapshotMcpTool(tool: McpServer[\"tools\"][number]): McpServer[\"tools\"][number] {\n if (Object.isFrozen(tool) && Object.isFrozen(tool.mcp)) {\n return tool;\n }\n const parseInput = tool.parseInput;\n let snapshot: McpServer[\"tools\"][number] = {\n name: tool.name,\n mcp: Object.freeze({ ...tool.mcp }),\n definition: (prompt: string) => tool.definition(prompt),\n call: (args: unknown, context?: ToolCallContext) => tool.call(args, context),\n };\n if (tool.requiresApproval !== undefined) {\n snapshot = { ...snapshot, requiresApproval: tool.requiresApproval };\n }\n if (parseInput !== undefined) {\n snapshot = {\n ...snapshot,\n parseInput: (args: JsonValue) => parseInput.call(tool, args),\n };\n }\n return Object.freeze(snapshot);\n}\n\nfunction assertUniqueMcpServerNames(servers: readonly McpServer[]): void {\n const names = new Set<string>();\n for (const server of servers) {\n if (names.has(server.name)) {\n throw new TypeError(`Duplicate MCP server name \"${server.name}\".`);\n }\n names.add(server.name);\n }\n}\n\nfunction snapshotToolIndex(index: ToolIndex): ToolIndex {\n const inspect = index.inspect;\n let snapshot: ToolIndex = {\n kind: \"tool-index\" as const,\n tools: Object.freeze([...index.tools]),\n topK: index.topK,\n search: (options: { query: string; abortSignal?: AbortSignal | undefined }) =>\n index.search(options),\n };\n if (index.minScore !== undefined) {\n snapshot = { ...snapshot, minScore: index.minScore };\n }\n if (index.filter !== undefined) {\n snapshot = { ...snapshot, filter: cloneFrozenPlainData(index.filter) };\n }\n if (inspect !== undefined) {\n snapshot = {\n ...snapshot,\n inspect: (request: VectorInspectRequest) => inspect.call(index, request),\n };\n }\n return Object.freeze(snapshot);\n}\n","import { isStreamingCompletionModel } from \"../completion/generate-completion\";\nimport type { CompletionModel, JsonObject, ToolChoice } from \"../completion/index\";\nimport type { GuardrailPolicy } from \"../guardrails\";\nimport { AgentRun } from \"../internal/agent-runtime/agent-run\";\nimport { prepareToolCall } from \"../internal/agent-runtime/prepared-tool-call\";\nimport { assertNonnegativeSafeInteger } from \"../internal/agent-runtime/run-validation\";\nimport type { McpServer } from \"../mcp\";\nimport type { AgentObservabilityOptions } from \"../observability\";\nimport type { RetrySetting } from \"../retry\";\nimport type { ZodSchema } from \"../schema/zod-schema\";\nimport { ToolNotFoundError } from \"../tool/errors\";\nimport type { AgentMiddleware } from \"../tool/middleware\";\nimport type { AnyTool, NormalizedToolOutput, Tool, ToolCallContext } from \"../tool/tool\";\nimport { createAgentStream } from \"./agent-stream\";\nimport { createAgentTool } from \"./agent-tool\";\nimport { normalizeAgentId } from \"./ids\";\nimport type { AgentLifecycle } from \"./lifecycle\";\nimport { registerAgentProviderOutputSchema } from \"./output-schema\";\nimport { resolveAgentOptions } from \"./resolve-options\";\nimport type { AgentResult, AgentRunOptions, AgentStream, AgentStreamEvent } from \"./run-types\";\nimport {\n cloneFrozenPlainData,\n snapshotAgentContext,\n snapshotAgentMemory,\n snapshotAgentObservability,\n snapshotGuardrailPolicies,\n} from \"./snapshot\";\nimport { prepareAgentTools } from \"./tool-catalog\";\nimport { getRegisteredAgentTool, registerAgentToolState } from \"./tool-state\";\nimport type { AgentContextInput, AgentMemory, AgentOptions, AgentToolOptions } from \"./types\";\n\nconst DEFAULT_MAX_TURNS = 20;\n\ntype RawResponseOf<Model> =\n Model extends CompletionModel<infer RawResponse> ? RawResponse : unknown;\n\nexport class Agent<\n Output = string,\n M extends CompletionModel = CompletionModel,\n ContextDocument = unknown,\n> {\n readonly id: string;\n readonly name: string | undefined;\n readonly description: string | undefined;\n readonly model: M;\n readonly instructions: string | undefined;\n readonly context: readonly AgentContextInput<ContextDocument>[];\n readonly temperature: number | undefined;\n readonly maxTokens: number | undefined;\n readonly providerOptions: JsonObject | undefined;\n readonly retries: RetrySetting | undefined;\n readonly mcpServers: readonly McpServer[];\n readonly tools: readonly AnyTool[];\n readonly toolChoice: ToolChoice | undefined;\n readonly defaultMaxTurns: number | undefined;\n readonly lifecycle: AgentLifecycle<Output, RawResponseOf<M>> | undefined;\n readonly outputSchema: ZodSchema<Output> | undefined;\n readonly observability: AgentObservabilityOptions | undefined;\n readonly guardrails: readonly GuardrailPolicy[];\n readonly middlewares: readonly AgentMiddleware[];\n readonly memory: AgentMemory | undefined;\n\n constructor(options: AgentOptions<Output, M, ContextDocument>) {\n const resolved = resolveAgentOptions(options);\n this.id = normalizeAgentId(resolved.id);\n this.name = resolved.name;\n this.description = resolved.description;\n this.model = resolved.model;\n this.instructions = resolved.instructions;\n this.context = snapshotAgentContext(resolved.context);\n this.temperature = resolved.temperature;\n this.maxTokens = resolved.maxTokens;\n this.providerOptions = cloneFrozenPlainData(resolved.providerOptions);\n this.retries = cloneFrozenPlainData(resolved.retries);\n\n const preparedTools = prepareAgentTools(resolved);\n this.mcpServers = preparedTools.mcpServers;\n this.tools = preparedTools.tools;\n registerAgentToolState(this, preparedTools.publicState, preparedTools.toolsByName);\n\n this.toolChoice = cloneFrozenPlainData(resolved.toolChoice);\n this.defaultMaxTurns = assertNonnegativeSafeInteger(\n resolved.defaultMaxTurns ?? DEFAULT_MAX_TURNS,\n \"maxTurns\",\n );\n this.lifecycle = resolved.lifecycle;\n this.outputSchema = resolved.outputSchema;\n registerAgentProviderOutputSchema(this, resolved.outputSchema);\n this.observability = snapshotAgentObservability(resolved.observability);\n this.guardrails = snapshotGuardrailPolicies(resolved.guardrails);\n this.middlewares = Object.freeze([...(resolved.middlewares ?? [])]);\n this.memory = snapshotAgentMemory(resolved.memory);\n }\n\n generate(options: AgentRunOptions<Output, RawResponseOf<M>>): Promise<AgentResult<Output>> {\n return AgentRun.fromAgent(this, options).generate();\n }\n\n stream(\n options: AgentRunOptions<Output, RawResponseOf<M>>,\n ): AgentStream<AgentStreamEvent<Output, RawResponseOf<M>>> {\n const run = AgentRun.fromAgent(this, options);\n if (!this.model.capabilities.streaming || !isStreamingCompletionModel(this.model)) {\n throw new Error(\"This completion model does not support streaming\");\n }\n return createAgentStream(run);\n }\n\n asTool(options: AgentToolOptions): Tool<{ prompt: string }, Output> {\n return createAgentTool(this, options);\n }\n\n getTool(toolName: string): AnyTool | undefined {\n return getRegisteredAgentTool(this, toolName);\n }\n\n async callTool(\n toolName: string,\n args: string,\n context?: ToolCallContext,\n ): Promise<NormalizedToolOutput> {\n const tool = this.getTool(toolName);\n if (tool === undefined) {\n throw new ToolNotFoundError(toolName);\n }\n return prepareToolCall(tool, args).call(context ?? {});\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS;AAgElB,IAAM,WAAW,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC;AACxC,IAAM,kBAAkB,EAAE,OAAkB,aAAa;AAAA,EACvD,SAAS;AACX,CAAC;AACD,IAAM,mBAAmB,EAAE;AAAA,EACzB,CAAC,UACC,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,KAAK,YAAY,KAAK;AAAA,EAC3F,EAAE,SAAS,gCAAgC;AAC7C;AAEA,IAAM,uBAAuB,EAC1B,OAAO;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AACT,CAAC,EACA,OAAO;AAEV,IAAM,uBAAuB,EAC1B,OAAO;AAA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