@anvia/core 1.0.0 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/agent/index.d.ts +3 -3
- package/dist/agent/index.js +8 -8
- package/dist/{agent-qRKa3ibC.d.ts → agent-DYfzP-n5.d.ts} +1 -1
- package/dist/{chunk-6BBOCFHV.js → chunk-AR2K73CJ.js} +3 -2
- package/dist/chunk-AR2K73CJ.js.map +1 -0
- package/dist/{chunk-LTXABCOO.js → chunk-DHJL44R2.js} +2 -2
- package/dist/{chunk-SJMSS5SI.js → chunk-EO2GECYH.js} +3 -3
- package/dist/{chunk-3SKZ2BKP.js → chunk-IWJK7JB5.js} +2 -2
- package/dist/{chunk-3RM57ZT2.js → chunk-IZNOP6JG.js} +2 -2
- package/dist/chunk-IZNOP6JG.js.map +1 -0
- package/dist/{chunk-ZA564323.js → chunk-K5L7R7XM.js} +2 -2
- package/dist/{chunk-3ZLM6OAZ.js → chunk-PH6OTIPZ.js} +11 -9
- package/dist/chunk-PH6OTIPZ.js.map +1 -0
- package/dist/{chunk-7PHMK7W4.js → chunk-TB5EKZM7.js} +1 -1
- package/dist/chunk-TB5EKZM7.js.map +1 -0
- package/dist/{chunk-YA7BMX7D.js → chunk-XMVOBX43.js} +2 -2
- package/dist/{chunk-EMZKPRE6.js → chunk-YFJ4NHV6.js} +2 -2
- package/dist/chunk-YFJ4NHV6.js.map +1 -0
- package/dist/completion/index.js +1 -1
- package/dist/embeddings/index.js +2 -2
- package/dist/evals/index.d.ts +1 -1
- package/dist/evals/index.js +5 -5
- package/dist/evals/index.js.map +1 -1
- package/dist/extractor/index.js +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +9 -9
- package/dist/internal/agent.d.ts +2 -2
- package/dist/internal/agent.js +8 -8
- package/dist/memory/index.js +2 -2
- package/dist/observability/index.d.ts +1 -1
- package/dist/observability/index.js +2 -2
- package/dist/pipeline/index.d.ts +2 -2
- package/dist/pipeline/index.js +3 -3
- package/dist/skills/index.js +5 -5
- package/dist/tool/index.js +4 -4
- package/dist/{types-CLCLFpAL.d.ts → types-BUEZMBhO.d.ts} +1 -0
- package/dist/vector-store/index.js +3 -3
- package/package.json +1 -1
- package/dist/chunk-3RM57ZT2.js.map +0 -1
- package/dist/chunk-3ZLM6OAZ.js.map +0 -1
- package/dist/chunk-6BBOCFHV.js.map +0 -1
- package/dist/chunk-7PHMK7W4.js.map +0 -1
- package/dist/chunk-EMZKPRE6.js.map +0 -1
- /package/dist/{chunk-LTXABCOO.js.map → chunk-DHJL44R2.js.map} +0 -0
- /package/dist/{chunk-SJMSS5SI.js.map → chunk-EO2GECYH.js.map} +0 -0
- /package/dist/{chunk-3SKZ2BKP.js.map → chunk-IWJK7JB5.js.map} +0 -0
- /package/dist/{chunk-ZA564323.js.map → chunk-K5L7R7XM.js.map} +0 -0
- /package/dist/{chunk-YA7BMX7D.js.map → chunk-XMVOBX43.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/observability/snapshot.ts","../src/observability/group.ts"],"sourcesContent":["export function observerSnapshot<T>(value: T): T {\n if (containsError(value, new WeakSet<object>())) {\n return cloneObserverFallback(value, new WeakMap<object, object>());\n }\n try {\n return globalThis.structuredClone(value);\n } catch {\n return cloneObserverFallback(value, new WeakMap<object, object>());\n }\n}\n\nfunction cloneObserverFallback<T>(value: T, seen: WeakMap<object, object>): T {\n if (typeof value !== \"object\" || value === null) {\n return value;\n }\n const existing = seen.get(value);\n if (existing !== undefined) {\n return existing as T;\n }\n if (Array.isArray(value)) {\n const clone: unknown[] = [];\n seen.set(value, clone);\n clone.push(...value.map((item) => cloneObserverFallback(item, seen)));\n return clone as T;\n }\n if (value instanceof Date) {\n return new Date(value.getTime()) as T;\n }\n if (value instanceof Error) {\n const clone = Object.create(Object.getPrototypeOf(value)) as Error;\n seen.set(value, clone);\n Object.defineProperties(clone, {\n name: { configurable: true, writable: true, value: value.name },\n message: { configurable: true, writable: true, value: value.message },\n });\n if (value.stack !== undefined) {\n Object.defineProperty(clone, \"stack\", {\n configurable: true,\n writable: true,\n value: value.stack,\n });\n }\n if (value.cause !== undefined) {\n Object.defineProperty(clone, \"cause\", {\n configurable: true,\n writable: true,\n value: cloneObserverFallback(value.cause, seen),\n });\n }\n for (const key of Object.getOwnPropertyNames(value)) {\n if (key === \"name\" || key === \"message\" || key === \"stack\" || key === \"cause\") continue;\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined) continue;\n if (\"value\" in descriptor) {\n descriptor.value = cloneObserverFallback(descriptor.value, seen);\n }\n Object.defineProperty(clone, key, descriptor);\n }\n return clone as T;\n }\n if (Object.getPrototypeOf(value) !== Object.prototype) {\n return value;\n }\n const clone: Record<string, unknown> = {};\n seen.set(value, clone);\n for (const [key, item] of Object.entries(value)) {\n clone[key] = cloneObserverFallback(item, seen);\n }\n return clone as T;\n}\n\nfunction containsError(value: unknown, seen: WeakSet<object>): boolean {\n if (typeof value !== \"object\" || value === null) return false;\n if (value instanceof Error) return true;\n if (seen.has(value)) return false;\n seen.add(value);\n if (Array.isArray(value)) {\n return value.some((item) => containsError(item, seen));\n }\n if (Object.getPrototypeOf(value) !== Object.prototype) return false;\n return Object.values(value).some((item) => containsError(item, seen));\n}\n","import { Usage } from \"../completion\";\nimport { observerSnapshot } from \"./snapshot\";\nimport type {\n AgentGenerationEndArgs,\n AgentGenerationErrorArgs,\n AgentGenerationObserver,\n AgentGenerationStartArgs,\n AgentGenerationUpdateArgs,\n AgentObserverErrorPolicy,\n AgentObserverMap,\n AgentRunEndArgs,\n AgentRunErrorArgs,\n AgentRunEventArgs,\n AgentRunObserver,\n AgentRunStartArgs,\n AgentToolEndArgs,\n AgentToolErrorArgs,\n AgentToolObserver,\n AgentToolStartArgs,\n AgentToolStreamEventArgs,\n AgentToolSuspendedArgs,\n AgentTraceInfo,\n} from \"./types\";\n\nexport type AgentObserverFailure = {\n readonly observer: string;\n readonly error: unknown;\n};\n\nexport class AgentObserverDispatchError extends AggregateError {\n readonly phase: string;\n readonly failures: readonly AgentObserverFailure[];\n\n constructor(phase: string, failures: readonly AgentObserverFailure[]) {\n super(\n failures.map((failure) => failure.error),\n `Agent observer ${phase} failed for ${failures.map((failure) => failure.observer).join(\", \")}.`,\n );\n this.name = \"AgentObserverDispatchError\";\n this.phase = phase;\n this.failures = Object.freeze([...failures]);\n }\n}\n\ntype NamedObserver<T> = {\n readonly name: string;\n readonly observer: T;\n};\n\ntype ActiveNamedObserver<T> = NamedObserver<T> & {\n terminal: boolean;\n};\n\nexport async function startAgentRunObservers(\n observers: AgentObserverMap,\n args: AgentRunStartArgs,\n options: {\n readonly primaryTrace?: string | undefined;\n readonly errorPolicy: AgentObserverErrorPolicy;\n },\n): Promise<ActiveAgentRunObservers> {\n const runObservers: ActiveNamedObserver<AgentRunObserver>[] = [];\n const failures: AgentObserverFailure[] = [];\n for (const [name, observer] of Object.entries(observers)) {\n try {\n const runObserver = await observer.startRun(observerSnapshot(args));\n if (runObserver !== undefined) {\n runObservers.push({ name, observer: runObserver, terminal: false });\n }\n } catch (error) {\n failures.push({ observer: name, error });\n }\n }\n if (options.errorPolicy === \"throw\" && failures.length > 0) {\n const startupError = new AgentObserverDispatchError(\"startRun\", failures);\n const cleanupFailures = await terminateObservers(runObservers, (observer) =>\n observer.error?.(\n observerSnapshot({\n error: startupError,\n usage: Usage.empty(),\n messages: [...args.history, args.prompt],\n }),\n ),\n );\n throw new AgentObserverDispatchError(\"startRun\", [...failures, ...cleanupFailures]);\n }\n return new ActiveAgentRunObservers(runObservers, options);\n}\n\nexport class ActiveAgentRunObservers {\n readonly trace: AgentTraceInfo | undefined;\n\n constructor(\n private readonly runObservers: readonly ActiveNamedObserver<AgentRunObserver>[],\n private readonly options: {\n readonly primaryTrace?: string | undefined;\n readonly errorPolicy: AgentObserverErrorPolicy;\n },\n ) {\n const primary =\n options.primaryTrace === undefined\n ? undefined\n : runObservers.find((entry) => entry.name === options.primaryTrace);\n this.trace =\n primary?.observer.trace === undefined\n ? undefined\n : Object.freeze({ observer: primary.name, ...primary.observer.trace });\n }\n\n async startGeneration(args: AgentGenerationStartArgs): Promise<ActiveGenerationObservers> {\n const generationObservers: ActiveNamedObserver<AgentGenerationObserver>[] = [];\n const failures: AgentObserverFailure[] = [];\n for (const entry of this.runObservers) {\n if (entry.observer.startGeneration === undefined) continue;\n try {\n const observer = await entry.observer.startGeneration(observerSnapshot(args));\n if (observer !== undefined) {\n generationObservers.push({ name: entry.name, observer, terminal: false });\n }\n } catch (error) {\n failures.push({ observer: entry.name, error });\n }\n }\n if (this.options.errorPolicy === \"throw\" && failures.length > 0) {\n const startupError = new AgentObserverDispatchError(\"startGeneration\", failures);\n const cleanupFailures = await terminateObservers(generationObservers, (observer) =>\n observer.error?.(observerSnapshot({ turn: args.turn, error: startupError })),\n );\n throw new AgentObserverDispatchError(\"startGeneration\", [...failures, ...cleanupFailures]);\n }\n return new ActiveGenerationObservers(generationObservers, this.options.errorPolicy);\n }\n\n async startTool(args: AgentToolStartArgs): Promise<ActiveToolObservers> {\n const toolObservers: ActiveNamedObserver<AgentToolObserver>[] = [];\n const failures: AgentObserverFailure[] = [];\n for (const entry of this.runObservers) {\n if (entry.observer.startTool === undefined) continue;\n try {\n const observer = await entry.observer.startTool(observerSnapshot(args));\n if (observer !== undefined) {\n toolObservers.push({ name: entry.name, observer, terminal: false });\n }\n } catch (error) {\n failures.push({ observer: entry.name, error });\n }\n }\n if (this.options.errorPolicy === \"throw\" && failures.length > 0) {\n const startupError = new AgentObserverDispatchError(\"startTool\", failures);\n const cleanupFailures = await terminateObservers(toolObservers, (observer) =>\n observer.error?.(observerSnapshot({ ...args, error: startupError })),\n );\n throw new AgentObserverDispatchError(\"startTool\", [...failures, ...cleanupFailures]);\n }\n return new ActiveToolObservers(toolObservers, this.options.errorPolicy);\n }\n\n async end(args: AgentRunEndArgs): Promise<void> {\n await dispatchTerminalObservers(\n this.runObservers,\n \"end\",\n (observer) => observer.end(observerSnapshot(args)),\n this.options.errorPolicy,\n );\n }\n\n async error(args: AgentRunErrorArgs): Promise<void> {\n await dispatchTerminalObservers(\n this.runObservers,\n \"error\",\n (observer) => observer.error?.(observerSnapshot(args)),\n \"ignore\",\n );\n }\n\n async event(args: AgentRunEventArgs): Promise<void> {\n await dispatchObservers(\n this.runObservers,\n \"event\",\n (observer) => observer.event?.(observerSnapshot(args)),\n this.options.errorPolicy,\n );\n }\n}\n\nexport class ActiveGenerationObservers {\n constructor(\n private readonly observers: readonly ActiveNamedObserver<AgentGenerationObserver>[],\n private readonly errorPolicy: AgentObserverErrorPolicy,\n ) {}\n\n async end(args: AgentGenerationEndArgs): Promise<void> {\n await dispatchTerminalObservers(\n this.observers,\n \"generation.end\",\n (observer) => observer.end(observerSnapshot(args)),\n this.errorPolicy,\n );\n }\n\n async error(args: AgentGenerationErrorArgs): Promise<void> {\n await dispatchTerminalObservers(\n this.observers,\n \"generation.error\",\n (observer) => observer.error?.(observerSnapshot(args)),\n \"ignore\",\n );\n }\n\n async update(args: AgentGenerationUpdateArgs): Promise<void> {\n await dispatchObservers(\n this.observers,\n \"generation.update\",\n (observer) => observer.update?.(observerSnapshot(args)),\n this.errorPolicy,\n );\n }\n}\n\nexport class ActiveToolObservers {\n constructor(\n private readonly observers: readonly ActiveNamedObserver<AgentToolObserver>[],\n private readonly errorPolicy: AgentObserverErrorPolicy,\n ) {}\n\n async streamEvent(args: AgentToolStreamEventArgs): Promise<void> {\n await dispatchObservers(\n this.observers,\n \"tool.streamEvent\",\n (observer) => observer.streamEvent?.(observerSnapshot(args)),\n this.errorPolicy,\n );\n }\n\n async end(args: AgentToolEndArgs): Promise<void> {\n await dispatchTerminalObservers(\n this.observers,\n \"tool.end\",\n (observer) => observer.end(observerSnapshot(args)),\n this.errorPolicy,\n );\n }\n\n async suspend(args: AgentToolSuspendedArgs): Promise<void> {\n await dispatchTerminalObservers(\n this.observers,\n \"tool.suspend\",\n (observer) => observer.suspend?.(observerSnapshot(args)),\n this.errorPolicy,\n );\n }\n\n async error(args: AgentToolErrorArgs): Promise<void> {\n await dispatchTerminalObservers(\n this.observers,\n \"tool.error\",\n (observer) => observer.error?.(observerSnapshot(args)),\n \"ignore\",\n );\n }\n}\n\nasync function dispatchObservers<T>(\n observers: readonly NamedObserver<T>[],\n phase: string,\n dispatch: (observer: T) => void | Promise<void> | undefined,\n errorPolicy: AgentObserverErrorPolicy,\n): Promise<void> {\n const failures: AgentObserverFailure[] = [];\n for (const entry of observers) {\n try {\n await dispatch(entry.observer);\n } catch (error) {\n failures.push({ observer: entry.name, error });\n }\n }\n throwObserverFailures(phase, failures, errorPolicy);\n}\n\nasync function dispatchTerminalObservers<T>(\n observers: readonly ActiveNamedObserver<T>[],\n phase: string,\n dispatch: (observer: T) => void | Promise<void> | undefined,\n errorPolicy: AgentObserverErrorPolicy,\n): Promise<void> {\n const failures = await terminateObservers(observers, dispatch);\n throwObserverFailures(phase, failures, errorPolicy);\n}\n\nasync function terminateObservers<T>(\n observers: readonly ActiveNamedObserver<T>[],\n dispatch: (observer: T) => void | Promise<void> | undefined,\n): Promise<AgentObserverFailure[]> {\n const failures: AgentObserverFailure[] = [];\n for (const entry of observers) {\n if (entry.terminal) continue;\n entry.terminal = true;\n try {\n await dispatch(entry.observer);\n } catch (error) {\n failures.push({ observer: entry.name, error });\n }\n }\n return failures;\n}\n\nfunction throwObserverFailures(\n phase: string,\n failures: readonly AgentObserverFailure[],\n errorPolicy: AgentObserverErrorPolicy,\n): void {\n if (errorPolicy === \"throw\" && failures.length > 0) {\n throw new AgentObserverDispatchError(phase, failures);\n }\n}\n"],"mappings":";;;;;AAAO,SAAS,iBAAoB,OAAa;AAC/C,MAAI,cAAc,OAAO,oBAAI,QAAgB,CAAC,GAAG;AAC/C,WAAO,sBAAsB,OAAO,oBAAI,QAAwB,CAAC;AAAA,EACnE;AACA,MAAI;AACF,WAAO,WAAW,gBAAgB,KAAK;AAAA,EACzC,Q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AI;AACF,YAAM,SAAS,MAAM,QAAQ;AAAA,IAC/B,SAAS,OAAO;AACd,eAAS,KAAK,EAAE,UAAU,MAAM,MAAM,MAAM,CAAC;AAAA,IAC/C;AAAA,EACF;AACA,wBAAsB,OAAO,UAAU,WAAW;AACpD;AAEA,eAAe,0BACb,WACA,OACA,UACA,aACe;AACf,QAAM,WAAW,MAAM,mBAAmB,WAAW,QAAQ;AAC7D,wBAAsB,OAAO,UAAU,WAAW;AACpD;AAEA,eAAe,mBACb,WACA,UACiC;AACjC,QAAM,WAAmC,CAAC;AAC1C,aAAW,SAAS,WAAW;AAC7B,QAAI,MAAM,SAAU;AACpB,UAAM,WAAW;AACjB,QAAI;AACF,YAAM,SAAS,MAAM,QAAQ;AAAA,IAC/B,SAAS,OAAO;AACd,eAAS,KAAK,EAAE,UAAU,MAAM,MAAM,MAAM,CAAC;AAAA,IAC/C;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,sBACP,OACA,UACA,aACM;AACN,MAAI,gBAAgB,WAAW,SAAS,SAAS,GAAG;AAClD,UAAM,IAAI,2BAA2B,OAAO,QAAQ;AAAA,EACtD;AACF;","names":["clone"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/completion/types.ts","../src/completion/provider-output-error.ts","../src/internal/completion-request.ts","../src/completion/stream-accumulator.ts","../src/completion/generate-completion.ts"],"sourcesContent":["import type { ModelCallOptions } from \"../model-call-options\";\nimport { isJsonValue } from \"./json\";\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonObject | readonly JsonValue[];\nexport type JsonObject = { [key: string]: JsonValue };\n\nexport type Document = {\n id: string;\n text: string;\n additionalProps?: Record<string, string>;\n};\n\nexport type TextPart = Readonly<{\n type: \"text\";\n text: string;\n signature?: string;\n}>;\n\nexport type ImageDetail = \"auto\" | \"low\" | \"high\";\n\nexport type FileData =\n | Readonly<{ type: \"url\"; url: string }>\n | Readonly<{ type: \"data\"; data: string }>\n | Readonly<{ type: \"text\"; text: string }>;\n\nexport type ImagePart = Readonly<{\n type: \"image\";\n image: Exclude<FileData, Readonly<{ type: \"text\"; text: string }>>;\n mediaType?: string;\n detail?: ImageDetail;\n}>;\n\nexport type FilePart = Readonly<{\n type: \"file\";\n data: FileData;\n mediaType: string;\n filename?: string;\n}>;\n\nexport type ReasoningPart = Readonly<{\n type: \"reasoning\";\n text: string;\n id?: string;\n details?: readonly ReasoningDetail[];\n}>;\n\nexport type ReasoningDetail =\n | Readonly<{\n type: \"text\";\n text: string;\n signature?: string;\n }>\n | Readonly<{\n type: \"summary\";\n text: string;\n }>\n | Readonly<{\n type: \"encrypted\";\n data: string;\n }>\n | Readonly<{\n type: \"redacted\";\n data: string;\n }>;\n\nexport type ReasoningContentType = ReasoningDetail[\"type\"];\n\nexport type ToolCallPart = Readonly<{\n type: \"tool-call\";\n toolCallId: string;\n callId?: string;\n toolName: string;\n input: JsonValue;\n signature?: string;\n}>;\n\nexport type ToolResultContentPart = TextPart | FilePart;\n\nexport type ToolResultOutput =\n | Readonly<{ type: \"text\"; value: string }>\n | Readonly<{ type: \"json\"; value: JsonValue }>\n | Readonly<{ type: \"content\"; value: readonly ToolResultContentPart[] }>\n | Readonly<{ type: \"execution-denied\"; reason?: string }>\n | Readonly<{ type: \"error-text\"; value: string }>\n | Readonly<{ type: \"error-json\"; value: JsonValue }>;\n\nexport type ToolResultPart = Readonly<{\n type: \"tool-result\";\n toolCallId: string;\n callId?: string;\n toolName: string;\n output: ToolResultOutput;\n}>;\n\nexport type ToolApprovalResponsePart = Readonly<{\n type: \"tool-approval-response\";\n interactionId: string;\n toolCallId: string;\n callId?: string;\n toolName: string;\n approved: boolean;\n reason?: string;\n}>;\n\nexport type ToolQuestionAnswer = Readonly<{\n questionId: string;\n value: string;\n}>;\n\nexport type ToolQuestionResponsePart = Readonly<{\n type: \"tool-question-response\";\n interactionId: string;\n toolCallId: string;\n callId?: string;\n toolName: string;\n answers: readonly ToolQuestionAnswer[];\n}>;\n\nexport type ToolInteractionResponsePart = ToolApprovalResponsePart | ToolQuestionResponsePart;\n\nexport type UserContentPart = TextPart | ImagePart | FilePart;\nexport type AssistantContentPart = TextPart | ImagePart | FilePart | ReasoningPart | ToolCallPart;\n\nexport type SystemMessage<Metadata extends JsonObject = JsonObject> = Readonly<{\n role: \"system\";\n content: string;\n metadata?: Metadata;\n}>;\n\nexport type UserMessage<Metadata extends JsonObject = JsonObject> = Readonly<{\n role: \"user\";\n content: string | readonly UserContentPart[];\n metadata?: Metadata;\n}>;\n\nexport type AssistantMessage<Metadata extends JsonObject = JsonObject> = Readonly<{\n role: \"assistant\";\n id?: string;\n content: string | readonly AssistantContentPart[];\n metadata?: Metadata;\n}>;\n\nexport type ToolMessage<Metadata extends JsonObject = JsonObject> = Readonly<{\n role: \"tool\";\n content: readonly (ToolResultPart | ToolInteractionResponsePart)[];\n metadata?: Metadata;\n}>;\n\nexport type Message<Metadata extends JsonObject = JsonObject> =\n | SystemMessage<Metadata>\n | UserMessage<Metadata>\n | AssistantMessage<Metadata>\n | ToolMessage<Metadata>;\n\nexport function reasoningDisplayText(\n reasoning: ReasoningPart | readonly ReasoningDetail[],\n): string {\n const details = \"type\" in reasoning ? reasoning.details : reasoning;\n if (details === undefined) {\n return \"type\" in reasoning ? reasoning.text : \"\";\n }\n return details\n .flatMap((item) => {\n if (item.type === \"text\" || item.type === \"summary\") {\n return [item.text];\n }\n return [];\n })\n .join(\"\");\n}\n\nexport type ToolChoice =\n | \"auto\"\n | \"required\"\n | \"none\"\n | {\n type: \"function\";\n name: string;\n };\n\nexport type ToolDefinition = {\n name: string;\n description: string;\n parameters: JsonObject;\n};\n\n/**\n * A tool executed by the model provider rather than by Anvia's local tool runtime.\n *\n * Provider packages expose typed factories for these values. Application code can\n * pass them through the same high-level `tools` APIs used for local tools.\n */\nexport type ProviderTool = {\n kind: \"provider\";\n provider: string;\n name: string;\n configuration?: JsonObject;\n};\n\nexport type CompletionTool = ToolDefinition | ProviderTool;\n\nexport function isProviderTool(value: unknown): value is ProviderTool {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const candidate = value as Partial<ProviderTool>;\n return (\n candidate.kind === \"provider\" &&\n typeof candidate.provider === \"string\" &&\n candidate.provider.trim().length > 0 &&\n typeof candidate.name === \"string\" &&\n candidate.name.trim().length > 0 &&\n (candidate.configuration === undefined ||\n (typeof candidate.configuration === \"object\" &&\n candidate.configuration !== null &&\n !Array.isArray(candidate.configuration) &&\n isJsonValue(candidate.configuration)))\n );\n}\n\nexport type CompletionSource = {\n type: \"url\";\n url: string;\n title?: string;\n id?: string;\n startIndex?: number;\n endIndex?: number;\n};\n\nexport type ProviderToolCall = {\n id: string;\n name: string;\n status?: string;\n details?: JsonObject;\n};\n\n/**\n * Provider-normalized, mutually exclusive usage buckets.\n *\n * Every token should appear in exactly one non-total bucket. `total` is the\n * only aggregate key and should equal the sum of the other buckets.\n */\nexport type UsageDetails = Record<string, number>;\n\nexport type Usage = {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n cachedInputTokens: number;\n cacheCreationInputTokens: number;\n details?: UsageDetails;\n};\n\nexport type ModelContextLimits = {\n contextWindow: number;\n maxInputTokens?: number;\n maxOutputTokens?: number;\n};\n\nexport type CompletionModelInfo = {\n modelId: string;\n context: ModelContextLimits;\n};\n\nexport type ContextUsage = {\n model: CompletionModelInfo;\n usedTokens: number;\n remainingTokens: number;\n usedPercent: number;\n remainingPercent: number;\n};\n\nexport function calculateContextUsage(\n usage: Usage,\n model: CompletionModelInfo | undefined,\n): ContextUsage | undefined {\n if (\n model === undefined ||\n !Number.isFinite(usage.inputTokens) ||\n usage.inputTokens <= 0 ||\n !Number.isFinite(model.context.contextWindow) ||\n model.context.contextWindow <= 0\n ) {\n return undefined;\n }\n\n const usedTokens = Math.max(0, usage.inputTokens);\n const remainingTokens = Math.max(0, model.context.contextWindow - usedTokens);\n const usedPercent = Math.min(100, (usedTokens / model.context.contextWindow) * 100);\n return {\n model,\n usedTokens,\n remainingTokens,\n usedPercent,\n remainingPercent: 100 - usedPercent,\n };\n}\n\nexport function withContextUsage<RawResponse>(\n response: CompletionResponse<RawResponse>,\n model: CompletionModelInfo | undefined,\n): CompletionResponse<RawResponse> {\n const contextUsage = calculateContextUsage(response.usage, model);\n return contextUsage === undefined ? response : { ...response, contextUsage };\n}\n\nexport function resolveModelContextLimits(\n modelId: string,\n catalog: Readonly<Record<string, ModelContextLimits>>,\n override?: ModelContextLimits,\n): ModelContextLimits | undefined {\n return override ?? catalog[modelId];\n}\n\nexport type AssistantGenerationMetadata = {\n provider: string;\n modelId: string;\n usage: Usage;\n finishReason?: CompletionFinishReason;\n providerFinishReason?: string;\n contextUsage?: ContextUsage;\n sources?: CompletionSource[];\n providerToolCalls?: ProviderToolCall[];\n};\n\nexport const Usage = {\n empty(): Usage {\n return {\n inputTokens: 0,\n outputTokens: 0,\n totalTokens: 0,\n cachedInputTokens: 0,\n cacheCreationInputTokens: 0,\n };\n },\n add(left: Usage, right: Usage): Usage {\n const result: Usage = {\n inputTokens: left.inputTokens + right.inputTokens,\n outputTokens: left.outputTokens + right.outputTokens,\n totalTokens: left.totalTokens + right.totalTokens,\n cachedInputTokens: left.cachedInputTokens + right.cachedInputTokens,\n cacheCreationInputTokens: left.cacheCreationInputTokens + right.cacheCreationInputTokens,\n };\n const details = addUsageDetails(left, right);\n if (details !== undefined) {\n result.details = details;\n }\n return result;\n },\n isEmpty(usage: Usage): boolean {\n return (\n isEmptyUsage(usage) &&\n (usage.details === undefined || Object.values(usage.details).every((value) => value === 0))\n );\n },\n};\n\nfunction addUsageDetails(left: Usage, right: Usage): UsageDetails | undefined {\n if (isEmptyUsage(left) && left.details === undefined) {\n return right.details === undefined ? undefined : { ...right.details };\n }\n if (isEmptyUsage(right) && right.details === undefined) {\n return left.details === undefined ? undefined : { ...left.details };\n }\n if (left.details === undefined || right.details === undefined) {\n return undefined;\n }\n const details: UsageDetails = { ...left.details };\n for (const [key, value] of Object.entries(right.details)) {\n details[key] = (details[key] ?? 0) + value;\n }\n return details;\n}\n\nfunction isEmptyUsage(usage: Usage): 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\nexport function getAssistantGenerationMetadata(\n message: Message,\n): AssistantGenerationMetadata | undefined {\n if (message.role !== \"assistant\" || !isJsonObjectValue(message.metadata)) {\n return undefined;\n }\n const frameworkMetadata = message.metadata.anvia;\n if (!isJsonObjectValue(frameworkMetadata)) {\n return undefined;\n }\n const generation = frameworkMetadata.generation;\n if (\n !isJsonObjectValue(generation) ||\n typeof generation.provider !== \"string\" ||\n typeof generation.modelId !== \"string\" ||\n !isUsageValue(generation.usage)\n ) {\n return undefined;\n }\n let usage: Usage = { ...generation.usage };\n if (generation.usage.details !== undefined) {\n usage = { ...usage, details: { ...generation.usage.details } };\n }\n const metadata: AssistantGenerationMetadata = {\n provider: generation.provider,\n modelId: generation.modelId,\n usage,\n };\n if (isCompletionFinishReason(generation.finishReason)) {\n metadata.finishReason = generation.finishReason;\n }\n if (typeof generation.providerFinishReason === \"string\") {\n metadata.providerFinishReason = generation.providerFinishReason;\n }\n if (isContextUsageValue(generation.contextUsage)) {\n metadata.contextUsage = {\n ...generation.contextUsage,\n model: {\n ...generation.contextUsage.model,\n context: { ...generation.contextUsage.model.context },\n },\n };\n }\n if (isCompletionSourceArray(generation.sources)) {\n metadata.sources = generation.sources.map((source) => ({ ...source }));\n }\n if (isProviderToolCallArray(generation.providerToolCalls)) {\n metadata.providerToolCalls = generation.providerToolCalls.map((toolCall) => {\n let copy: ProviderToolCall = { ...toolCall };\n if (toolCall.details !== undefined) {\n copy = { ...copy, details: { ...toolCall.details } };\n }\n return copy;\n });\n }\n return metadata;\n}\n\nfunction isJsonObjectValue(value: JsonValue | undefined): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isContextUsageValue(value: JsonValue | undefined): value is JsonObject & ContextUsage {\n if (!isJsonObjectValue(value) || !isJsonObjectValue(value.model)) {\n return false;\n }\n const context = value.model.context;\n if (\n typeof value.model.modelId === \"string\" &&\n isJsonObjectValue(context) &&\n isPositiveFiniteNumber(context.contextWindow) &&\n isOptionalPositiveFiniteNumber(context.maxInputTokens) &&\n isOptionalPositiveFiniteNumber(context.maxOutputTokens) &&\n isNonnegativeFiniteNumber(value.usedTokens) &&\n isNonnegativeFiniteNumber(value.remainingTokens) &&\n isPercentage(value.usedPercent) &&\n isPercentage(value.remainingPercent)\n ) {\n const contextWindow = context.contextWindow;\n const remainingTokens = Math.max(0, contextWindow - value.usedTokens);\n const usedPercent = Math.min(100, (value.usedTokens / contextWindow) * 100);\n const remainingPercent = (remainingTokens / contextWindow) * 100;\n return (\n value.remainingTokens === remainingTokens &&\n approximatelyEqual(value.usedPercent, usedPercent) &&\n approximatelyEqual(value.remainingPercent, remainingPercent)\n );\n }\n return false;\n}\n\nfunction approximatelyEqual(left: number, right: number): boolean {\n const scale = Math.max(1, Math.abs(left), Math.abs(right));\n return Math.abs(left - right) <= Number.EPSILON * scale * 8;\n}\n\nfunction isPositiveFiniteNumber(value: JsonValue | undefined): value is number {\n return isNonnegativeFiniteNumber(value) && value > 0;\n}\n\nfunction isOptionalPositiveFiniteNumber(value: JsonValue | undefined): boolean {\n return value === undefined || isPositiveFiniteNumber(value);\n}\n\nfunction isPercentage(value: JsonValue | undefined): value is number {\n return isNonnegativeFiniteNumber(value) && value <= 100;\n}\n\nfunction isUsageValue(value: JsonValue | undefined): value is JsonObject & Usage {\n if (!isJsonObjectValue(value)) {\n return false;\n }\n return (\n isNonnegativeFiniteNumber(value.inputTokens) &&\n isNonnegativeFiniteNumber(value.outputTokens) &&\n isNonnegativeFiniteNumber(value.totalTokens) &&\n isNonnegativeFiniteNumber(value.cachedInputTokens) &&\n isNonnegativeFiniteNumber(value.cacheCreationInputTokens) &&\n isUsageDetailsValue(value.details)\n );\n}\n\nfunction isNonnegativeFiniteNumber(value: JsonValue | undefined): value is number {\n return typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n}\n\nfunction isUsageDetailsValue(value: JsonValue | undefined): value is JsonObject | undefined {\n if (value === undefined) {\n return true;\n }\n if (!isJsonObjectValue(value)) {\n return false;\n }\n let total: number | undefined;\n let bucketSum = 0;\n for (const [key, detail] of Object.entries(value)) {\n if (detail === undefined || !isNonnegativeFiniteNumber(detail)) {\n return false;\n }\n if (key === \"total\") {\n total = detail;\n } else {\n bucketSum += detail;\n }\n }\n return total !== undefined && total === bucketSum;\n}\n\nfunction isCompletionSourceArray(value: JsonValue | undefined): value is CompletionSource[] {\n return (\n Array.isArray(value) &&\n value.every(\n (source) =>\n isJsonObjectValue(source) &&\n source.type === \"url\" &&\n typeof source.url === \"string\" &&\n (source.title === undefined || typeof source.title === \"string\") &&\n (source.id === undefined || typeof source.id === \"string\") &&\n (source.startIndex === undefined || typeof source.startIndex === \"number\") &&\n (source.endIndex === undefined || typeof source.endIndex === \"number\"),\n )\n );\n}\n\nfunction isProviderToolCallArray(value: JsonValue | undefined): value is ProviderToolCall[] {\n return (\n Array.isArray(value) &&\n value.every(\n (toolCall) =>\n isJsonObjectValue(toolCall) &&\n typeof toolCall.id === \"string\" &&\n typeof toolCall.name === \"string\" &&\n (toolCall.status === undefined || typeof toolCall.status === \"string\") &&\n (toolCall.details === undefined || isJsonObjectValue(toolCall.details)),\n )\n );\n}\n\nexport type CompletionRequest = {\n instructions?: string;\n chatHistory: Message[];\n documents: Document[];\n tools: ToolDefinition[];\n providerTools?: ProviderTool[];\n temperature?: number;\n maxTokens?: number;\n toolChoice?: ToolChoice;\n providerOptions?: JsonObject;\n outputSchema?: JsonObject;\n};\n\nexport type CompletionFinishReason = \"stop\" | \"length\" | \"content-filter\" | \"tool-calls\" | \"other\";\n\nexport type CompletionResponse<RawResponse = unknown> = {\n choice: AssistantContentPart[];\n usage: Usage;\n finishReason?: CompletionFinishReason;\n providerFinishReason?: string;\n contextUsage?: ContextUsage;\n rawResponse: RawResponse;\n messageId?: string;\n sources?: CompletionSource[];\n providerToolCalls?: ProviderToolCall[];\n};\n\nexport type CompletionResult<Output = string, RawResponse = unknown> = {\n output: Output;\n text: string;\n content: readonly AssistantContentPart[];\n usage: Usage;\n finishReason?: CompletionFinishReason;\n providerFinishReason?: string;\n contextUsage?: ContextUsage;\n rawResponse: RawResponse;\n messageId?: string;\n sources?: readonly CompletionSource[];\n providerToolCalls?: readonly ProviderToolCall[];\n};\n\nfunction isCompletionFinishReason(value: JsonValue | undefined): value is CompletionFinishReason {\n return (\n value === \"stop\" ||\n value === \"length\" ||\n value === \"content-filter\" ||\n value === \"tool-calls\" ||\n value === \"other\"\n );\n}\n\nexport type CompletionModelCapabilities = {\n streaming: boolean;\n tools: boolean;\n toolChoice: boolean;\n imageInput: boolean;\n documentInput: boolean;\n outputSchema: boolean;\n reasoning: boolean;\n providerTools?: boolean;\n};\n\nexport interface CompletionModel<RawResponse = unknown> {\n readonly provider: string;\n readonly modelId: string;\n readonly contextLimits?: ModelContextLimits | undefined;\n readonly capabilities: CompletionModelCapabilities;\n traceRequest?(\n request: CompletionRequest,\n options?: { stream?: boolean | undefined },\n ): JsonObject | undefined;\n completion(\n request: CompletionRequest,\n options?: ModelCallOptions,\n ): Promise<CompletionResponse<RawResponse>>;\n}\n\nexport type ToolCallArgumentsMode = \"append\" | \"replace\";\n\nexport type CompletionStreamPart =\n | {\n type: \"text_delta\";\n delta: string;\n }\n | {\n type: \"reasoning_delta\";\n delta: string;\n id?: string;\n contentType?: ReasoningContentType;\n signature?: string;\n }\n | {\n type: \"tool_call_delta\";\n id: string;\n callId?: string;\n name?: string;\n argumentsDelta?: string;\n argumentsMode?: ToolCallArgumentsMode;\n signature?: string;\n }\n | {\n type: \"tool_call\";\n toolCall: ToolCallPart;\n }\n | {\n type: \"source\";\n source: CompletionSource;\n }\n | {\n type: \"provider_tool_call\";\n toolCall: ProviderToolCall;\n }\n | {\n type: \"message_id\";\n id: string;\n };\n\nexport type CompletionModelStreamEvent<RawResponse = unknown> =\n | CompletionStreamPart\n | {\n type: \"final\";\n response: CompletionResponse<RawResponse>;\n }\n | {\n type: \"error\";\n error: unknown;\n usage?: Usage;\n };\n\nexport type CompletionStreamEvent<Output = string, RawResponse = unknown> =\n | CompletionStreamPart\n | {\n type: \"final\";\n result: CompletionResult<Output, RawResponse>;\n }\n | {\n type: \"error\";\n error: unknown;\n usage: Usage;\n };\n\nexport interface StreamingCompletionModel<RawResponse = unknown>\n extends CompletionModel<RawResponse> {\n streamCompletion(\n request: CompletionRequest,\n options?: ModelCallOptions,\n ): AsyncIterable<CompletionModelStreamEvent<RawResponse>>;\n}\n\nexport class CompletionCapabilityError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CompletionCapabilityError\";\n }\n}\n\nexport function assertCompletionRequestSupported(\n model: CompletionModel,\n request: CompletionRequest,\n options: { streaming?: boolean | undefined } = {},\n): void {\n const modelLabel = `${model.provider}:${model.modelId}`;\n const capabilities = model.capabilities;\n\n if (options.streaming === true && !capabilities.streaming) {\n throw new CompletionCapabilityError(`${modelLabel} does not support streaming completions.`);\n }\n\n if (request.tools.length > 0 && !capabilities.tools) {\n throw new CompletionCapabilityError(`${modelLabel} does not support tool definitions.`);\n }\n\n if ((request.providerTools?.length ?? 0) > 0 && capabilities.providerTools !== true) {\n throw new CompletionCapabilityError(`${modelLabel} does not support provider-executed tools.`);\n }\n\n if (request.toolChoice !== undefined && !capabilities.toolChoice) {\n throw new CompletionCapabilityError(`${modelLabel} does not support tool choice.`);\n }\n\n if (request.outputSchema !== undefined && !capabilities.outputSchema) {\n throw new CompletionCapabilityError(`${modelLabel} does not support output schemas.`);\n }\n\n if (!capabilities.imageInput && requestHasImageInput(request)) {\n throw new CompletionCapabilityError(`${modelLabel} does not support image input.`);\n }\n\n if (!capabilities.documentInput && requestHasFileDocumentInput(request)) {\n throw new CompletionCapabilityError(`${modelLabel} does not support document file input.`);\n }\n}\n\nexport function textFromAssistantContent(content: readonly AssistantContentPart[]): string {\n return content.flatMap((item) => (item.type === \"text\" ? [item.text] : [])).join(\"\\n\");\n}\n\nfunction requestHasImageInput(request: CompletionRequest): boolean {\n return request.chatHistory.some((message) =>\n message.role === \"system\" || typeof message.content === \"string\"\n ? false\n : message.content.some((content) => content.type === \"image\"),\n );\n}\n\nfunction requestHasFileDocumentInput(request: CompletionRequest): boolean {\n return request.chatHistory.some((message) =>\n message.role === \"user\" && typeof message.content !== \"string\"\n ? message.content.some((content) => content.type === \"file\" && content.data.type !== \"text\")\n : false,\n );\n}\n","import { isJsonValue } from \"./json\";\nimport type { CompletionFinishReason, CompletionResponse, ToolCallPart, Usage } from \"./types\";\n\nexport const COMPLETION_PROVIDER_OUTPUT_ERROR_CODE = \"ANVIA_COMPLETION_PROVIDER_OUTPUT\" as const;\n\nexport type CompletionProviderOutputErrorKind =\n | \"malformed-tool-arguments\"\n | \"invalid-tool-arguments\"\n | \"invalid-stream-event\"\n | \"invalid-response\"\n | \"incomplete-stream\"\n | \"incomplete-tool-call\"\n | \"invalid-tool-call\"\n | \"truncated-tool-call\"\n | \"filtered-tool-call\";\n\ntype CompletionProviderOutputErrorBaseOptions = Readonly<{\n toolCallId?: string | undefined;\n usage?: Usage | undefined;\n}>;\n\nexport type CompletionProviderOutputErrorOptions =\n | Readonly<\n CompletionProviderOutputErrorBaseOptions & {\n kind: \"truncated-tool-call\";\n finishReason: \"length\";\n }\n >\n | Readonly<\n CompletionProviderOutputErrorBaseOptions & {\n kind: \"filtered-tool-call\";\n finishReason: \"content-filter\";\n }\n >\n | Readonly<\n CompletionProviderOutputErrorBaseOptions & {\n kind: Exclude<\n CompletionProviderOutputErrorKind,\n \"truncated-tool-call\" | \"filtered-tool-call\"\n >;\n finishReason?: Exclude<CompletionFinishReason, \"length\" | \"content-filter\"> | undefined;\n }\n >;\n\nconst PROVIDER_OUTPUT_ERROR_KINDS = new Set<CompletionProviderOutputErrorKind>([\n \"malformed-tool-arguments\",\n \"invalid-tool-arguments\",\n \"invalid-stream-event\",\n \"invalid-response\",\n \"incomplete-stream\",\n \"incomplete-tool-call\",\n \"invalid-tool-call\",\n \"truncated-tool-call\",\n \"filtered-tool-call\",\n]);\n\n/**\n * A provider returned incomplete output or a tool call that cannot be consumed safely.\n *\n * The error intentionally excludes raw model arguments. Provider output can contain\n * credentials or other sensitive values and must not become log metadata by default.\n */\nexport class CompletionProviderOutputError extends Error {\n readonly code = COMPLETION_PROVIDER_OUTPUT_ERROR_CODE;\n readonly kind: CompletionProviderOutputErrorKind;\n readonly toolCallId: string | undefined;\n readonly finishReason: CompletionFinishReason | undefined;\n readonly usage: Usage | undefined;\n\n constructor(options: CompletionProviderOutputErrorOptions) {\n assertProviderOutputErrorOptions(options);\n super(providerOutputErrorMessage(options.kind, options.toolCallId));\n this.name = \"CompletionProviderOutputError\";\n this.kind = options.kind;\n this.toolCallId = options.toolCallId;\n this.finishReason = options.finishReason;\n this.usage = options.usage === undefined ? undefined : copyUsage(options.usage);\n }\n}\n\nexport function assertCompletionResponseIntegrity(\n options: Readonly<{ response: CompletionResponse }>,\n): void {\n const { response } = options;\n const toolCalls = response.choice.filter(\n (content): content is ToolCallPart => content.type === \"tool-call\",\n );\n\n if (toolCalls.length > 0) {\n if (response.finishReason !== undefined && !isCompletionFinishReason(response.finishReason)) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-call\",\n usage: response.usage,\n });\n }\n if (response.finishReason === \"length\") {\n throw new CompletionProviderOutputError({\n kind: \"truncated-tool-call\",\n finishReason: response.finishReason,\n usage: response.usage,\n });\n }\n if (response.finishReason === \"content-filter\") {\n throw new CompletionProviderOutputError({\n kind: \"filtered-tool-call\",\n finishReason: response.finishReason,\n usage: response.usage,\n });\n }\n if (response.finishReason === \"other\") {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-call\",\n finishReason: response.finishReason,\n usage: response.usage,\n });\n }\n } else if (response.finishReason === \"tool-calls\") {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-call\",\n finishReason: response.finishReason,\n usage: response.usage,\n });\n }\n\n const toolCallIds = new Set<string>();\n const callIds = new Set<string>();\n for (const toolCall of toolCalls) {\n if (!isNonblankString(toolCall.toolCallId) || !isNonblankString(toolCall.toolName)) {\n throw invalidToolCall(toolCall.toolCallId, response.usage);\n }\n if (toolCall.callId !== undefined && !isNonblankString(toolCall.callId)) {\n throw invalidToolCall(toolCall.toolCallId, response.usage);\n }\n if (toolCallIds.has(toolCall.toolCallId)) {\n throw invalidToolCall(toolCall.toolCallId, response.usage);\n }\n toolCallIds.add(toolCall.toolCallId);\n if (toolCall.callId !== undefined) {\n if (callIds.has(toolCall.callId)) {\n throw invalidToolCall(toolCall.toolCallId, response.usage);\n }\n callIds.add(toolCall.callId);\n }\n if (!isJsonValue(toolCall.input)) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-arguments\",\n toolCallId: toolCall.toolCallId,\n usage: response.usage,\n });\n }\n }\n}\n\nfunction invalidToolCall(toolCallId: unknown, usage: Usage): CompletionProviderOutputError {\n return new CompletionProviderOutputError({\n kind: \"invalid-tool-call\",\n toolCallId: isNonblankString(toolCallId) ? toolCallId : undefined,\n usage,\n });\n}\n\nfunction assertProviderOutputErrorOptions(options: CompletionProviderOutputErrorOptions): void {\n if (typeof options !== \"object\" || options === null) {\n throw new TypeError(\"CompletionProviderOutputError options must be an object.\");\n }\n if (!PROVIDER_OUTPUT_ERROR_KINDS.has(options.kind)) {\n throw new TypeError(\"CompletionProviderOutputError kind is invalid.\");\n }\n if (options.toolCallId !== undefined && !isNonblankString(options.toolCallId)) {\n throw new TypeError(\"CompletionProviderOutputError toolCallId must be a non-empty string.\");\n }\n if (options.finishReason !== undefined && !isCompletionFinishReason(options.finishReason)) {\n throw new TypeError(\"CompletionProviderOutputError finishReason is invalid.\");\n }\n if (options.kind === \"truncated-tool-call\" && options.finishReason !== \"length\") {\n throw new TypeError('CompletionProviderOutputError truncated-tool-call requires \"length\".');\n }\n if (options.kind === \"filtered-tool-call\" && options.finishReason !== \"content-filter\") {\n throw new TypeError(\n 'CompletionProviderOutputError filtered-tool-call requires \"content-filter\".',\n );\n }\n if (options.finishReason === \"length\" && options.kind !== \"truncated-tool-call\") {\n throw new TypeError(\n 'CompletionProviderOutputError finishReason \"length\" requires truncated-tool-call.',\n );\n }\n if (options.finishReason === \"content-filter\" && options.kind !== \"filtered-tool-call\") {\n throw new TypeError(\n 'CompletionProviderOutputError finishReason \"content-filter\" requires filtered-tool-call.',\n );\n }\n if (options.usage !== undefined) {\n assertUsage(options.usage);\n }\n}\n\nfunction providerOutputErrorMessage(\n kind: CompletionProviderOutputErrorKind,\n toolCallId: string | undefined,\n): string {\n const toolCall =\n toolCallId === undefined ? \"tool call\" : `tool call ${JSON.stringify(displayId(toolCallId))}`;\n if (kind === \"malformed-tool-arguments\") {\n return `Completion provider returned ${toolCall} with malformed JSON arguments.`;\n }\n if (kind === \"invalid-tool-arguments\") {\n return `Completion provider returned ${toolCall} with arguments that are not a JSON value.`;\n }\n if (kind === \"invalid-stream-event\") {\n return \"Completion provider returned an invalid stream event.\";\n }\n if (kind === \"invalid-response\") {\n return \"Completion provider returned a response that cannot be consumed safely.\";\n }\n if (kind === \"incomplete-tool-call\") {\n return \"Completion provider stream ended before its tool call was complete.\";\n }\n if (kind === \"incomplete-stream\") {\n return \"Completion provider stream ended without a terminal response.\";\n }\n if (kind === \"truncated-tool-call\") {\n return \"Completion provider stopped at its output limit before a tool call could be consumed safely.\";\n }\n if (kind === \"filtered-tool-call\") {\n return \"Completion provider content filtering prevented a tool call from being consumed safely.\";\n }\n return `Completion provider returned an invalid ${toolCall}.`;\n}\n\nfunction displayId(value: string): string {\n let sanitized = \"\";\n for (const character of value) {\n const code = character.charCodeAt(0);\n sanitized += code <= 31 || code === 127 ? \"�\" : character;\n }\n return sanitized.length <= 128 ? sanitized : `${sanitized.slice(0, 127)}…`;\n}\n\nfunction isNonblankString(value: unknown): value is string {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n\nfunction isCompletionFinishReason(value: unknown): value is CompletionFinishReason {\n return (\n value === \"stop\" ||\n value === \"length\" ||\n value === \"content-filter\" ||\n value === \"tool-calls\" ||\n value === \"other\"\n );\n}\n\nfunction assertUsage(usage: Usage): void {\n for (const value of [\n usage.inputTokens,\n usage.outputTokens,\n usage.totalTokens,\n usage.cachedInputTokens,\n usage.cacheCreationInputTokens,\n ]) {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 0) {\n throw new TypeError(\"CompletionProviderOutputError usage must contain finite token counts.\");\n }\n }\n if (usage.details !== undefined) {\n for (const value of Object.values(usage.details)) {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 0) {\n throw new TypeError(\n \"CompletionProviderOutputError usage details must contain finite token counts.\",\n );\n }\n }\n }\n}\n\nfunction copyUsage(usage: Usage): Usage {\n const copied: Usage = {\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n totalTokens: usage.totalTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n };\n if (usage.details !== undefined) copied.details = { ...usage.details };\n return copied;\n}\n","import { parseMessage, parseMessages } from \"../completion/message-schema\";\nimport type {\n CompletionRequest,\n CompletionTool,\n Document,\n JsonObject,\n Message as MessageType,\n ToolChoice,\n ToolDefinition,\n} from \"../completion/types\";\nimport { isProviderTool } from \"../completion/types\";\nimport { assertJsonObject } from \"./json-object\";\n\nexport type CompletionRequestOptions = {\n instructions?: string | undefined;\n documents?: readonly Document[] | undefined;\n tools?: readonly CompletionTool[] | undefined;\n temperature?: number | undefined;\n maxTokens?: number | undefined;\n toolChoice?: ToolChoice | undefined;\n outputSchema?: JsonObject | undefined;\n providerOptions?: JsonObject | undefined;\n};\n\nexport function createCompletionRequest(\n input: string | MessageType | readonly MessageType[],\n options: CompletionRequestOptions,\n): CompletionRequest {\n const configuredTools = options.tools ?? [];\n const chatHistory = messagesFromInput(input);\n assertNoAgentInteractionParts(chatHistory);\n const request: CompletionRequest = {\n chatHistory,\n documents: [...(options.documents ?? [])],\n tools: configuredTools.filter((tool): tool is ToolDefinition => !isProviderTool(tool)),\n };\n const providerTools = configuredTools.filter(isProviderTool);\n\n if (providerTools.length > 0) request.providerTools = providerTools;\n if (options.instructions !== undefined && options.instructions.length > 0) {\n request.instructions = options.instructions;\n }\n if (options.temperature !== undefined) request.temperature = options.temperature;\n if (options.maxTokens !== undefined) request.maxTokens = options.maxTokens;\n if (options.toolChoice !== undefined) request.toolChoice = options.toolChoice;\n if (options.outputSchema !== undefined) request.outputSchema = options.outputSchema;\n if (options.providerOptions !== undefined) {\n assertJsonObject(options.providerOptions, \"providerOptions\");\n request.providerOptions = options.providerOptions;\n }\n\n return request;\n}\n\nfunction assertNoAgentInteractionParts(messages: readonly MessageType[]): void {\n for (const message of messages) {\n if (message.role === \"tool\" && message.content.some((part) => part.type !== \"tool-result\")) {\n throw new TypeError(\n \"Completion messages contain an unresolved Agent interaction response. Resume the Agent with its continuation instead of sending interaction parts directly to a provider.\",\n );\n }\n }\n}\n\nfunction messagesFromInput(input: string | MessageType | readonly MessageType[]): MessageType[] {\n if (typeof input === \"string\") {\n return [{ role: \"user\", content: input }];\n }\n if (Array.isArray(input)) {\n if (input.length === 0) {\n throw new Error(\"input must contain at least one Message.\");\n }\n return parseMessages(input);\n }\n return [parseMessage(input)];\n}\n","import { isJsonValue } from \"./json\";\nimport { CompletionProviderOutputError } from \"./provider-output-error\";\nimport type {\n AssistantContentPart,\n CompletionModelStreamEvent,\n CompletionResponse,\n CompletionSource,\n CompletionStreamPart,\n JsonValue,\n ProviderToolCall,\n ReasoningDetail,\n ToolCallPart,\n} from \"./types\";\nimport { Usage } from \"./types\";\n\ntype AccumulatedStreamEvent = Exclude<\n CompletionStreamPart,\n { type: \"tool_call_delta\" } | { type: \"message_id\" }\n>;\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 argumentsSnapshotSeen: boolean;\n signature?: string;\n fullCallSeen: boolean;\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>): AccumulatedStreamEvent | undefined {\n if (event.type === \"text_delta\") {\n if (typeof event.delta !== \"string\") {\n throw new CompletionProviderOutputError({ kind: \"invalid-stream-event\" });\n }\n this.appendText(event.delta);\n return { type: \"text_delta\", delta: event.delta };\n }\n\n if (event.type === \"reasoning_delta\") {\n if (\n typeof event.delta !== \"string\" ||\n (event.id !== undefined && !isNonblankString(event.id)) ||\n (event.signature !== undefined && !isNonblankString(event.signature)) ||\n (event.contentType !== undefined && !isReasoningContentType(event.contentType))\n ) {\n throw new CompletionProviderOutputError({ kind: \"invalid-stream-event\" });\n }\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 if (!isNonblankString(event.id)) {\n throw new CompletionProviderOutputError({ kind: \"invalid-tool-call\" });\n }\n const toolCall = this.toolCallStateForId(event.id);\n if (toolCall.fullCallSeen) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-call\",\n toolCallId: toolCall.id,\n });\n }\n if (event.callId !== undefined) {\n if (!isNonblankString(event.callId)) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-call\",\n toolCallId: toolCall.id,\n });\n }\n if (toolCall.callId !== undefined && toolCall.callId !== event.callId) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-call\",\n toolCallId: toolCall.id,\n });\n }\n toolCall.callId = event.callId;\n }\n if (event.name !== undefined) {\n if (!isNonblankString(event.name)) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-call\",\n toolCallId: toolCall.id,\n });\n }\n if (toolCall.name.length > 0 && toolCall.name !== event.name) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-call\",\n toolCallId: toolCall.id,\n });\n }\n toolCall.name = event.name;\n }\n if (event.signature !== undefined) {\n if (\n !isNonblankString(event.signature) ||\n (toolCall.signature !== undefined && toolCall.signature !== event.signature)\n ) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-call\",\n toolCallId: toolCall.id,\n });\n }\n toolCall.signature = event.signature;\n }\n if (\n event.argumentsMode !== undefined &&\n event.argumentsMode !== \"append\" &&\n event.argumentsMode !== \"replace\"\n ) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-stream-event\",\n toolCallId: toolCall.id,\n });\n }\n if (event.argumentsMode !== undefined && event.argumentsDelta === undefined) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-stream-event\",\n toolCallId: toolCall.id,\n });\n }\n if (event.argumentsDelta !== undefined) {\n if (typeof event.argumentsDelta !== \"string\") {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-arguments\",\n toolCallId: toolCall.id,\n });\n }\n if (event.argumentsMode === \"replace\") {\n if (\n toolCall.argumentsText.length > 0 &&\n toolCall.argumentsText !== event.argumentsDelta &&\n (toolCall.argumentsSnapshotSeen ||\n !event.argumentsDelta.startsWith(toolCall.argumentsText))\n ) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-call\",\n toolCallId: toolCall.id,\n });\n }\n toolCall.argumentsText = event.argumentsDelta;\n toolCall.argumentsSnapshotSeen = true;\n } else {\n if (toolCall.argumentsSnapshotSeen) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-call\",\n toolCallId: toolCall.id,\n });\n }\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 if (!isNonblankString(event.id)) {\n throw new CompletionProviderOutputError({ kind: \"invalid-stream-event\" });\n }\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 this.assertAccumulatedFinishReason();\n let accumulatedResponse: CompletionResponse<RawResponse>;\n try {\n accumulatedResponse = this.buildAccumulatedResponse();\n } catch (error) {\n if (error instanceof CompletionProviderOutputError && this.finalResponse !== undefined) {\n throw providerOutputErrorWithUsage(error, this.finalResponse.usage);\n }\n throw error;\n }\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 assertAccumulatedFinishReason(): void {\n if (this.finalResponse === undefined) {\n if (this.toolCalls.size === 0) {\n throw new CompletionProviderOutputError({ kind: \"incomplete-stream\" });\n }\n const toolCallId = this.toolCalls.size === 1 ? this.toolCalls.keys().next().value : undefined;\n throw new CompletionProviderOutputError({\n kind: \"incomplete-tool-call\",\n toolCallId,\n });\n }\n if (this.toolCalls.size === 0) return;\n const finishReason = this.finalResponse.finishReason;\n if (finishReason === \"length\") {\n throw new CompletionProviderOutputError({\n kind: \"truncated-tool-call\",\n finishReason,\n usage: this.finalResponse.usage,\n });\n }\n if (finishReason === \"content-filter\") {\n throw new CompletionProviderOutputError({\n kind: \"filtered-tool-call\",\n finishReason,\n usage: this.finalResponse.usage,\n });\n }\n if (finishReason !== undefined && finishReason !== \"stop\" && finishReason !== \"tool-calls\") {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-call\",\n usage: this.finalResponse.usage,\n });\n }\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(toolCallContent(toolCall));\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 (\n !isNonblankString(toolCall.toolCallId) ||\n !isNonblankString(toolCall.toolName) ||\n (toolCall.callId !== undefined && !isNonblankString(toolCall.callId)) ||\n (toolCall.signature !== undefined && !isNonblankString(toolCall.signature))\n ) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-call\",\n toolCallId: isNonblankString(toolCall.toolCallId) ? toolCall.toolCallId : undefined,\n });\n }\n if (!isJsonValue(toolCall.input)) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-arguments\",\n toolCallId: toolCall.toolCallId,\n });\n }\n const existing = this.toolCalls.get(toolCall.toolCallId);\n if (existing !== undefined) {\n if (existing.fullCallSeen) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-call\",\n toolCallId: toolCall.toolCallId,\n });\n }\n if (\n (existing.name.length > 0 && existing.name !== toolCall.toolName) ||\n (existing.callId !== undefined && existing.callId !== toolCall.callId) ||\n (existing.signature !== undefined &&\n toolCall.signature !== undefined &&\n existing.signature !== toolCall.signature)\n ) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-call\",\n toolCallId: toolCall.toolCallId,\n });\n }\n if (existing.argumentsText.length > 0) {\n const accumulatedInput = parseToolArguments(existing.id, existing.argumentsText);\n if (!jsonValuesEqual(accumulatedInput, toolCall.input)) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-call\",\n toolCallId: toolCall.toolCallId,\n });\n }\n }\n }\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 argumentsSnapshotSeen: true,\n fullCallSeen: true,\n };\n if (toolCall.callId !== undefined) {\n partial.callId = toolCall.callId;\n }\n const signature = toolCall.signature ?? existing?.signature;\n if (signature !== undefined) {\n partial.signature = 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.finishReason !== undefined) {\n mergedResponse.finishReason = finalResponse.finishReason;\n }\n if (finalResponse.providerFinishReason !== undefined) {\n mergedResponse.providerFinishReason = finalResponse.providerFinishReason;\n }\n if (finalResponse.messageId !== undefined) {\n mergedResponse.messageId = finalResponse.messageId;\n }\n return this.withAccumulatedArtifacts(mergedResponse, accumulatedResponse);\n }\n\n const accumulatedNonTool = accumulatedResponse.choice.filter(\n (content) => content.type !== \"tool-call\",\n );\n const finalNonTool = finalResponse.choice.filter((content) => content.type !== \"tool-call\");\n if (accumulatedNonTool.length > 0 && !nonToolPartsEqual(accumulatedNonTool, finalNonTool)) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-stream-event\",\n usage: finalResponse.usage,\n });\n }\n\n const accumulatedById = new Map<string, ToolCallPart>();\n const accumulatedByCallId = new Map<string, ToolCallPart>();\n for (const content of accumulatedResponse.choice) {\n if (content.type !== \"tool-call\") continue;\n accumulatedById.set(content.toolCallId, content);\n if (content.callId !== undefined) accumulatedByCallId.set(content.callId, content);\n }\n\n const matchedAccumulatedToolCalls = new Set<ToolCallPart>();\n const choice = finalResponse.choice.map((content) => {\n if (content.type !== \"tool-call\") return content;\n const accumulated = accumulatedById.get(content.toolCallId);\n if (accumulated === undefined) {\n const changedIdentity =\n content.callId === undefined ? undefined : accumulatedByCallId.get(content.callId);\n if (changedIdentity !== undefined) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-call\",\n toolCallId: changedIdentity.toolCallId,\n usage: finalResponse.usage,\n });\n }\n return content;\n }\n matchedAccumulatedToolCalls.add(accumulated);\n return mergeFinalToolCall(accumulated, content, finalResponse.usage);\n });\n\n for (const accumulated of accumulatedById.values()) {\n if (!matchedAccumulatedToolCalls.has(accumulated)) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-call\",\n toolCallId: accumulated.toolCallId,\n usage: finalResponse.usage,\n });\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 argumentsSnapshotSeen: false,\n fullCallSeen: false,\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): ToolCallPart {\n const argumentsValue = 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 mergeFinalToolCall(\n accumulated: ToolCallPart,\n finalToolCall: ToolCallPart,\n usage: CompletionResponse[\"usage\"],\n): ToolCallPart {\n if (\n finalToolCall.toolCallId !== accumulated.toolCallId ||\n finalToolCall.toolName !== accumulated.toolName ||\n (accumulated.callId !== undefined && finalToolCall.callId !== accumulated.callId) ||\n (accumulated.signature !== undefined &&\n finalToolCall.signature !== undefined &&\n finalToolCall.signature !== accumulated.signature)\n ) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-call\",\n toolCallId: accumulated.toolCallId,\n usage,\n });\n }\n if (!isJsonValue(finalToolCall.input)) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-arguments\",\n toolCallId: accumulated.toolCallId,\n usage,\n });\n }\n if (!jsonValuesEqual(accumulated.input, finalToolCall.input)) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-call\",\n toolCallId: accumulated.toolCallId,\n usage,\n });\n }\n let merged: ToolCallPart = {\n type: \"tool-call\",\n toolCallId: finalToolCall.toolCallId,\n toolName: finalToolCall.toolName,\n input: accumulated.input,\n };\n const callId = finalToolCall.callId ?? accumulated.callId;\n if (callId !== undefined) merged = { ...merged, callId };\n const signature = finalToolCall.signature ?? accumulated.signature;\n if (signature !== undefined) merged = { ...merged, signature };\n return merged;\n}\n\nfunction reasoningDeltaEvent(\n event: Extract<CompletionModelStreamEvent, { type: \"reasoning_delta\" }>,\n): AccumulatedStreamEvent {\n const mapped: AccumulatedStreamEvent = { 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 parseToolArguments(toolCallId: string, text: string): JsonValue {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n throw new CompletionProviderOutputError({\n kind: \"malformed-tool-arguments\",\n toolCallId,\n });\n }\n if (!isJsonValue(value)) {\n throw new CompletionProviderOutputError({\n kind: \"invalid-tool-arguments\",\n toolCallId,\n });\n }\n return value;\n}\n\nfunction jsonValuesEqual(left: JsonValue, right: JsonValue): boolean {\n if (left === right) {\n return true;\n }\n if (left === null || right === null || typeof left !== \"object\" || typeof right !== \"object\") {\n return false;\n }\n if (isJsonArray(left) || isJsonArray(right)) {\n if (!isJsonArray(left) || !isJsonArray(right) || left.length !== right.length) {\n return false;\n }\n return left.every((value, index) => {\n const rightValue = right[index];\n return rightValue !== undefined && jsonValuesEqual(value, rightValue);\n });\n }\n\n const leftKeys = Object.keys(left);\n const rightKeys = Object.keys(right);\n if (leftKeys.length !== rightKeys.length) {\n return false;\n }\n for (const key of leftKeys) {\n if (!Object.hasOwn(right, key)) {\n return false;\n }\n const leftValue = left[key];\n const rightValue = right[key];\n if (\n leftValue === undefined ||\n rightValue === undefined ||\n !jsonValuesEqual(leftValue, rightValue)\n ) {\n return false;\n }\n }\n return true;\n}\n\nfunction nonToolPartsEqual(\n accumulated: readonly AssistantContentPart[],\n final: readonly AssistantContentPart[],\n): boolean {\n if (accumulated.length !== final.length) return false;\n if (!isJsonValue(accumulated) || !isJsonValue(final)) return false;\n const unmatched = [...final];\n for (const part of accumulated) {\n const index = unmatched.findIndex((candidate) => jsonValuesEqual(part, candidate));\n if (index < 0) return false;\n unmatched.splice(index, 1);\n }\n return true;\n}\n\nfunction isJsonArray(value: JsonValue): value is readonly JsonValue[] {\n return Array.isArray(value);\n}\n\nfunction providerOutputErrorWithUsage(\n error: CompletionProviderOutputError,\n usage: CompletionResponse[\"usage\"],\n): CompletionProviderOutputError {\n const shared: { toolCallId?: string; usage: CompletionResponse[\"usage\"] } = { usage };\n if (error.toolCallId !== undefined) shared.toolCallId = error.toolCallId;\n if (error.kind === \"truncated-tool-call\") {\n return new CompletionProviderOutputError({\n ...shared,\n kind: error.kind,\n finishReason: \"length\",\n });\n }\n if (error.kind === \"filtered-tool-call\") {\n return new CompletionProviderOutputError({\n ...shared,\n kind: error.kind,\n finishReason: \"content-filter\",\n });\n }\n if (error.finishReason === \"length\" || error.finishReason === \"content-filter\") {\n throw error;\n }\n return new CompletionProviderOutputError({\n ...shared,\n kind: error.kind,\n finishReason: error.finishReason,\n });\n}\n\nfunction isNonblankString(value: unknown): value is string {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n\nfunction isReasoningContentType(value: unknown): boolean {\n return value === \"text\" || value === \"summary\" || value === \"encrypted\" || value === \"redacted\";\n}\n","import { abortError, throwIfAborted } from \"../internal/abort\";\nimport { createCompletionRequest } from \"../internal/completion-request\";\nimport type { ModelCallOptions } from \"../model-call-options\";\nimport {\n completionProviderOutputErrorUsage,\n type ResolvedRetryOptions,\n type RetrySetting,\n resolveRetryOptions,\n retryDelayMs,\n retryOptionsForFailure,\n waitForRetry,\n} from \"../retry\";\nimport { toProviderJsonSchema, type ZodSchema } from \"../schema/zod-schema\";\nimport { isJsonValue } from \"./json\";\nimport {\n assertCompletionResponseIntegrity,\n CompletionProviderOutputError,\n} from \"./provider-output-error\";\nimport { CompletionStreamAccumulator } from \"./stream-accumulator\";\nimport type {\n CompletionModel,\n CompletionModelStreamEvent,\n CompletionRequest,\n CompletionResponse,\n CompletionResult,\n CompletionStreamEvent,\n CompletionTool,\n Document,\n JsonObject,\n Message as MessageType,\n StreamingCompletionModel,\n ToolChoice,\n} from \"./types\";\nimport { assertCompletionRequestSupported, textFromAssistantContent, Usage } from \"./types\";\n\nexport type CompletionStructuredOutputPhase = \"truncated\" | \"content-filter\" | \"parse\" | \"schema\";\n\nexport class CompletionStructuredOutputError extends Error {\n readonly phase: CompletionStructuredOutputPhase;\n readonly outputLength: number;\n readonly usage: Usage;\n readonly finishReason: CompletionResponse[\"finishReason\"];\n readonly providerFinishReason: string | undefined;\n\n constructor(options: {\n phase: CompletionStructuredOutputPhase;\n outputLength: number;\n usage: Usage;\n finishReason?: CompletionResponse[\"finishReason\"];\n providerFinishReason?: string | undefined;\n cause?: unknown;\n }) {\n const failure =\n options.phase === \"truncated\"\n ? \"because the provider reached its output limit\"\n : options.phase === \"content-filter\"\n ? \"because the provider filtered the response\"\n : options.phase === \"parse\"\n ? \"during JSON parsing\"\n : \"during schema validation\";\n super(`Structured completion output failed ${failure}.`, { cause: options.cause });\n this.name = \"CompletionStructuredOutputError\";\n this.phase = options.phase;\n this.outputLength = options.outputLength;\n this.usage = options.usage;\n this.finishReason = options.finishReason;\n this.providerFinishReason = options.providerFinishReason;\n }\n}\n\nexport type CompletionInput =\n | { prompt: string; messages?: never }\n | { messages: readonly MessageType[]; prompt?: never };\n\nexport type CompletionBaseOptions<Model extends CompletionModel = CompletionModel> =\n CompletionInput & {\n model: Model;\n instructions?: string | undefined;\n documents?: readonly Document[] | undefined;\n tools?: readonly CompletionTool[] | undefined;\n temperature?: number | undefined;\n maxTokens?: number | undefined;\n toolChoice?: ToolChoice | undefined;\n providerOptions?: JsonObject | undefined;\n retries?: RetrySetting | undefined;\n abortSignal?: AbortSignal | undefined;\n };\n\nexport type GenerateCompletionOptions<Model extends CompletionModel = CompletionModel> =\n CompletionBaseOptions<Model> & { outputSchema?: never };\n\nexport type GenerateStructuredCompletionOptions<\n Output,\n Model extends CompletionModel = CompletionModel,\n> = CompletionBaseOptions<Model> & { outputSchema: ZodSchema<Output> };\n\nexport type StreamCompletionOptions<\n Model extends StreamingCompletionModel = StreamingCompletionModel,\n> = GenerateCompletionOptions<Model>;\n\nexport type StreamStructuredCompletionOptions<\n Output,\n Model extends StreamingCompletionModel = StreamingCompletionModel,\n> = GenerateStructuredCompletionOptions<Output, Model>;\n\ntype RawResponseOf<Model> =\n Model extends CompletionModel<infer RawResponse> ? RawResponse : unknown;\n\nexport function generateCompletion<Output, Model extends CompletionModel>(\n options: GenerateStructuredCompletionOptions<Output, Model>,\n): Promise<CompletionResult<Output, RawResponseOf<Model>>>;\nexport function generateCompletion<Model extends CompletionModel>(\n options: GenerateCompletionOptions<Model>,\n): Promise<CompletionResult<string, RawResponseOf<Model>>>;\nexport async function generateCompletion<Output, Model extends CompletionModel>(\n options: GenerateCompletionOptions<Model> | GenerateStructuredCompletionOptions<Output, Model>,\n): Promise<CompletionResult<Output | string, RawResponseOf<Model>>> {\n throwIfAborted(options.abortSignal);\n const request = requestFromOptions(options);\n assertCompletionRequestSupported(options.model, request);\n const retries = resolveOptionalRetries(options.retries);\n const response = await sendCompletion(options.model, request, retries, options.abortSignal);\n return resultFromResponse(response, structuredOutputSchema(options));\n}\n\nexport function streamCompletion<Output, Model extends StreamingCompletionModel>(\n options: StreamStructuredCompletionOptions<Output, Model>,\n): AsyncIterable<CompletionStreamEvent<Output, RawResponseOf<Model>>>;\nexport function streamCompletion<Model extends StreamingCompletionModel>(\n options: StreamCompletionOptions<Model>,\n): AsyncIterable<CompletionStreamEvent<string, RawResponseOf<Model>>>;\nexport function streamCompletion<Output, Model extends StreamingCompletionModel>(\n options: StreamCompletionOptions<Model> | StreamStructuredCompletionOptions<Output, Model>,\n): AsyncIterable<CompletionStreamEvent<Output | string, RawResponseOf<Model>>> {\n throwIfAborted(options.abortSignal);\n const request = requestFromOptions(options);\n if (!isStreamingCompletionModel(options.model) || !options.model.capabilities.streaming) {\n throw new Error(\"This completion model does not support streaming\");\n }\n assertCompletionRequestSupported(options.model, request, { streaming: true });\n const retries = resolveOptionalRetries(options.retries);\n return streamCompletionWithRetries(\n options.model,\n request,\n retries,\n options.abortSignal,\n structuredOutputSchema(options),\n );\n}\n\nasync function sendCompletion<Model extends CompletionModel>(\n model: Model,\n request: CompletionRequest,\n retries: ResolvedRetryOptions | undefined,\n abortSignal: AbortSignal | undefined,\n): Promise<CompletionResponse<RawResponseOf<Model>>> {\n const callOptions = modelCallOptions(abortSignal);\n let attempt = 1;\n let failedUsage = Usage.empty();\n while (true) {\n try {\n throwIfAborted(abortSignal);\n const response = (await model.completion(request, callOptions)) as CompletionResponse<\n RawResponseOf<Model>\n >;\n assertCompletionResponseIntegrity({ response });\n return Usage.isEmpty(failedUsage)\n ? response\n : { ...response, usage: Usage.add(failedUsage, response.usage) };\n } catch (error) {\n const normalizedError =\n abortSignal?.aborted === true ? abortError(abortSignal.reason) : error;\n const attemptUsage = completionProviderOutputErrorUsage(normalizedError);\n if (attemptUsage !== undefined) failedUsage = Usage.add(failedUsage, attemptUsage);\n const retryOptions = retryOptionsForFailure(retries, {\n error: normalizedError,\n attempt,\n streaming: false,\n });\n if (retryOptions === undefined) throw normalizedError;\n await waitForRetry(retryDelayMs(retryOptions, attempt), abortSignal);\n attempt += 1;\n }\n }\n}\n\nfunction resolveOptionalRetries(\n setting: RetrySetting | undefined,\n): ResolvedRetryOptions | undefined {\n return setting === undefined || setting === false ? undefined : resolveRetryOptions(setting);\n}\n\nasync function* streamCompletionWithRetries<Output, Model extends StreamingCompletionModel>(\n model: Model,\n request: CompletionRequest,\n retries: ResolvedRetryOptions | undefined,\n abortSignal: AbortSignal | undefined,\n outputSchema: ZodSchema<Output> | undefined,\n): AsyncIterable<CompletionStreamEvent<Output | string, RawResponseOf<Model>>> {\n let attempt = 1;\n let swallowedUsage = Usage.empty();\n const callOptions = modelCallOptions(abortSignal);\n\n attemptLoop: while (true) {\n let exposedProgress = false;\n let retryDelay: number | undefined;\n const accumulator = new CompletionStreamAccumulator<RawResponseOf<Model>>();\n try {\n throwIfAborted(abortSignal);\n const events = model.streamCompletion(request, callOptions) as AsyncIterable<\n CompletionModelStreamEvent<RawResponseOf<Model>>\n >;\n for await (const event of events) {\n if (event.type === \"error\" && !exposedProgress) {\n const eventError =\n abortSignal?.aborted === true ? abortError(abortSignal.reason) : event.error;\n const eventUsage =\n event.usage ?? completionProviderOutputErrorUsage(eventError) ?? Usage.empty();\n const retryOptions = retryOptionsForFailure(retries, {\n error: eventError,\n attempt,\n streaming: true,\n });\n if (retryOptions !== undefined) {\n swallowedUsage = Usage.add(swallowedUsage, eventUsage);\n retryDelay = retryDelayMs(retryOptions, attempt);\n break;\n }\n }\n\n if (event.type === \"error\") {\n const eventError =\n abortSignal?.aborted === true ? abortError(abortSignal.reason) : event.error;\n const eventUsage =\n event.usage ?? completionProviderOutputErrorUsage(eventError) ?? Usage.empty();\n yield {\n type: \"error\",\n error: eventError,\n usage: Usage.add(swallowedUsage, eventUsage),\n };\n return;\n }\n\n if (event.type === \"final\") {\n const cumulativeUsage = Usage.add(swallowedUsage, event.response.usage);\n try {\n accumulator.accept(event);\n const accumulatedResponse = accumulator.response();\n const response = Usage.isEmpty(swallowedUsage)\n ? accumulatedResponse\n : { ...accumulatedResponse, usage: cumulativeUsage };\n assertCompletionResponseIntegrity({ response });\n yield {\n type: \"final\",\n result: resultFromResponse(response, outputSchema),\n };\n } catch (error) {\n const retryOptions = exposedProgress\n ? undefined\n : retryOptionsForFailure(retries, {\n error,\n attempt,\n streaming: true,\n });\n if (retryOptions !== undefined) {\n swallowedUsage = cumulativeUsage;\n await waitForRetry(retryDelayMs(retryOptions, attempt), abortSignal);\n attempt += 1;\n continue attemptLoop;\n }\n yield { type: \"error\", error, usage: cumulativeUsage };\n }\n return;\n }\n\n accumulator.accept(event);\n exposedProgress = true;\n yield event;\n }\n\n if (retryDelay !== undefined) {\n await waitForRetry(retryDelay, abortSignal);\n attempt += 1;\n continue;\n }\n\n let incomplete: unknown;\n try {\n accumulator.response();\n incomplete = new CompletionProviderOutputError({ kind: \"incomplete-stream\" });\n } catch (error) {\n incomplete = error;\n }\n if (!exposedProgress) {\n const retryOptions = retryOptionsForFailure(retries, {\n error: incomplete,\n attempt,\n streaming: true,\n });\n if (retryOptions !== undefined) {\n await waitForRetry(retryDelayMs(retryOptions, attempt), abortSignal);\n attempt += 1;\n continue;\n }\n }\n yield { type: \"error\", error: incomplete, usage: swallowedUsage };\n return;\n } catch (error) {\n const normalizedError =\n abortSignal?.aborted === true ? abortError(abortSignal.reason) : error;\n const attemptUsage = completionProviderOutputErrorUsage(normalizedError);\n const cumulativeUsage =\n attemptUsage === undefined ? swallowedUsage : Usage.add(swallowedUsage, attemptUsage);\n if (!exposedProgress) {\n const retryOptions = retryOptionsForFailure(retries, {\n error: normalizedError,\n attempt,\n streaming: true,\n });\n if (retryOptions !== undefined) {\n try {\n swallowedUsage = cumulativeUsage;\n await waitForRetry(retryDelayMs(retryOptions, attempt), abortSignal);\n attempt += 1;\n continue;\n } catch (waitError) {\n yield { type: \"error\", error: waitError, usage: cumulativeUsage };\n return;\n }\n }\n }\n yield { type: \"error\", error: normalizedError, usage: cumulativeUsage };\n return;\n }\n }\n}\n\nfunction requestFromOptions<Model extends CompletionModel, Output>(\n options: GenerateCompletionOptions<Model> | GenerateStructuredCompletionOptions<Output, Model>,\n): CompletionRequest {\n const input = inputFromOptions(options);\n return createCompletionRequest(input, {\n instructions: options.instructions,\n documents: options.documents,\n tools: options.tools,\n temperature: options.temperature,\n maxTokens: options.maxTokens,\n toolChoice: options.toolChoice,\n providerOptions: options.providerOptions,\n outputSchema:\n \"outputSchema\" in options && options.outputSchema !== undefined\n ? toProviderJsonSchema(options.outputSchema)\n : undefined,\n });\n}\n\nfunction inputFromOptions(options: CompletionInput): string | readonly MessageType[] {\n const prompt = (options as { prompt?: unknown }).prompt;\n const messages = (options as { messages?: unknown }).messages;\n const hasPrompt = prompt !== undefined;\n const hasMessages = messages !== undefined;\n if (hasPrompt === hasMessages) {\n throw new TypeError(\"Exactly one of prompt or messages must be provided.\");\n }\n if (hasPrompt) {\n if (typeof prompt !== \"string\" || prompt.trim().length === 0) {\n throw new TypeError(\"Completion prompt must be a non-empty string.\");\n }\n return prompt;\n }\n if (!Array.isArray(messages)) {\n throw new TypeError(\"Completion messages must be an array of Message values.\");\n }\n return messages as readonly MessageType[];\n}\n\nfunction structuredOutputSchema<Output>(options: {\n outputSchema?: ZodSchema<Output> | undefined;\n}): ZodSchema<Output> | undefined {\n return options.outputSchema;\n}\n\nfunction resultFromResponse<Output, RawResponse>(\n response: CompletionResponse<RawResponse>,\n outputSchema: ZodSchema<Output> | undefined,\n): CompletionResult<Output | string, RawResponse> {\n const text = textFromAssistantContent(response.choice);\n const result: CompletionResult<Output | string, RawResponse> = {\n output: outputSchema === undefined ? text : parseCompletionOutput(text, outputSchema, response),\n text,\n content: [...response.choice],\n usage: response.usage,\n rawResponse: response.rawResponse,\n };\n if (response.finishReason !== undefined) result.finishReason = response.finishReason;\n if (response.providerFinishReason !== undefined) {\n result.providerFinishReason = response.providerFinishReason;\n }\n if (response.contextUsage !== undefined) result.contextUsage = response.contextUsage;\n if (response.messageId !== undefined) result.messageId = response.messageId;\n if (response.sources !== undefined) result.sources = [...response.sources];\n if (response.providerToolCalls !== undefined) {\n result.providerToolCalls = [...response.providerToolCalls];\n }\n return result;\n}\n\nfunction parseCompletionOutput<Output, RawResponse>(\n text: string,\n schema: ZodSchema<Output>,\n response: CompletionResponse<RawResponse>,\n): Output {\n if (response.finishReason === \"content-filter\") {\n throw new CompletionStructuredOutputError({\n phase: \"content-filter\",\n outputLength: text.length,\n usage: response.usage,\n finishReason: response.finishReason,\n providerFinishReason: response.providerFinishReason,\n });\n }\n if (response.finishReason === \"length\") {\n throw new CompletionStructuredOutputError({\n phase: \"truncated\",\n outputLength: text.length,\n usage: response.usage,\n finishReason: response.finishReason,\n providerFinishReason: response.providerFinishReason,\n });\n }\n let json: unknown;\n try {\n json = JSON.parse(text);\n if (!isJsonValue(json)) {\n throw new TypeError(\"Structured completion output is not a JSON value.\");\n }\n } catch (error) {\n throw new CompletionStructuredOutputError({\n phase: \"parse\",\n outputLength: text.length,\n usage: response.usage,\n finishReason: response.finishReason,\n providerFinishReason: response.providerFinishReason,\n cause: error,\n });\n }\n try {\n return schema.parse(json);\n } catch (error) {\n throw new CompletionStructuredOutputError({\n phase: \"schema\",\n outputLength: text.length,\n usage: response.usage,\n finishReason: response.finishReason,\n providerFinishReason: response.providerFinishReason,\n cause: error,\n });\n }\n}\n\nfunction modelCallOptions(abortSignal: AbortSignal | undefined): ModelCallOptions | undefined {\n return abortSignal === undefined ? undefined : { abortSignal };\n}\n\nexport function isStreamingCompletionModel(\n model: CompletionModel,\n): model is StreamingCompletionModel {\n return typeof (model as { streamCompletion?: unknown }).streamCompletion === \"function\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA2JO,SAAS,qBACd,WACQ;AACR,QAAM,UAAU,UAAU,YAAY,UAAU,UAAU;AAC1D,MAAI,YAAY,QAAW;AACzB,WAAO,UAAU,YAAY,UAAU,OAAO;AAAA,EAChD;AACA,SAAO,QACJ,QAAQ,CAAC,SAAS;AACjB,QAAI,KAAK,SAAS,UAAU,KAAK,SAAS,WAAW;AACnD,aAAO,CAAC,KAAK,IAAI;AAAA,IACnB;AACA,WAAO,CAAC;AAAA,EACV,CAAC,EACA,KAAK,EAAE;AACZ;AAgC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B,OAAO,SAAS;AAAA,MAChB,cAAc,SAAS;AAAA,MACvB,sBAAsB,SAAS;AAAA,IACjC,CAAC;AAAA,EACH;AACA,MAAI,SAAS,iBAAiB,UAAU;AACtC,UAAM,IAAI,gCAAgC;AAAA,MACxC,OAAO;AAAA,MACP,cAAc,KAAK;AAAA,MACnB,OAAO,SAAS;AAAA,MAChB,cAAc,SAAS;AAAA,MACvB,sBAAsB,SAAS;AAAA,IACjC,CAAC;AAAA,EACH;AACA,MAAI;AACJ,MAAI;AACF,WAAO,KAAK,MAAM,IAAI;AACtB,QAAI,CAAC,YAAY,IAAI,GAAG;AACtB,YAAM,IAAI,UAAU,mDAAmD;AAAA,IACzE;AAAA,EACF,SAAS,OAAO;AACd,UAAM,IAAI,gCAAgC;AAAA,MACxC,OAAO;AAAA,MACP,cAAc,KAAK;AAAA,MACnB,OAAO,SAAS;AAAA,MAChB,cAAc,SAAS;AAAA,MACvB,sBAAsB,SAAS;AAAA,MAC/B,OAAO;AAAA,IACT,CAAC;AAAA,EACH;AACA,MAAI;AACF,WAAO,OAAO,MAAM,IAAI;AAAA,EAC1B,SAAS,OAAO;AACd,UAAM,IAAI,gCAAgC;AAAA,MACxC,OAAO;AAAA,MACP,cAAc,KAAK;AAAA,MACnB,OAAO,SAAS;AAAA,MAChB,cAAc,SAAS;AAAA,MACvB,sBAAsB,SAAS;AAAA,MAC/B,OAAO;AAAA,IACT,CAAC;AAAA,EACH;AACF;AAEA,SAAS,iBAAiB,aAAoE;AAC5F,SAAO,gBAAgB,SAAY,SAAY,EAAE,YAAY;AAC/D;AAEO,SAAS,2BACd,OACmC;AACnC,SAAO,OAAQ,MAAyC,qBAAqB;AAC/E;","names":["isCompletionFinishReason","isNonblankString","key","reasoning"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/vector-store/index.ts","../src/internal/vector-search-options.ts","../src/internal/agent-runtime/approval-requirement.ts","../src/tool/errors.ts","../src/tool/tool.ts","../src/internal/agent-runtime/prepared-tool-call.ts","../src/tool/create-tool.ts","../src/vector-store/filter.ts","../src/vector-store/lsh.ts","../src/vector-store/retrieve.ts"],"sourcesContent":["import { z } from \"zod\";\nimport {\n cosineSimilarity,\n type EmbeddedDocument,\n type Embedding,\n type VectorMetadata,\n} from \"../embeddings\";\nimport { assertFiniteMinScore, assertPositiveSearchLimit } from \"../internal/vector-search-options\";\nimport { createTool } from \"../tool/create-tool\";\nimport type { Tool } from \"../tool/tool\";\nimport { matchesVectorFilter } from \"./filter\";\nimport { LshIndex } from \"./lsh\";\nimport { retrieveDocuments } from \"./retrieve\";\nimport type {\n IndexStrategy,\n VectorInspectItem,\n VectorInspectPage,\n VectorInspectRequest,\n VectorSearchRequest,\n VectorSearchResult,\n VectorSearchToolOptions,\n VectorStore,\n VectorStoreUpsertOptions,\n} from \"./types\";\n\nexport { matchesVectorFilter, vectorFilter } from \"./filter\";\nexport { retrieveDocuments } from \"./retrieve\";\nexport type * from \"./types\";\n\ntype StoredDocument<T, Metadata extends VectorMetadata> = EmbeddedDocument<T, Metadata>;\n\nexport type InMemoryVectorStoreOptions = {\n dimensions?: number | undefined;\n index?: IndexStrategy | undefined;\n};\n\nexport type InMemoryVectorStoreFromDocumentsOptions<\n T,\n Metadata extends VectorMetadata = VectorMetadata,\n> = InMemoryVectorStoreOptions & {\n documents: Array<EmbeddedDocument<T, Metadata>>;\n};\n\nexport class InMemoryVectorStore<T, Metadata extends VectorMetadata = VectorMetadata>\n implements VectorStore<T, Metadata>\n{\n private readonly documents = new Map<string, StoredDocument<T, Metadata>>();\n private readonly indexStrategy: IndexStrategy;\n private lshIndex: LshIndex | undefined;\n private embeddingDimension: number | undefined;\n\n constructor(options: InMemoryVectorStoreOptions = {}) {\n this.indexStrategy = options.index ?? { type: \"bruteForce\" };\n if (\n options.dimensions !== undefined &&\n (!Number.isSafeInteger(options.dimensions) || options.dimensions < 1)\n ) {\n throw new RangeError(\"Vector dimensions must be a positive safe integer.\");\n }\n this.embeddingDimension = options.dimensions;\n }\n\n static fromDocuments<T, Metadata extends VectorMetadata = VectorMetadata>(\n options: InMemoryVectorStoreFromDocumentsOptions<T, Metadata>,\n ): InMemoryVectorStore<T, Metadata> {\n const store = new InMemoryVectorStore<T, Metadata>(options);\n store.replaceDocuments(options.documents);\n return store;\n }\n\n async ensure(): Promise<void> {}\n async validate(): Promise<void> {}\n\n async upsert(options: VectorStoreUpsertOptions<T, Metadata>): Promise<void> {\n this.replaceDocuments(options.documents);\n }\n\n get(options: { id: string }): StoredDocument<T, Metadata> | undefined {\n return this.documents.get(options.id);\n }\n\n values(): Array<StoredDocument<T, Metadata>> {\n return [...this.documents.values()];\n }\n\n len(): number {\n return this.documents.size;\n }\n\n isEmpty(): boolean {\n return this.documents.size === 0;\n }\n\n async search(request: VectorSearchRequest): Promise<Array<VectorSearchResult<T, Metadata>>> {\n throwIfAborted(request.abortSignal);\n assertPositiveSearchLimit(request.topK);\n assertFiniteMinScore(request.minScore);\n const queryEmbedding: Embedding = { document: \"\", vector: request.vector };\n const results = this.candidates(queryEmbedding)\n .filter((document) => matchesVectorFilter(document.metadata, request.filter))\n .flatMap((document) => {\n const score = bestScore(queryEmbedding, document.embeddings);\n if (score === undefined || (request.minScore !== undefined && score < request.minScore)) {\n return [];\n }\n let result: VectorSearchResult<T, Metadata> = {\n score,\n id: document.id,\n document: document.document,\n };\n if (document.metadata !== undefined) {\n result = { ...result, metadata: document.metadata };\n }\n return [result];\n })\n .sort((left, right) => right.score - left.score)\n .slice(0, request.topK);\n throwIfAborted(request.abortSignal);\n return results;\n }\n\n async inspect(request: VectorInspectRequest): Promise<VectorInspectPage<T, Metadata>> {\n throwIfAborted(request.abortSignal);\n const limit = assertPositiveSearchLimit(request.limit);\n const start = Math.max(0, Math.trunc(Number(request.cursor ?? \"0\")));\n const documents = this.values().filter((document) =>\n matchesVectorFilter(document.metadata, request.filter),\n );\n const page = documents.slice(start, start + limit);\n const nextOffset = start + page.length;\n const result: VectorInspectPage<T, Metadata> = {\n items: page.map((document): VectorInspectItem<T, Metadata> => {\n let item: VectorInspectItem<T, Metadata> = {\n id: document.id,\n document: document.document,\n };\n if (document.metadata !== undefined) {\n item = { ...item, metadata: document.metadata };\n }\n return item;\n }),\n totalCount: documents.length,\n };\n if (nextOffset < documents.length) result.nextCursor = String(nextOffset);\n throwIfAborted(request.abortSignal);\n return result;\n }\n\n private replaceDocuments(documents: Array<EmbeddedDocument<T, Metadata>>): void {\n const ids = new Set<string>();\n for (const document of documents) {\n if (ids.has(document.id)) throw new TypeError(`Duplicate vector document id: ${document.id}`);\n ids.add(document.id);\n if (document.embeddings.length === 0) {\n throw new TypeError(`Vector document ${document.id} must contain at least one embedding.`);\n }\n for (const embedding of document.embeddings)\n assertFiniteVector(embedding.vector, document.id);\n }\n this.validateDocumentDimensions(documents);\n for (const document of documents) this.documents.set(document.id, document);\n this.rebuildLshIndex();\n }\n\n private candidates(queryEmbedding: Embedding): Array<StoredDocument<T, Metadata>> {\n this.validateQueryDimension(queryEmbedding);\n if (this.indexStrategy.type !== \"lsh\" || this.lshIndex === undefined) return this.values();\n const candidateIds = this.lshIndex.query(queryEmbedding.vector);\n if (candidateIds.size === 0) return this.values();\n return [...candidateIds].flatMap((id) => {\n const document = this.documents.get(id);\n return document === undefined ? [] : [document];\n });\n }\n\n private rebuildLshIndex(): void {\n if (this.indexStrategy.type !== \"lsh\") {\n this.lshIndex = undefined;\n return;\n }\n const firstEmbedding = this.values().flatMap((document) => document.embeddings)[0];\n if (firstEmbedding === undefined) {\n this.lshIndex = undefined;\n return;\n }\n const index = new LshIndex(firstEmbedding.vector.length, this.indexStrategy);\n for (const document of this.documents.values()) {\n for (const embedding of document.embeddings) index.insert(document.id, embedding.vector);\n }\n this.lshIndex = index;\n }\n\n private validateDocumentDimensions(documents: Array<EmbeddedDocument<T, Metadata>>): void {\n let dimension = this.embeddingDimension;\n for (const document of documents) {\n for (const embedding of document.embeddings) {\n dimension = validateEmbeddingDimension(dimension, embedding, document.id);\n }\n }\n this.embeddingDimension = dimension;\n }\n\n private validateQueryDimension(queryEmbedding: Embedding): void {\n if (this.embeddingDimension !== undefined) {\n validateEmbeddingDimension(this.embeddingDimension, queryEmbedding, \"query\");\n }\n }\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) {\n const error = new Error(\"The operation was aborted.\");\n error.name = \"AbortError\";\n throw error;\n }\n}\n\nexport function createVectorSearchTool<T, Metadata extends VectorMetadata>(\n options: VectorSearchToolOptions<T, Metadata>,\n): Tool<{ query: string; topK?: number }, Array<VectorSearchResult<T, Metadata>>> {\n const configuredTopK = assertPositiveSearchLimit(options.topK ?? 5);\n assertFiniteMinScore(options.minScore);\n return createTool({\n name: options.name,\n description:\n options.description ?? \"Search a vector store for documents relevant to the provided query.\",\n inputSchema: z.object({\n query: z.string().min(1).describe(\"The query string to search for relevant documents.\"),\n topK: z.number().int().positive().optional().describe(\"The maximum number of results.\"),\n }),\n outputSchema: z.array(\n z.object({\n score: z.number(),\n id: z.string(),\n document: z.any(),\n metadata: z\n .record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.null()]))\n .optional(),\n }),\n ),\n execute: ({ query, topK }, context) => {\n const request = {\n query,\n topK: topK ?? configuredTopK,\n minScore: options.minScore,\n filter: options.filter,\n retries: options.retries,\n abortSignal: context.abortSignal,\n };\n return \"models\" in options && options.models !== undefined\n ? retrieveDocuments({\n ...request,\n store: options.store,\n models: options.models,\n fusion: options.fusion,\n })\n : retrieveDocuments({ ...request, store: options.store, model: options.model });\n },\n }) as Tool<{ query: string; topK?: number }, Array<VectorSearchResult<T, Metadata>>>;\n}\n\nfunction bestScore(queryEmbedding: Embedding, embeddings: Embedding[]): number | undefined {\n let best: number | undefined;\n for (const embedding of embeddings) {\n const score = cosineSimilarity(queryEmbedding.vector, embedding.vector);\n best = best === undefined ? score : Math.max(best, score);\n }\n return best;\n}\n\nfunction validateEmbeddingDimension(\n expectedDimension: number | undefined,\n embedding: Embedding,\n id: string,\n): number {\n assertFiniteVector(embedding.vector, id);\n if (expectedDimension === undefined) return embedding.vector.length;\n if (embedding.vector.length !== expectedDimension) {\n throw new Error(\n `Vector dimension mismatch: expected ${expectedDimension} dimensions but received ${embedding.vector.length} for ${id}`,\n );\n }\n return expectedDimension;\n}\n\nfunction assertFiniteVector(vector: number[], id: string): void {\n if (vector.length === 0) throw new TypeError(`Vector for ${id} must not be empty.`);\n if (!vector.every(Number.isFinite)) {\n throw new TypeError(`Vector for ${id} must contain only finite numbers.`);\n }\n}\n","export function assertPositiveSearchLimit(value: number, name = \"topK\"): number {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new RangeError(`${name} must be a positive safe integer.`);\n }\n return value;\n}\n\nexport function assertFiniteMinScore(\n value: number | undefined,\n name = \"minScore\",\n): number | undefined {\n if (value !== undefined && !Number.isFinite(value)) {\n throw new RangeError(`${name} must be a finite number.`);\n }\n return value;\n}\n","import type { ToolApprovalRequirement } from \"../../tool/tool\";\n\nexport function toolMayRequireApproval(requirement: unknown): boolean {\n return requirement !== undefined && requirement !== false;\n}\n\nexport function assertToolApprovalRequirement(\n requirement: unknown,\n options: { allowFunction: boolean },\n): asserts requirement is boolean | ToolApprovalRequirement | ((...args: never[]) => unknown) {\n if (typeof requirement === \"boolean\") {\n return;\n }\n if (options.allowFunction && typeof requirement === \"function\") {\n return;\n }\n if (typeof requirement !== \"object\" || requirement === null || Array.isArray(requirement)) {\n throw new TypeError(\n 'Tool \"requiresApproval\" must be a boolean, a function, or an object with an optional string reason.',\n );\n }\n const reason = (requirement as { reason?: unknown }).reason;\n if (reason !== undefined && typeof reason !== \"string\") {\n throw new TypeError('Tool \"requiresApproval.reason\" must be a string.');\n }\n}\n","export class ToolCallError extends Error {\n constructor(\n message: string,\n readonly cause?: unknown,\n ) {\n super(message);\n this.name = \"ToolCallError\";\n }\n}\n\nexport class ToolNotFoundError extends Error {\n constructor(readonly toolName: string) {\n super(`Tool not found: ${toolName}`);\n this.name = \"ToolNotFoundError\";\n }\n}\n\nexport class ToolJsonError extends Error {\n constructor(\n message: string,\n readonly cause?: unknown,\n ) {\n super(message);\n this.name = \"ToolJsonError\";\n }\n}\n","import { isJsonValue } from \"../completion/json\";\nimport { parseMessage } from \"../completion/message-schema\";\nimport type {\n JsonObject,\n JsonValue,\n ToolDefinition,\n ToolResultContentPart,\n ToolResultOutput,\n} from \"../completion/types\";\n\nexport type ToolApprovalRunContext = {\n agentId: string;\n runId: string;\n sessionId?: string;\n metadata?: JsonObject;\n};\n\nexport type ToolApprovalContext<Args = unknown> = {\n toolName: string;\n args: Args;\n rawArgs: string;\n toolCallId: string;\n callId?: string;\n internalCallId: string;\n run: ToolApprovalRunContext;\n};\n\nexport type ToolApprovalRequirement = {\n reason?: string | undefined;\n};\n\nexport type ToolRequiresApproval<Args = unknown> =\n | boolean\n | ToolApprovalRequirement\n | ((\n args: Args,\n context: ToolApprovalContext<Args>,\n ) => boolean | ToolApprovalRequirement | Promise<boolean | ToolApprovalRequirement>);\n\nexport type ToolCallStreamEvent = {\n agentId: string;\n agentName?: string | undefined;\n event: unknown;\n};\n\nexport type ToolCallContext = {\n emitStreamEvent?(event: ToolCallStreamEvent): void | Promise<void>;\n abortSignal?: AbortSignal | undefined;\n};\n\nexport interface Tool<Args = unknown, Output = unknown> {\n readonly name: string;\n readonly requiresApproval?: ToolRequiresApproval<Args>;\n definition(prompt: string): ToolDefinition | Promise<ToolDefinition>;\n call(args: Args, context?: ToolCallContext): Output | Promise<Output>;\n parseInput?(args: JsonValue): Args;\n}\n\nexport type AnyTool = Omit<Tool<unknown, unknown>, \"requiresApproval\"> & {\n readonly requiresApproval?: unknown;\n};\n\nconst richToolOutput = Symbol(\"anvia.tool-output.content\");\n\nexport type RichToolOutput = Readonly<{\n [richToolOutput]: true;\n content: readonly ToolResultContentPart[];\n}>;\n\nexport type NormalizedToolOutput = ToolResultOutput;\n\nexport class ToolResultSerializationError extends TypeError {\n constructor(readonly output: unknown) {\n super(\"Tool output must be a string, a strict JSON value, or ToolOutput.content(...).\");\n this.name = \"ToolResultSerializationError\";\n }\n}\n\nexport const ToolOutput = {\n content(content: readonly ToolResultContentPart[]): RichToolOutput {\n return { [richToolOutput]: true, content };\n },\n};\n\nexport function normalizeToolResultOutput(output: unknown): NormalizedToolOutput {\n if (typeof output === \"string\") {\n return { type: \"text\", value: output };\n }\n if (isRichToolOutput(output)) {\n try {\n const message = parseMessage({\n role: \"tool\",\n content: [\n {\n type: \"tool-result\",\n toolCallId: \"validation\",\n toolName: \"validation\",\n output: { type: \"content\", value: output.content },\n },\n ],\n });\n if (message.role !== \"tool\") throw new TypeError(\"Unexpected message role\");\n const result = message.content[0];\n if (result?.type !== \"tool-result\") throw new TypeError(\"Unexpected tool result part\");\n if (result?.output.type !== \"content\") throw new TypeError(\"Unexpected tool output\");\n return result.output;\n } catch {\n throw new ToolResultSerializationError(output);\n }\n }\n if (isJsonValue(output)) {\n return { type: \"json\", value: output };\n }\n throw new ToolResultSerializationError(output);\n}\n\nexport function toolResultContentToText(content: readonly ToolResultContentPart[]): string {\n return content\n .map((item) => (item.type === \"text\" ? item.text : `[file:${item.mediaType}]`))\n .join(\"\\n\");\n}\n\nfunction isRichToolOutput(value: unknown): value is RichToolOutput {\n return typeof value === \"object\" && value !== null && richToolOutput in value;\n}\n\nexport function parseToolArgs(args: string): JsonValue {\n const value: unknown = JSON.parse(args);\n if (!isJsonValue(value)) {\n throw new TypeError(\"Tool arguments must be a JSON value.\");\n }\n return value;\n}\n","import { ToolCallError, ToolJsonError } from \"../../tool/errors\";\nimport {\n type AnyTool,\n type NormalizedToolOutput,\n normalizeToolResultOutput,\n parseToolArgs,\n type ToolCallContext,\n} from \"../../tool/tool\";\n\nconst preparedToolInputSymbol = Symbol(\"preparedToolInput\");\nconst preparedToolOwnerSymbol = Symbol(\"preparedToolOwner\");\n\nexport type PreparedToolCall = {\n input: unknown;\n call(context: ToolCallContext): Promise<NormalizedToolOutput>;\n};\n\ntype PreparedToolCallContext = ToolCallContext & {\n [preparedToolInputSymbol]?: { owner: object; input: unknown };\n};\n\ntype ToolWithPreparedOwner = AnyTool & {\n [preparedToolOwnerSymbol]?: object;\n};\n\nexport function attachPreparedToolOwner<T extends AnyTool>(tool: T, owner: object): T {\n Object.defineProperty(tool, preparedToolOwnerSymbol, {\n configurable: false,\n enumerable: true,\n value: owner,\n writable: false,\n });\n return tool;\n}\n\nexport function preparedToolInput(\n context: ToolCallContext | undefined,\n owner: object,\n): { input: unknown } | undefined {\n if (context === undefined || !(preparedToolInputSymbol in context)) {\n return undefined;\n }\n const prepared = (context as PreparedToolCallContext)[preparedToolInputSymbol];\n return prepared?.owner === owner ? { input: prepared.input } : undefined;\n}\n\nexport function withoutPreparedToolInput(context: ToolCallContext): ToolCallContext {\n if (!(preparedToolInputSymbol in context)) {\n return context;\n }\n const { [preparedToolInputSymbol]: _prepared, ...publicContext } =\n context as PreparedToolCallContext;\n return publicContext;\n}\n\nexport function prepareToolCall(tool: AnyTool, args: string): PreparedToolCall {\n let rawInput: ReturnType<typeof parseToolArgs>;\n try {\n rawInput = parseToolArgs(args);\n } catch (error) {\n throw new ToolJsonError(`Invalid JSON arguments for tool ${tool.name}`, error);\n }\n\n let input: unknown;\n try {\n input = tool.parseInput === undefined ? rawInput : tool.parseInput(rawInput);\n } catch (error) {\n throw asToolCallError(tool.name, error);\n }\n\n return prepareToolCallFromInput(tool, input);\n}\n\nexport function prepareToolCallFromInput(tool: AnyTool, input: unknown): PreparedToolCall {\n return {\n input,\n async call(context) {\n try {\n const owner = (tool as ToolWithPreparedOwner)[preparedToolOwnerSymbol];\n return normalizeToolResultOutput(\n await tool.call(\n input,\n owner === undefined ? context : withPreparedToolInput(context, owner, input),\n ),\n );\n } catch (error) {\n throw asToolCallError(tool.name, error);\n }\n },\n };\n}\n\nfunction withPreparedToolInput(\n context: ToolCallContext,\n owner: object,\n input: unknown,\n): ToolCallContext {\n const preparedContext: PreparedToolCallContext = { ...context };\n Object.defineProperty(preparedContext, preparedToolInputSymbol, {\n configurable: false,\n enumerable: true,\n value: { owner, input },\n writable: false,\n });\n return preparedContext;\n}\n\nfunction asToolCallError(toolName: string, error: unknown): ToolCallError {\n if (error instanceof ToolCallError) {\n return error;\n }\n return error instanceof Error\n ? new ToolCallError(error.message, error)\n : new ToolCallError(`Tool ${toolName} failed`, error);\n}\n","import type { z } from \"zod\";\nimport { assertToolApprovalRequirement } from \"../internal/agent-runtime/approval-requirement\";\nimport {\n attachPreparedToolOwner,\n preparedToolInput,\n withoutPreparedToolInput,\n} from \"../internal/agent-runtime/prepared-tool-call\";\nimport { toProviderJsonSchema, type ZodSchema } from \"../schema/zod-schema\";\nimport type { Tool, ToolCallContext, ToolRequiresApproval } from \"./tool\";\n\nexport type CreateToolOptions<\n InputSchema extends ZodSchema,\n OutputSchema extends ZodSchema | undefined = undefined,\n Output = unknown,\n> = {\n name: string;\n description: string;\n inputSchema: InputSchema;\n outputSchema?: OutputSchema;\n requiresApproval?: ToolRequiresApproval<z.output<InputSchema>>;\n execute(\n args: z.output<InputSchema>,\n context: ToolCallContext,\n ): OutputSchema extends ZodSchema\n ? z.input<OutputSchema> | Promise<z.input<OutputSchema>>\n : Output | Promise<Output>;\n};\n\ntype CreateToolOutput<\n OutputSchema extends ZodSchema | undefined,\n Output,\n> = OutputSchema extends ZodSchema ? z.output<OutputSchema> : Output;\n\nexport function createTool<InputSchema extends ZodSchema, Output = unknown>(\n options: CreateToolOptions<InputSchema, undefined, Output> & { outputSchema?: undefined },\n): Tool<z.output<InputSchema>, Output>;\n\nexport function createTool<InputSchema extends ZodSchema, OutputSchema extends ZodSchema>(\n options: CreateToolOptions<InputSchema, OutputSchema>,\n): Tool<z.output<InputSchema>, z.output<OutputSchema>>;\n\nexport function createTool<\n InputSchema extends ZodSchema,\n OutputSchema extends ZodSchema | undefined = undefined,\n Output = unknown,\n>(\n options: CreateToolOptions<InputSchema, OutputSchema, Output>,\n): Tool<z.output<InputSchema>, CreateToolOutput<OutputSchema, Output>> {\n const { name, description, inputSchema, outputSchema, execute } = options;\n const requiresApproval = snapshotApprovalRequirement(options.requiresApproval);\n if (requiresApproval !== undefined) {\n assertToolApprovalRequirement(requiresApproval, { allowFunction: true });\n }\n const parameters = toProviderJsonSchema(inputSchema);\n const preparedInputOwner = {};\n const definition = () => ({\n name,\n description,\n parameters: globalThis.structuredClone(parameters),\n });\n const call = async (\n args: z.output<InputSchema>,\n context: ToolCallContext = {},\n ): Promise<CreateToolOutput<OutputSchema, Output>> => {\n const prepared = preparedToolInput(context, preparedInputOwner);\n const parsedArgs =\n prepared === undefined ? inputSchema.parse(args) : (prepared.input as z.output<InputSchema>);\n const executionContext = prepared === undefined ? context : withoutPreparedToolInput(context);\n const result = await execute(parsedArgs, executionContext);\n return (outputSchema === undefined ? result : outputSchema.parse(result)) as CreateToolOutput<\n OutputSchema,\n Output\n >;\n };\n const parseInput = (args: unknown): z.output<InputSchema> => inputSchema.parse(args);\n\n const tool: Tool<z.output<InputSchema>, CreateToolOutput<OutputSchema, Output>> = {\n name,\n definition,\n call,\n parseInput,\n };\n if (requiresApproval !== undefined) {\n Object.defineProperty(tool, \"requiresApproval\", {\n configurable: false,\n enumerable: true,\n value: requiresApproval,\n writable: false,\n });\n }\n return attachPreparedToolOwner(tool, preparedInputOwner);\n}\n\nfunction snapshotApprovalRequirement<Args>(\n requirement: ToolRequiresApproval<Args> | undefined,\n): ToolRequiresApproval<Args> | undefined {\n return typeof requirement === \"object\" && requirement !== null\n ? Object.freeze({ ...requirement })\n : requirement;\n}\n","import type { VectorMetadata, VectorMetadataValue } from \"../embeddings\";\nimport type { VectorFilter } from \"./types\";\n\nexport type { VectorFilter } from \"./types\";\n\nexport const vectorFilter = {\n eq(key: string, value: VectorMetadataValue): VectorFilter {\n return { type: \"eq\", key, value };\n },\n gt(key: string, value: VectorMetadataValue): VectorFilter {\n return { type: \"gt\", key, value };\n },\n lt(key: string, value: VectorMetadataValue): VectorFilter {\n return { type: \"lt\", key, value };\n },\n and(left: VectorFilter, right: VectorFilter): VectorFilter {\n return { type: \"and\", filters: [left, right] };\n },\n or(left: VectorFilter, right: VectorFilter): VectorFilter {\n return { type: \"or\", filters: [left, right] };\n },\n};\n\nexport function matchesVectorFilter(\n metadata: VectorMetadata | undefined,\n filter: VectorFilter | undefined,\n): boolean {\n if (filter === undefined) {\n return true;\n }\n if (metadata === undefined) {\n return false;\n }\n\n switch (filter.type) {\n case \"eq\":\n return metadata[filter.key] === filter.value;\n case \"gt\":\n return compare(metadata[filter.key], filter.value) > 0;\n case \"lt\":\n return compare(metadata[filter.key], filter.value) < 0;\n case \"and\":\n return (\n matchesVectorFilter(metadata, filter.filters[0]) &&\n matchesVectorFilter(metadata, filter.filters[1])\n );\n case \"or\":\n return (\n matchesVectorFilter(metadata, filter.filters[0]) ||\n matchesVectorFilter(metadata, filter.filters[1])\n );\n }\n}\n\nfunction compare(left: VectorMetadataValue | undefined, right: VectorMetadataValue): number {\n if (typeof left === \"number\" && typeof right === \"number\") {\n return left - right;\n }\n if (typeof left === \"string\" && typeof right === \"string\") {\n return left.localeCompare(right);\n }\n if (typeof left === \"boolean\" && typeof right === \"boolean\") {\n return Number(left) - Number(right);\n }\n return 0;\n}\n","import type { LshOptions } from \"./types\";\n\nexport type { LshOptions } from \"./types\";\n\nexport class LshIndex {\n private readonly hyperplanes: number[][];\n private readonly tables: Array<Map<string, Set<string>>>;\n\n constructor(\n dimensions: number,\n private readonly options: LshOptions,\n ) {\n const rng = seededRandom(options.seed ?? 42);\n this.hyperplanes = [];\n for (let index = 0; index < options.numTables * options.numHyperplanes; index += 1) {\n const plane = Array.from({ length: dimensions }, () => rng() * 2 - 1);\n const norm = Math.sqrt(plane.reduce((sum, value) => sum + value ** 2, 0));\n this.hyperplanes.push(norm === 0 ? plane : plane.map((value) => value / norm));\n }\n this.tables = Array.from({ length: options.numTables }, () => new Map());\n }\n\n insert(id: string, vector: number[]): void {\n for (let table = 0; table < this.options.numTables; table += 1) {\n const hash = this.hash(vector, table);\n const bucket = this.tables[table]?.get(hash) ?? new Set<string>();\n bucket.add(id);\n this.tables[table]?.set(hash, bucket);\n }\n }\n\n query(vector: number[]): Set<string> {\n const candidates = new Set<string>();\n for (let table = 0; table < this.options.numTables; table += 1) {\n const hash = this.hash(vector, table);\n for (const id of this.tables[table]?.get(hash) ?? []) {\n candidates.add(id);\n }\n }\n return candidates;\n }\n\n private hash(vector: number[], table: number): string {\n let hash = \"\";\n const start = table * this.options.numHyperplanes;\n for (let offset = 0; offset < this.options.numHyperplanes; offset += 1) {\n const plane = this.hyperplanes[start + offset] as number[];\n const dot = vector.reduce((sum, value, index) => sum + value * (plane[index] ?? 0), 0);\n hash += dot >= 0 ? \"1\" : \"0\";\n }\n return hash;\n }\n}\n\nfunction seededRandom(seed: number): () => number {\n let state = seed >>> 0;\n return () => {\n state = (state * 1664525 + 1013904223) >>> 0;\n return state / 0x100000000;\n };\n}\n","import { embedSparseQuery, embedText, type VectorMetadata } from \"../embeddings\";\nimport { throwIfAborted } from \"../internal/abort\";\nimport { assertFiniteMinScore, assertPositiveSearchLimit } from \"../internal/vector-search-options\";\nimport { type ResolvedRetryOptions, resolveRetryOptions, runWithRetries } from \"../retry\";\nimport type {\n RetrieveDocumentsOptions,\n RetrieveHybridDocumentsOptions,\n VectorSearchResult,\n} from \"./types\";\n\nexport function retrieveDocuments<T, Metadata extends VectorMetadata = VectorMetadata>(\n options: RetrieveDocumentsOptions<T, Metadata>,\n): Promise<Array<VectorSearchResult<T, Metadata>>>;\nexport function retrieveDocuments<T, Metadata extends VectorMetadata = VectorMetadata>(\n options: RetrieveHybridDocumentsOptions<T, Metadata>,\n): Promise<Array<VectorSearchResult<T, Metadata>>>;\nexport async function retrieveDocuments<T, Metadata extends VectorMetadata = VectorMetadata>(\n options: RetrieveDocumentsOptions<T, Metadata> | RetrieveHybridDocumentsOptions<T, Metadata>,\n): Promise<Array<VectorSearchResult<T, Metadata>>> {\n assertPositiveSearchLimit(options.topK);\n assertFiniteMinScore(options.minScore);\n throwIfAborted(options.abortSignal);\n const retries = resolveRetries(options.retries);\n const search = (operation: () => Promise<Array<VectorSearchResult<T, Metadata>>>) =>\n runWithRetries(operation, retries, {\n streaming: false,\n abortSignal: options.abortSignal,\n });\n\n if (\"model\" in options && options.model !== undefined) {\n const { embedding } = await embedText({\n model: options.model,\n text: options.query,\n retries: options.retries,\n abortSignal: options.abortSignal,\n });\n return deduplicateResults(\n await search(() =>\n options.store.search({\n vector: embedding.vector,\n topK: options.topK,\n minScore: options.minScore,\n filter: options.filter,\n abortSignal: options.abortSignal,\n }),\n ),\n );\n }\n\n const [{ embedding: dense }, { embedding: sparse }] = await Promise.all([\n embedText({\n model: options.models.dense,\n text: options.query,\n retries: options.retries,\n abortSignal: options.abortSignal,\n }),\n embedSparseQuery({\n model: options.models.sparse,\n query: options.query,\n retries: options.retries,\n abortSignal: options.abortSignal,\n }),\n ]);\n return deduplicateResults(\n await search(() =>\n options.store.searchHybrid({\n vector: dense.vector,\n sparseVector: sparse.vector,\n fusion: options.fusion,\n topK: options.topK,\n minScore: options.minScore,\n filter: options.filter,\n abortSignal: options.abortSignal,\n }),\n ),\n );\n}\n\nfunction deduplicateResults<T, Metadata extends VectorMetadata>(\n results: Array<VectorSearchResult<T, Metadata>>,\n): Array<VectorSearchResult<T, Metadata>> {\n const bestById = new Map<string, VectorSearchResult<T, Metadata>>();\n for (const result of results) {\n const current = bestById.get(result.id);\n if (current === undefined || result.score > current.score) bestById.set(result.id, result);\n }\n return [...bestById.values()].sort((left, right) => right.score - left.score);\n}\n\nfunction resolveRetries(\n setting: RetrieveDocumentsOptions<unknown>[\"retries\"],\n): ResolvedRetryOptions | undefined {\n return setting === undefined || setting === false ? undefined : resolveRetryOptions(setting);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS;;;ACAX,SAAS,0BAA0B,OAAe,OAAO,QAAgB;AAC9E,MAAI,CAAC,OAAO,cAAc,KAAK,KAAK,SAAS,GAAG;AAC9C,UAAM,IAAI,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,UAAM,QAAQ,iBAAiB,eAAe,QAAQ,UAAU,MAAM;AACtE,WAAO,SAAS,SAAY,QAAQ,KAAK,IAAI,MAAM,KAAK;AAAA,EAC1D;AACA,SAAO;AACT;AAEA,SAAS,2BACP,mBACA,WACA,IACQ;AACR,qBAAmB,UAAU,QAAQ,EAAE;AACvC,MAAI,sBAAsB,OAAW,QAAO,UAAU,OAAO;AAC7D,MAAI,UAAU,OAAO,WAAW,mBAAmB;AACjD,UAAM,IAAI;AAAA,MACR,uCAAuC,iBAAiB,4BAA4B,UAAU,OAAO,MAAM,QAAQ,EAAE;AAAA,IACvH;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,mBAAmB,QAAkB,IAAkB;AAC9D,MAAI,OAAO,WAAW,EAAG,OAAM,IAAI,UAAU,cAAc,EAAE,qBAAqB;AAClF,MAAI,CAAC,OAAO,MAAM,OAAO,QAAQ,GAAG;AAClC,UAAM,IAAI,UAAU,cAAc,EAAE,oCAAoC;AAAA,EAC1E;AACF;","names":["throwIfAborted"]}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|