@anvia/core 0.11.2 → 0.11.3

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.
Files changed (62) hide show
  1. package/dist/agent/index.d.ts +11 -11
  2. package/dist/agent/index.js +6 -6
  3. package/dist/{agent-Bq2KtSaw.d.ts → agent-Bcpuodu2.d.ts} +7 -7
  4. package/dist/audio-generation/index.d.ts +3 -3
  5. package/dist/{chunk-R75SGHCI.js → chunk-2GXGB6U5.js} +5 -5
  6. package/dist/{chunk-WJO6NVE2.js → chunk-5LFGEMIW.js} +1 -1
  7. package/dist/{chunk-WJO6NVE2.js.map → chunk-5LFGEMIW.js.map} +1 -1
  8. package/dist/{chunk-SISUMRUX.js → chunk-7CQAERL3.js} +12 -6
  9. package/dist/chunk-7CQAERL3.js.map +1 -0
  10. package/dist/{chunk-X3SWV6W6.js → chunk-FV5B4SGK.js} +2 -2
  11. package/dist/{chunk-DOS77JZC.js → chunk-JNO4AR7Q.js} +2 -2
  12. package/dist/{chunk-N6REB3DH.js → chunk-MLMXQ2OV.js} +4 -4
  13. package/dist/{chunk-62RUYGMM.js → chunk-NI637AGP.js} +3 -3
  14. package/dist/{chunk-5G3VME2D.js → chunk-SRBW3LD7.js} +2 -2
  15. package/dist/chunk-SRBW3LD7.js.map +1 -0
  16. package/dist/completion/index.d.ts +8 -6
  17. package/dist/completion/index.js +2 -2
  18. package/dist/{create-completion-BEbtU5pX.d.ts → create-completion-Y6YsYbQB.d.ts} +2 -2
  19. package/dist/evals/index.d.ts +8 -8
  20. package/dist/evals/index.js +7 -7
  21. package/dist/extractor/index.d.ts +8 -8
  22. package/dist/extractor/index.js +7 -7
  23. package/dist/hooks/index.d.ts +3 -3
  24. package/dist/image-generation/index.d.ts +3 -3
  25. package/dist/{index-CTNzKidE.d.ts → index-CD9jb9Or.d.ts} +2 -2
  26. package/dist/index.d.ts +12 -12
  27. package/dist/index.js +7 -7
  28. package/dist/internal/agent.d.ts +8 -8
  29. package/dist/internal/agent.js +5 -5
  30. package/dist/loaders/index.d.ts +1 -1
  31. package/dist/mcp/index.d.ts +4 -4
  32. package/dist/memory/index.d.ts +3 -3
  33. package/dist/{middleware-CG7l0rR3.d.ts → middleware-ByyL6Rj0.d.ts} +3 -3
  34. package/dist/model-listing/index.d.ts +2 -1
  35. package/dist/observability/index.d.ts +3 -3
  36. package/dist/pipeline/index.d.ts +8 -8
  37. package/dist/request/index.d.ts +8 -8
  38. package/dist/request/index.js +4 -4
  39. package/dist/skills/index.d.ts +4 -4
  40. package/dist/skills/index.js +2 -2
  41. package/dist/{think-tool-B8Rqw2i_.d.ts → think-tool-B065hm73.d.ts} +1 -1
  42. package/dist/tool/index.d.ts +5 -5
  43. package/dist/tool/index.js +2 -2
  44. package/dist/{tool-BLypI31e.d.ts → tool-B8K543oQ.d.ts} +1 -1
  45. package/dist/transcription/index.d.ts +3 -3
  46. package/dist/{types-CIwm9p4w.d.ts → types-7F_IKQQW.d.ts} +2 -2
  47. package/dist/{types-D-YTJdLj.d.ts → types-BzUuhjKr.d.ts} +1 -1
  48. package/dist/{types-CCxnnJjU.d.ts → types-CGML74sE.d.ts} +1 -1
  49. package/dist/{types-CNfjQ5rB.d.ts → types-CqG6d7Ce.d.ts} +1 -1
  50. package/dist/{types-KKjICcrA.d.ts → types-Pl4PFQWL.d.ts} +1 -1
  51. package/dist/{types-C8loR4il.d.ts → types-q9G7Bvwl.d.ts} +8 -8
  52. package/dist/ui/index.d.ts +1 -1
  53. package/dist/ui/index.js +2 -2
  54. package/dist/vector-store/index.d.ts +4 -4
  55. package/package.json +1 -1
  56. package/dist/chunk-5G3VME2D.js.map +0 -1
  57. package/dist/chunk-SISUMRUX.js.map +0 -1
  58. /package/dist/{chunk-R75SGHCI.js.map → chunk-2GXGB6U5.js.map} +0 -0
  59. /package/dist/{chunk-X3SWV6W6.js.map → chunk-FV5B4SGK.js.map} +0 -0
  60. /package/dist/{chunk-DOS77JZC.js.map → chunk-JNO4AR7Q.js.map} +0 -0
  61. /package/dist/{chunk-N6REB3DH.js.map → chunk-MLMXQ2OV.js.map} +0 -0
  62. /package/dist/{chunk-62RUYGMM.js.map → chunk-NI637AGP.js.map} +0 -0
@@ -1,15 +1,15 @@
1
- import { D as DynamicContextOptions, a as DynamicToolOptions, b as AgentEventStore, c as AgentEventStoreOptions, A as Agent } from '../agent-Bq2KtSaw.js';
2
- export { d as AgentEventAppendInput, e as AgentEventRecord, f as AgentEventStoreInclude, g as AgentSession, h as AgentToolOptions } from '../agent-Bq2KtSaw.js';
1
+ import { D as DynamicContextOptions, a as DynamicToolOptions, b as AgentEventStore, c as AgentEventStoreOptions, A as Agent } from '../agent-Bcpuodu2.js';
2
+ export { d as AgentEventAppendInput, e as AgentEventRecord, f as AgentEventStoreInclude, g as AgentSession, h as AgentToolOptions } from '../agent-Bcpuodu2.js';
3
3
  import { Z as ZodSchema } from '../zod-schema-C7F4clpm.js';
4
- import { C as CompletionModel, e as JsonValue, n as ToolChoice } from '../types-C8loR4il.js';
5
- import { P as PromptHook } from '../types-CCxnnJjU.js';
6
- import { a as McpServer } from '../types-CIwm9p4w.js';
7
- import { M as MemoryStore, a as MemoryOptions } from '../types-CNfjQ5rB.js';
8
- import { b as AgentObserver, O as ObserveOptions } from '../index-CTNzKidE.js';
9
- import { a as SkillSet } from '../types-D-YTJdLj.js';
10
- import { k as ToolSearchDocument, l as ToolSet, A as AgentMiddleware, e as ToolMiddleware } from '../middleware-CG7l0rR3.js';
11
- import { A as AnyTool, e as ToolApprovalsOptions } from '../tool-BLypI31e.js';
12
- import { a as VectorSearchIndex } from '../types-KKjICcrA.js';
4
+ import { C as CompletionModel, e as JsonValue, n as ToolChoice } from '../types-q9G7Bvwl.js';
5
+ import { P as PromptHook } from '../types-CGML74sE.js';
6
+ import { a as McpServer } from '../types-7F_IKQQW.js';
7
+ import { M as MemoryStore, a as MemoryOptions } from '../types-CqG6d7Ce.js';
8
+ import { b as AgentObserver, O as ObserveOptions } from '../index-CD9jb9Or.js';
9
+ import { a as SkillSet } from '../types-BzUuhjKr.js';
10
+ import { k as ToolSearchDocument, l as ToolSet, A as AgentMiddleware, e as ToolMiddleware } from '../middleware-ByyL6Rj0.js';
11
+ import { A as AnyTool, e as ToolApprovalsOptions } from '../tool-B8K543oQ.js';
12
+ import { a as VectorSearchIndex } from '../types-Pl4PFQWL.js';
13
13
  import 'zod';
14
14
  import '@modelcontextprotocol/sdk/client/sse.js';
15
15
  import '@modelcontextprotocol/sdk/client/stdio.js';
@@ -1,17 +1,17 @@
1
1
  import {
2
2
  AgentBuilder
3
- } from "../chunk-62RUYGMM.js";
4
- import "../chunk-N6REB3DH.js";
5
- import "../chunk-SISUMRUX.js";
3
+ } from "../chunk-NI637AGP.js";
4
+ import "../chunk-MLMXQ2OV.js";
5
+ import "../chunk-7CQAERL3.js";
6
6
  import "../chunk-YK4WAAS4.js";
7
7
  import "../chunk-XUUY2L2D.js";
8
- import "../chunk-X3SWV6W6.js";
8
+ import "../chunk-FV5B4SGK.js";
9
9
  import "../chunk-5EDHXYH5.js";
10
10
  import "../chunk-M6RPFHG7.js";
11
11
  import "../chunk-JS5MGVNM.js";
12
12
  import "../chunk-OIMLU4SF.js";
13
- import "../chunk-5G3VME2D.js";
14
- import "../chunk-WJO6NVE2.js";
13
+ import "../chunk-SRBW3LD7.js";
14
+ import "../chunk-5LFGEMIW.js";
15
15
  import "../chunk-WQKHFADH.js";
16
16
  import "../chunk-NPZDYOE6.js";
17
17
  import "../chunk-MMHG7WAM.js";
@@ -1,10 +1,10 @@
1
- import { C as CompletionModel, M as Message, D as Document, e as JsonValue, n as ToolChoice, J as JsonObject } from './types-C8loR4il.js';
2
- import { P as PromptHook } from './types-CCxnnJjU.js';
3
- import { c as MemoryContext, e as MemoryRegistration, S as SessionOptions } from './types-CNfjQ5rB.js';
4
- import { c as AgentTraceOptions, P as PromptResponse, a as AgentStreamEvent, d as AgentObserverRegistration } from './index-CTNzKidE.js';
5
- import { e as ToolApprovalsOptions, T as Tool, A as AnyTool, f as ToolCallContext, N as NormalizedToolOutput } from './tool-BLypI31e.js';
6
- import { A as AgentMiddleware, e as ToolMiddleware, k as ToolSearchDocument, l as ToolSet } from './middleware-CG7l0rR3.js';
7
- import { V as VectorFilter, c as VectorSearchResult, a as VectorSearchIndex } from './types-KKjICcrA.js';
1
+ import { C as CompletionModel, M as Message, D as Document, e as JsonValue, n as ToolChoice, J as JsonObject } from './types-q9G7Bvwl.js';
2
+ import { P as PromptHook } from './types-CGML74sE.js';
3
+ import { c as MemoryContext, e as MemoryRegistration, S as SessionOptions } from './types-CqG6d7Ce.js';
4
+ import { c as AgentTraceOptions, P as PromptResponse, a as AgentStreamEvent, d as AgentObserverRegistration } from './index-CD9jb9Or.js';
5
+ import { e as ToolApprovalsOptions, T as Tool, A as AnyTool, f as ToolCallContext, N as NormalizedToolOutput } from './tool-B8K543oQ.js';
6
+ import { A as AgentMiddleware, e as ToolMiddleware, k as ToolSearchDocument, l as ToolSet } from './middleware-ByyL6Rj0.js';
7
+ import { V as VectorFilter, c as VectorSearchResult, a as VectorSearchIndex } from './types-Pl4PFQWL.js';
8
8
 
9
9
  declare class PromptRequest<M extends CompletionModel = CompletionModel> {
10
10
  private readonly agent;
@@ -1,4 +1,4 @@
1
- import { e as JsonValue } from '../types-C8loR4il.js';
1
+ import { e as JsonValue } from '../types-q9G7Bvwl.js';
2
2
 
3
3
  type AudioGenerationRequest = {
4
4
  text: string;
@@ -11,9 +11,9 @@ type AudioGenerationResponse<RawResponse = unknown> = {
11
11
  mediaType?: string | undefined;
12
12
  rawResponse: RawResponse;
13
13
  };
14
- interface AudioGenerationModel<RawResponse = unknown> {
14
+ interface AudioGenerationModel<RawResponse = unknown, ModelName extends string = string> {
15
15
  readonly provider?: string | undefined;
16
- readonly defaultModel?: string | undefined;
16
+ readonly defaultModel?: ModelName | undefined;
17
17
  audioGeneration(request: AudioGenerationRequest): Promise<AudioGenerationResponse<RawResponse>>;
18
18
  }
19
19
 
@@ -1,20 +1,20 @@
1
1
  import {
2
2
  AgentBuilder
3
- } from "./chunk-62RUYGMM.js";
3
+ } from "./chunk-NI637AGP.js";
4
4
  import {
5
5
  extractRagText
6
- } from "./chunk-SISUMRUX.js";
6
+ } from "./chunk-7CQAERL3.js";
7
7
  import {
8
8
  createTool
9
9
  } from "./chunk-5EDHXYH5.js";
10
10
  import {
11
11
  CompletionRequestBuilder
12
- } from "./chunk-5G3VME2D.js";
12
+ } from "./chunk-SRBW3LD7.js";
13
13
  import {
14
14
  CompletionCapabilityError,
15
15
  Message,
16
16
  Usage
17
- } from "./chunk-WJO6NVE2.js";
17
+ } from "./chunk-5LFGEMIW.js";
18
18
 
19
19
  // src/extractor/extractor.ts
20
20
  var SUBMIT_TOOL_NAME = "submit";
@@ -138,4 +138,4 @@ export {
138
138
  Extractor,
139
139
  ExtractorBuilder
140
140
  };
141
- //# sourceMappingURL=chunk-R75SGHCI.js.map
141
+ //# sourceMappingURL=chunk-2GXGB6U5.js.map
@@ -231,4 +231,4 @@ export {
231
231
  assertCompletionRequestSupported,
232
232
  textFromAssistantContent
233
233
  };
234
- //# sourceMappingURL=chunk-WJO6NVE2.js.map
234
+ //# sourceMappingURL=chunk-5LFGEMIW.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/completion/types.ts"],"sourcesContent":["export type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonObject | JsonValue[];\nexport type JsonObject = { [key: string]: JsonValue | undefined };\n\nexport type Document = {\n id: string;\n text: string;\n additionalProps?: Record<string, string>;\n};\n\nexport type Text = {\n type: \"text\";\n text: string;\n signature?: string;\n};\n\nexport type ImageDetail = \"auto\" | \"low\" | \"high\";\n\nexport type ImageContent = {\n type: \"image\";\n source:\n | {\n type: \"url\";\n url: string;\n }\n | {\n type: \"base64\";\n data: string;\n mediaType: string;\n };\n detail?: ImageDetail;\n};\n\nexport type DocumentContent = {\n type: \"document\";\n source:\n | {\n type: \"url\";\n url: string;\n mediaType: string;\n filename?: string;\n }\n | {\n type: \"base64\";\n data: string;\n mediaType: string;\n filename?: string;\n }\n | {\n type: \"text\";\n text: string;\n mediaType?: string;\n filename?: string;\n };\n};\n\nexport type Reasoning = {\n type: \"reasoning\";\n text: string;\n id?: string;\n content?: ReasoningContent[];\n};\n\nexport type ReasoningContent =\n | {\n type: \"text\";\n text: string;\n signature?: string;\n }\n | {\n type: \"summary\";\n text: string;\n }\n | {\n type: \"encrypted\";\n data: string;\n }\n | {\n type: \"redacted\";\n data: string;\n };\n\nexport type ReasoningContentType = ReasoningContent[\"type\"];\n\nexport type ToolFunction = {\n name: string;\n arguments: JsonValue;\n};\n\nexport type ToolCall = {\n type: \"tool_call\";\n id: string;\n callId?: string;\n function: ToolFunction;\n signature?: string;\n additionalParams?: JsonValue;\n};\n\nexport type ToolResultContent =\n | { type: \"text\"; text: string }\n | { type: \"image\"; data: string; mediaType?: string };\n\nexport type ToolResult = {\n type: \"tool_result\";\n id: string;\n callId?: string;\n content: ToolResultContent[];\n};\n\nexport type UserContent = Text | ImageContent | DocumentContent;\nexport type AssistantContent = Text | ToolCall | Reasoning | ImageContent;\nexport type ToolContent = ToolResult;\n\nexport type SystemMessage = {\n role: \"system\";\n content: string;\n};\n\nexport type UserMessage = {\n role: \"user\";\n content: UserContent[];\n};\n\nexport type AssistantMessage = {\n role: \"assistant\";\n id?: string;\n content: AssistantContent[];\n};\n\nexport type ToolMessage = {\n role: \"tool\";\n content: ToolContent[];\n};\n\nexport type Message = SystemMessage | UserMessage | AssistantMessage | ToolMessage;\n\nexport const UserContent = {\n text(text: string): Text {\n return { type: \"text\", text };\n },\n imageUrl(url: string, options: { detail?: ImageDetail } = {}): ImageContent {\n const image: ImageContent = { type: \"image\", source: { type: \"url\", url } };\n if (options.detail !== undefined) {\n image.detail = options.detail;\n }\n return image;\n },\n imageBase64(\n data: string,\n mediaType: string,\n options: { detail?: ImageDetail } = {},\n ): ImageContent {\n const image: ImageContent = {\n type: \"image\",\n source: { type: \"base64\", data, mediaType },\n };\n if (options.detail !== undefined) {\n image.detail = options.detail;\n }\n return image;\n },\n documentUrl(\n url: string,\n mediaType: string,\n options: { filename?: string | undefined } = {},\n ): DocumentContent {\n return {\n type: \"document\",\n source:\n options.filename === undefined\n ? { type: \"url\", url, mediaType }\n : { type: \"url\", url, mediaType, filename: options.filename },\n };\n },\n documentBase64(\n data: string,\n mediaType: string,\n options: { filename?: string | undefined } = {},\n ): DocumentContent {\n return {\n type: \"document\",\n source:\n options.filename === undefined\n ? { type: \"base64\", data, mediaType }\n : { type: \"base64\", data, mediaType, filename: options.filename },\n };\n },\n documentText(text: string): Text {\n return { type: \"text\", text };\n },\n};\n\nexport const ToolContent = {\n toolResult(id: string, content: string | ToolResultContent[], callId?: string): ToolResult {\n const normalized =\n typeof content === \"string\" ? [{ type: \"text\" as const, text: content }] : content;\n return callId === undefined\n ? { type: \"tool_result\", id, content: normalized }\n : { type: \"tool_result\", id, callId, content: normalized };\n },\n};\n\nexport function serializeToolResultOutput(output: unknown): string {\n if (typeof output === \"string\") {\n return output;\n }\n\n try {\n const serialized = JSON.stringify(output);\n return serialized === undefined ? String(output) : serialized;\n } catch {\n return String(output);\n }\n}\n\nexport function isToolResultContentArray(value: unknown): value is ToolResultContent[] {\n return (\n Array.isArray(value) &&\n value.length > 0 &&\n value.every((item) => {\n if (typeof item !== \"object\" || item === null || !(\"type\" in item)) {\n return false;\n }\n if (item.type === \"text\") {\n return \"text\" in item && typeof item.text === \"string\";\n }\n if (item.type === \"image\") {\n return (\n \"data\" in item &&\n typeof item.data === \"string\" &&\n (!(\"mediaType\" in item) ||\n item.mediaType === undefined ||\n typeof item.mediaType === \"string\")\n );\n }\n return false;\n })\n );\n}\n\nexport const AssistantContent = {\n text(text: string): Text {\n return { type: \"text\", text };\n },\n imageUrl(url: string, options: { detail?: ImageDetail } = {}): ImageContent {\n const image: ImageContent = { type: \"image\", source: { type: \"url\", url } };\n if (options.detail !== undefined) {\n image.detail = options.detail;\n }\n return image;\n },\n imageBase64(\n data: string,\n mediaType: string,\n options: { detail?: ImageDetail } = {},\n ): ImageContent {\n const image: ImageContent = {\n type: \"image\",\n source: { type: \"base64\", data, mediaType },\n };\n if (options.detail !== undefined) {\n image.detail = options.detail;\n }\n return image;\n },\n reasoning(text: string, id?: string): Reasoning {\n return id === undefined ? { type: \"reasoning\", text } : { type: \"reasoning\", text, id };\n },\n reasoningFromContent(content: ReasoningContent[], id?: string): Reasoning {\n const text = reasoningDisplayText(content);\n const reasoning: Reasoning = { type: \"reasoning\", text, content };\n return id === undefined ? reasoning : { ...reasoning, id };\n },\n reasoningSummary(text: string, id?: string): Reasoning {\n return AssistantContent.reasoningFromContent([{ type: \"summary\", text }], id);\n },\n reasoningEncrypted(data: string, id?: string): Reasoning {\n return AssistantContent.reasoningFromContent([{ type: \"encrypted\", data }], id);\n },\n reasoningRedacted(data: string, id?: string): Reasoning {\n return AssistantContent.reasoningFromContent([{ type: \"redacted\", data }], id);\n },\n toolCall(id: string, name: string, args: JsonValue, callId?: string): ToolCall {\n const base: ToolCall = {\n type: \"tool_call\",\n id,\n function: {\n name,\n arguments: args,\n },\n };\n return callId === undefined ? base : { ...base, callId };\n },\n};\n\nexport function reasoningDisplayText(reasoning: Reasoning | ReasoningContent[]): string {\n const content = Array.isArray(reasoning) ? reasoning : reasoning.content;\n if (content === undefined) {\n return Array.isArray(reasoning) ? \"\" : reasoning.text;\n }\n return content\n .flatMap((item) => {\n if (item.type === \"text\" || item.type === \"summary\") {\n return [item.text];\n }\n return [];\n })\n .join(\"\");\n}\n\nexport const Message = {\n system(content: string): Message {\n return { role: \"system\", content };\n },\n user(content: string | UserContent[]): Message {\n return {\n role: \"user\",\n content: typeof content === \"string\" ? [UserContent.text(content)] : content,\n };\n },\n assistant(content: string | AssistantContent[], id?: string): Message {\n const normalized = typeof content === \"string\" ? [AssistantContent.text(content)] : content;\n return id === undefined\n ? { role: \"assistant\", content: normalized }\n : { role: \"assistant\", id, content: normalized };\n },\n tool(content: ToolContent | ToolContent[]): Message {\n return {\n role: \"tool\",\n content: Array.isArray(content) ? content : [content],\n };\n },\n toolResult(id: string, output: unknown, options: { callId?: string | undefined } = {}): Message {\n const content = isToolResultContentArray(output) ? output : serializeToolResultOutput(output);\n return Message.tool(ToolContent.toolResult(id, content, options.callId));\n },\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\nexport type Usage = {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n cachedInputTokens: number;\n cacheCreationInputTokens: number;\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 return {\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 },\n};\n\nexport type CompletionRequest = {\n model?: string;\n instructions?: string;\n chatHistory: Message[];\n documents: Document[];\n tools: ToolDefinition[];\n temperature?: number;\n maxTokens?: number;\n toolChoice?: ToolChoice;\n additionalParams?: JsonValue;\n outputSchema?: JsonObject;\n};\n\nexport type CompletionResponse<RawResponse = unknown> = {\n choice: AssistantContent[];\n usage: Usage;\n rawResponse: RawResponse;\n messageId?: string;\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};\n\nexport interface CompletionModel<RawResponse = unknown> {\n readonly provider: string;\n readonly defaultModel: string;\n readonly capabilities: CompletionModelCapabilities;\n traceRequest?(\n request: CompletionRequest,\n options?: { stream?: boolean | undefined },\n ): JsonObject | undefined;\n completion(request: CompletionRequest): Promise<CompletionResponse<RawResponse>>;\n}\n\nexport type CompletionStreamEvent<RawResponse = unknown> =\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 signature?: string;\n }\n | {\n type: \"tool_call\";\n toolCall: ToolCall;\n }\n | {\n type: \"message_id\";\n id: string;\n }\n | {\n type: \"final\";\n response: CompletionResponse<RawResponse>;\n }\n | {\n type: \"error\";\n error: unknown;\n };\n\nexport interface StreamingCompletionModel<RawResponse = unknown>\n extends CompletionModel<RawResponse> {\n streamCompletion(request: CompletionRequest): AsyncIterable<CompletionStreamEvent<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}:${request.model ?? model.defaultModel}`;\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.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: AssistantContent[]): 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\" ? false : 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\"\n ? message.content.some(\n (content) => content.type === \"document\" && content.source.type !== \"text\",\n )\n : false,\n );\n}\n"],"mappings":";AAwIO,IAAM,cAAc;AAAA,EACzB,KAAK,MAAoB;AACvB,WAAO,EAAE,MAAM,QAAQ,KAAK;AAAA,EAC9B;AAAA,EACA,SAAS,KAAa,UAAoC,CAAC,GAAiB;AAC1E,UAAM,QAAsB,EAAE,MAAM,SAAS,QAAQ,EAAE,MAAM,OAAO,IAAI,EAAE;AAC1E,QAAI,QAAQ,WAAW,QAAW;AAChC,YAAM,SAAS,QAAQ;AAAA,IACzB;AACA,WAAO;AAAA,EACT;AAAA,EACA,YACE,MACA,WACA,UAAoC,CAAC,GACvB;AACd,UAAM,QAAsB;AAAA,MAC1B,MAAM;AAAA,MACN,QAAQ,EAAE,MAAM,UAAU,MAAM,UAAU;AAAA,IAC5C;AACA,QAAI,QAAQ,WAAW,QAAW;AAChC,YAAM,SAAS,QAAQ;AAAA,IACzB;AACA,WAAO;AAAA,EACT;AAAA,EACA,YACE,KACA,WACA,UAA6C,CAAC,GAC7B;AACjB,WAAO;AAAA,MACL,MAAM;AAAA,MACN,QACE,QAAQ,aAAa,SACjB,EAAE,MAAM,OAAO,KAAK,UAAU,IAC9B,EAAE,MAAM,OAAO,KAAK,WAAW,UAAU,QAAQ,SAAS;AAAA,IAClE;AAAA,EACF;AAAA,EACA,eACE,MACA,WACA,UAA6C,CAAC,GAC7B;AACjB,WAAO;AAAA,MACL,MAAM;AAAA,MACN,QACE,QAAQ,aAAa,SACjB,EAA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AU,gCAAgC;AAAA,EACnF;AAEA,MAAI,CAAC,aAAa,iBAAiB,4BAA4B,OAAO,GAAG;AACvE,UAAM,IAAI,0BAA0B,GAAG,UAAU,wCAAwC;AAAA,EAC3F;AACF;AAEO,SAAS,yBAAyB,SAAqC;AAC5E,SAAO,QAAQ,QAAQ,CAAC,SAAU,KAAK,SAAS,SAAS,CAAC,KAAK,IAAI,IAAI,CAAC,CAAE,EAAE,KAAK,IAAI;AACvF;AAEA,SAAS,qBAAqB,SAAqC;AACjE,SAAO,QAAQ,YAAY;AAAA,IAAK,CAAC,YAC/B,QAAQ,SAAS,WAAW,QAAQ,QAAQ,QAAQ,KAAK,CAAC,YAAY,QAAQ,SAAS,OAAO;AAAA,EAChG;AACF;AAEA,SAAS,4BAA4B,SAAqC;AACxE,SAAO,QAAQ,YAAY;AAAA,IAAK,CAAC,YAC/B,QAAQ,SAAS,SACb,QAAQ,QAAQ;AAAA,MACd,CAAC,YAAY,QAAQ,SAAS,cAAc,QAAQ,OAAO,SAAS;AAAA,IACtE,IACA;AAAA,EACN;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/completion/types.ts"],"sourcesContent":["export type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonObject | JsonValue[];\nexport type JsonObject = { [key: string]: JsonValue | undefined };\n\nexport type Document = {\n id: string;\n text: string;\n additionalProps?: Record<string, string>;\n};\n\nexport type Text = {\n type: \"text\";\n text: string;\n signature?: string;\n};\n\nexport type ImageDetail = \"auto\" | \"low\" | \"high\";\n\nexport type ImageContent = {\n type: \"image\";\n source:\n | {\n type: \"url\";\n url: string;\n }\n | {\n type: \"base64\";\n data: string;\n mediaType: string;\n };\n detail?: ImageDetail;\n};\n\nexport type DocumentContent = {\n type: \"document\";\n source:\n | {\n type: \"url\";\n url: string;\n mediaType: string;\n filename?: string;\n }\n | {\n type: \"base64\";\n data: string;\n mediaType: string;\n filename?: string;\n }\n | {\n type: \"text\";\n text: string;\n mediaType?: string;\n filename?: string;\n };\n};\n\nexport type Reasoning = {\n type: \"reasoning\";\n text: string;\n id?: string;\n content?: ReasoningContent[];\n};\n\nexport type ReasoningContent =\n | {\n type: \"text\";\n text: string;\n signature?: string;\n }\n | {\n type: \"summary\";\n text: string;\n }\n | {\n type: \"encrypted\";\n data: string;\n }\n | {\n type: \"redacted\";\n data: string;\n };\n\nexport type ReasoningContentType = ReasoningContent[\"type\"];\n\nexport type ToolFunction = {\n name: string;\n arguments: JsonValue;\n};\n\nexport type ToolCall = {\n type: \"tool_call\";\n id: string;\n callId?: string;\n function: ToolFunction;\n signature?: string;\n additionalParams?: JsonValue;\n};\n\nexport type ToolResultContent =\n | { type: \"text\"; text: string }\n | { type: \"image\"; data: string; mediaType?: string };\n\nexport type ToolResult = {\n type: \"tool_result\";\n id: string;\n callId?: string;\n content: ToolResultContent[];\n};\n\nexport type UserContent = Text | ImageContent | DocumentContent;\nexport type AssistantContent = Text | ToolCall | Reasoning | ImageContent;\nexport type ToolContent = ToolResult;\n\nexport type SystemMessage = {\n role: \"system\";\n content: string;\n};\n\nexport type UserMessage = {\n role: \"user\";\n content: UserContent[];\n};\n\nexport type AssistantMessage = {\n role: \"assistant\";\n id?: string;\n content: AssistantContent[];\n};\n\nexport type ToolMessage = {\n role: \"tool\";\n content: ToolContent[];\n};\n\nexport type Message = SystemMessage | UserMessage | AssistantMessage | ToolMessage;\n\nexport const UserContent = {\n text(text: string): Text {\n return { type: \"text\", text };\n },\n imageUrl(url: string, options: { detail?: ImageDetail } = {}): ImageContent {\n const image: ImageContent = { type: \"image\", source: { type: \"url\", url } };\n if (options.detail !== undefined) {\n image.detail = options.detail;\n }\n return image;\n },\n imageBase64(\n data: string,\n mediaType: string,\n options: { detail?: ImageDetail } = {},\n ): ImageContent {\n const image: ImageContent = {\n type: \"image\",\n source: { type: \"base64\", data, mediaType },\n };\n if (options.detail !== undefined) {\n image.detail = options.detail;\n }\n return image;\n },\n documentUrl(\n url: string,\n mediaType: string,\n options: { filename?: string | undefined } = {},\n ): DocumentContent {\n return {\n type: \"document\",\n source:\n options.filename === undefined\n ? { type: \"url\", url, mediaType }\n : { type: \"url\", url, mediaType, filename: options.filename },\n };\n },\n documentBase64(\n data: string,\n mediaType: string,\n options: { filename?: string | undefined } = {},\n ): DocumentContent {\n return {\n type: \"document\",\n source:\n options.filename === undefined\n ? { type: \"base64\", data, mediaType }\n : { type: \"base64\", data, mediaType, filename: options.filename },\n };\n },\n documentText(text: string): Text {\n return { type: \"text\", text };\n },\n};\n\nexport const ToolContent = {\n toolResult(id: string, content: string | ToolResultContent[], callId?: string): ToolResult {\n const normalized =\n typeof content === \"string\" ? [{ type: \"text\" as const, text: content }] : content;\n return callId === undefined\n ? { type: \"tool_result\", id, content: normalized }\n : { type: \"tool_result\", id, callId, content: normalized };\n },\n};\n\nexport function serializeToolResultOutput(output: unknown): string {\n if (typeof output === \"string\") {\n return output;\n }\n\n try {\n const serialized = JSON.stringify(output);\n return serialized === undefined ? String(output) : serialized;\n } catch {\n return String(output);\n }\n}\n\nexport function isToolResultContentArray(value: unknown): value is ToolResultContent[] {\n return (\n Array.isArray(value) &&\n value.length > 0 &&\n value.every((item) => {\n if (typeof item !== \"object\" || item === null || !(\"type\" in item)) {\n return false;\n }\n if (item.type === \"text\") {\n return \"text\" in item && typeof item.text === \"string\";\n }\n if (item.type === \"image\") {\n return (\n \"data\" in item &&\n typeof item.data === \"string\" &&\n (!(\"mediaType\" in item) ||\n item.mediaType === undefined ||\n typeof item.mediaType === \"string\")\n );\n }\n return false;\n })\n );\n}\n\nexport const AssistantContent = {\n text(text: string): Text {\n return { type: \"text\", text };\n },\n imageUrl(url: string, options: { detail?: ImageDetail } = {}): ImageContent {\n const image: ImageContent = { type: \"image\", source: { type: \"url\", url } };\n if (options.detail !== undefined) {\n image.detail = options.detail;\n }\n return image;\n },\n imageBase64(\n data: string,\n mediaType: string,\n options: { detail?: ImageDetail } = {},\n ): ImageContent {\n const image: ImageContent = {\n type: \"image\",\n source: { type: \"base64\", data, mediaType },\n };\n if (options.detail !== undefined) {\n image.detail = options.detail;\n }\n return image;\n },\n reasoning(text: string, id?: string): Reasoning {\n return id === undefined ? { type: \"reasoning\", text } : { type: \"reasoning\", text, id };\n },\n reasoningFromContent(content: ReasoningContent[], id?: string): Reasoning {\n const text = reasoningDisplayText(content);\n const reasoning: Reasoning = { type: \"reasoning\", text, content };\n return id === undefined ? reasoning : { ...reasoning, id };\n },\n reasoningSummary(text: string, id?: string): Reasoning {\n return AssistantContent.reasoningFromContent([{ type: \"summary\", text }], id);\n },\n reasoningEncrypted(data: string, id?: string): Reasoning {\n return AssistantContent.reasoningFromContent([{ type: \"encrypted\", data }], id);\n },\n reasoningRedacted(data: string, id?: string): Reasoning {\n return AssistantContent.reasoningFromContent([{ type: \"redacted\", data }], id);\n },\n toolCall(id: string, name: string, args: JsonValue, callId?: string): ToolCall {\n const base: ToolCall = {\n type: \"tool_call\",\n id,\n function: {\n name,\n arguments: args,\n },\n };\n return callId === undefined ? base : { ...base, callId };\n },\n};\n\nexport function reasoningDisplayText(reasoning: Reasoning | ReasoningContent[]): string {\n const content = Array.isArray(reasoning) ? reasoning : reasoning.content;\n if (content === undefined) {\n return Array.isArray(reasoning) ? \"\" : reasoning.text;\n }\n return content\n .flatMap((item) => {\n if (item.type === \"text\" || item.type === \"summary\") {\n return [item.text];\n }\n return [];\n })\n .join(\"\");\n}\n\nexport const Message = {\n system(content: string): Message {\n return { role: \"system\", content };\n },\n user(content: string | UserContent[]): Message {\n return {\n role: \"user\",\n content: typeof content === \"string\" ? [UserContent.text(content)] : content,\n };\n },\n assistant(content: string | AssistantContent[], id?: string): Message {\n const normalized = typeof content === \"string\" ? [AssistantContent.text(content)] : content;\n return id === undefined\n ? { role: \"assistant\", content: normalized }\n : { role: \"assistant\", id, content: normalized };\n },\n tool(content: ToolContent | ToolContent[]): Message {\n return {\n role: \"tool\",\n content: Array.isArray(content) ? content : [content],\n };\n },\n toolResult(id: string, output: unknown, options: { callId?: string | undefined } = {}): Message {\n const content = isToolResultContentArray(output) ? output : serializeToolResultOutput(output);\n return Message.tool(ToolContent.toolResult(id, content, options.callId));\n },\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\nexport type Usage = {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n cachedInputTokens: number;\n cacheCreationInputTokens: number;\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 return {\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 },\n};\n\nexport type CompletionRequest<ModelName extends string = string> = {\n model?: ModelName;\n instructions?: string;\n chatHistory: Message[];\n documents: Document[];\n tools: ToolDefinition[];\n temperature?: number;\n maxTokens?: number;\n toolChoice?: ToolChoice;\n additionalParams?: JsonValue;\n outputSchema?: JsonObject;\n};\n\nexport type CompletionResponse<RawResponse = unknown> = {\n choice: AssistantContent[];\n usage: Usage;\n rawResponse: RawResponse;\n messageId?: string;\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};\n\nexport interface CompletionModel<RawResponse = unknown, ModelName extends string = string> {\n readonly provider: string;\n readonly defaultModel: ModelName;\n readonly capabilities: CompletionModelCapabilities;\n traceRequest?(\n request: CompletionRequest<ModelName>,\n options?: { stream?: boolean | undefined },\n ): JsonObject | undefined;\n completion(request: CompletionRequest<ModelName>): Promise<CompletionResponse<RawResponse>>;\n}\n\nexport type CompletionStreamEvent<RawResponse = unknown> =\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 signature?: string;\n }\n | {\n type: \"tool_call\";\n toolCall: ToolCall;\n }\n | {\n type: \"message_id\";\n id: string;\n }\n | {\n type: \"final\";\n response: CompletionResponse<RawResponse>;\n }\n | {\n type: \"error\";\n error: unknown;\n };\n\nexport interface StreamingCompletionModel<RawResponse = unknown, ModelName extends string = string>\n extends CompletionModel<RawResponse, ModelName> {\n streamCompletion(\n request: CompletionRequest<ModelName>,\n ): AsyncIterable<CompletionStreamEvent<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}:${request.model ?? model.defaultModel}`;\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.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: AssistantContent[]): 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\" ? false : 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\"\n ? message.content.some(\n (content) => content.type === \"document\" && content.source.type !== \"text\",\n )\n : false,\n );\n}\n"],"mappings":";AAwIO,IAAM,cAAc;AAAA,EACzB,KAAK,MAAoB;AACvB,WAAO,EAAE,MAAM,QAAQ,KAAK;AAAA,EAC9B;AAAA,EACA,SAAS,KAAa,UAAoC,CAAC,GAAiB;AAC1E,UAAM,QAAsB,EAAE,MAAM,SAAS,QAAQ,EAAE,MAAM,OAAO,IAAI,EAAE;AAC1E,QAAI,QAAQ,WAAW,QAAW;AAChC,YAAM,SAAS,QAAQ;AAAA,IACzB;AACA,WAAO;AAAA,EACT;AAAA,EACA,YACE,MACA,WACA,UAAoC,CAAC,GACvB;AACd,UAAM,QAAsB;AAAA,MAC1B,MAAM;AAAA,MACN,QAAQ,EAAE,MAAM,UAAU,MAAM,UAAU;AAAA,IAC5C;AACA,QAAI,QAAQ,WAAW,QAAW;AAChC,YAAM,SAAS,QAAQ;AAAA,IACzB;AACA,WAAO;AAAA,EACT;AAAA,EACA,YACE,KACA,WACA,UAA6C,CAAC,GAC7B;AACjB,WAAO;AAAA,MACL,MAAM;AAAA,MACN,QACE,QAAQ,aAAa,SACjB,EAAE,MAAM,OAAO,KAAK,UAAU,IAC9B,EAAE,MAAM,OAAO,KAAK,WAAW,UAAU,QAAQ,SAAS;AAAA,IAClE;AAAA,EACF;AAAA,EACA,eACE,MACA,WACA,UAA6C,CAAC,GAC7B;AACjB,WAAO;AAAA,MACL,MAAM;AAAA,MACN,QACE,QAAQ,aAAa,SACjB,EAAE,MAAM,UAAU,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AA,EACnF;AAEA,MAAI,CAAC,aAAa,iBAAiB,4BAA4B,OAAO,GAAG;AACvE,UAAM,IAAI,0BAA0B,GAAG,UAAU,wCAAwC;AAAA,EAC3F;AACF;AAEO,SAAS,yBAAyB,SAAqC;AAC5E,SAAO,QAAQ,QAAQ,CAAC,SAAU,KAAK,SAAS,SAAS,CAAC,KAAK,IAAI,IAAI,CAAC,CAAE,EAAE,KAAK,IAAI;AACvF;AAEA,SAAS,qBAAqB,SAAqC;AACjE,SAAO,QAAQ,YAAY;AAAA,IAAK,CAAC,YAC/B,QAAQ,SAAS,WAAW,QAAQ,QAAQ,QAAQ,KAAK,CAAC,YAAY,QAAQ,SAAS,OAAO;AAAA,EAChG;AACF;AAEA,SAAS,4BAA4B,SAAqC;AACxE,SAAO,QAAQ,YAAY;AAAA,IAAK,CAAC,YAC/B,QAAQ,SAAS,SACb,QAAQ,QAAQ;AAAA,MACd,CAAC,YAAY,QAAQ,SAAS,cAAc,QAAQ,OAAO,SAAS;AAAA,IACtE,IACA;AAAA,EACN;AACF;","names":[]}
@@ -4,21 +4,21 @@ import {
4
4
  import {
5
5
  parseToolArgs,
6
6
  toolResultContentToText
7
- } from "./chunk-X3SWV6W6.js";
7
+ } from "./chunk-FV5B4SGK.js";
8
8
  import {
9
9
  mapWithConcurrency
10
10
  } from "./chunk-OIMLU4SF.js";
11
11
  import {
12
12
  CompletionRequestBuilder,
13
13
  isStreamingCompletionModel
14
- } from "./chunk-5G3VME2D.js";
14
+ } from "./chunk-SRBW3LD7.js";
15
15
  import {
16
16
  Message,
17
17
  ToolContent,
18
18
  Usage,
19
19
  assertCompletionRequestSupported,
20
20
  textFromAssistantContent
21
- } from "./chunk-WJO6NVE2.js";
21
+ } from "./chunk-5LFGEMIW.js";
22
22
  import {
23
23
  runControl,
24
24
  toolCallControl
@@ -1198,7 +1198,10 @@ var PromptRequest = class _PromptRequest {
1198
1198
  const dynamicContext = await fetchDynamicContext(this.agent, ragText);
1199
1199
  const toolDefs = await fetchToolDefinitions(this.agent, ragText);
1200
1200
  let request = new CompletionRequestBuilder(this.agent.model, prompt).instructions(this.agent.instructions).messages(historyForRequest).documents([...this.agent.staticContext, ...dynamicContext]).tools(toolDefs).temperature(this.agent.temperature).maxTokens(this.agent.maxTokens).additionalParams(this.agent.additionalParams).toolChoice(this.agent.toolChoice).outputSchema(this.agent.outputSchema).build();
1201
- request = await this.runCompletionRequestMiddlewares(request, currentTurns);
1201
+ request = await this.runCompletionRequestMiddlewares(
1202
+ request,
1203
+ currentTurns
1204
+ );
1202
1205
  let response;
1203
1206
  try {
1204
1207
  response = await this.runCompletion(request, currentTurns, runObservers);
@@ -1314,7 +1317,10 @@ var PromptRequest = class _PromptRequest {
1314
1317
  const dynamicContext = await fetchDynamicContext(this.agent, ragText);
1315
1318
  const toolDefs = await fetchToolDefinitions(this.agent, ragText);
1316
1319
  let request = new CompletionRequestBuilder(this.agent.model, prompt).instructions(this.agent.instructions).messages(historyForRequest).documents([...this.agent.staticContext, ...dynamicContext]).tools(toolDefs).temperature(this.agent.temperature).maxTokens(this.agent.maxTokens).additionalParams(this.agent.additionalParams).toolChoice(this.agent.toolChoice).outputSchema(this.agent.outputSchema).build();
1317
- request = await this.runCompletionRequestMiddlewares(request, currentTurns);
1320
+ request = await this.runCompletionRequestMiddlewares(
1321
+ request,
1322
+ currentTurns
1323
+ );
1318
1324
  assertCompletionRequestSupported(this.agent.model, request, { streaming: true });
1319
1325
  const providerRequest = this.providerTraceRequest(request, { stream: true });
1320
1326
  const generationObservers = await runObservers.startGeneration(
@@ -1778,4 +1784,4 @@ export {
1778
1784
  extractRagText,
1779
1785
  PromptRequest
1780
1786
  };
1781
- //# sourceMappingURL=chunk-SISUMRUX.js.map
1787
+ //# sourceMappingURL=chunk-7CQAERL3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/request/errors.ts","../src/internal/async-queue.ts","../src/internal/prompt-runtime/memory.ts","../src/internal/prompt-runtime/retrieval.ts","../src/internal/prompt-runtime/stream-accumulator.ts","../src/internal/prompt-runtime/stream-events.ts","../src/internal/prompt-runtime/tool-execution.ts","../src/internal/rag-text.ts","../src/observability/group.ts","../src/request/prompt-request.ts"],"sourcesContent":["import type { Message } from \"../completion/index\";\nimport type { ToolApprovalRequest } from \"../tool\";\n\nexport class MaxTurnsError extends Error {\n constructor(\n readonly maxTurns: number,\n readonly chatHistory: Message[],\n readonly prompt: Message,\n ) {\n super(`Reached max turn limit: ${maxTurns}`);\n this.name = \"MaxTurnsError\";\n }\n}\n\nexport class PromptCancelledError extends Error {\n constructor(\n readonly chatHistory: Message[],\n readonly reason: string,\n ) {\n super(`Prompt cancelled: ${reason}`);\n this.name = \"PromptCancelledError\";\n }\n}\n\nexport class ToolApprovalRequiredError extends Error {\n constructor(readonly request: ToolApprovalRequest) {\n super(`Tool approval required for ${request.toolName}, but no approval handler is configured.`);\n this.name = \"ToolApprovalRequiredError\";\n }\n}\n","type AsyncQueueWaiter<T> = {\n resolve: (result: IteratorResult<T>) => void;\n reject: (error: unknown) => void;\n};\n\nexport type AsyncQueue<T> = AsyncIterable<T> & {\n enqueue(value: T): void;\n close(): void;\n throw(error: unknown): void;\n};\n\nexport function createAsyncQueue<T>(): AsyncQueue<T> {\n const values: T[] = [];\n const waiters: AsyncQueueWaiter<T>[] = [];\n let closed = false;\n let error: unknown;\n\n function flush(): void {\n while (waiters.length > 0 && values.length > 0) {\n const waiter = waiters.shift();\n const value = values.shift() as T;\n if (waiter !== undefined) {\n waiter.resolve({ value, done: false });\n }\n }\n\n if (values.length > 0 || waiters.length === 0 || !closed) {\n return;\n }\n\n while (waiters.length > 0) {\n const waiter = waiters.shift();\n if (waiter === undefined) {\n continue;\n }\n if (error !== undefined) {\n waiter.reject(error);\n } else {\n waiter.resolve({ value: undefined, done: true });\n }\n }\n }\n\n return {\n enqueue(value: T): void {\n if (closed) {\n return;\n }\n values.push(value);\n flush();\n },\n close(): void {\n closed = true;\n flush();\n },\n throw(thrown: unknown): void {\n closed = true;\n error = thrown;\n flush();\n },\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return {\n next(): Promise<IteratorResult<T>> {\n if (values.length > 0) {\n const value = values.shift() as T;\n return Promise.resolve({ value, done: false });\n }\n if (error !== undefined) {\n return Promise.reject(error);\n }\n if (closed) {\n return Promise.resolve({ value: undefined, done: true });\n }\n return new Promise((resolve, reject) => {\n waiters.push({ resolve, reject });\n });\n },\n };\n },\n };\n}\n","import type { Agent } from \"../../agent/agent\";\nimport type { Message as MessageType } from \"../../completion/index\";\nimport type { MemoryContext, MemoryRegistration, MemorySavePolicy } from \"../../memory/types\";\n\nexport class PromptRequestMemory {\n constructor(\n private readonly agent: Agent,\n private readonly memoryContext: MemoryContext | undefined,\n private readonly initialHistory: MessageType[],\n ) {}\n\n memoryPolicy(): MemorySavePolicy | undefined {\n return this.memory()?.options.savePolicy;\n }\n\n pendingTurnMessages(newMessages: MessageType[]): MessageType[] {\n return this.memoryPolicy() === \"turn\" ? [...newMessages] : [];\n }\n\n async prepareRun(runId: string, newMessages: MessageType[]): Promise<MessageType[]> {\n const memory = this.memory();\n if (memory === undefined || this.memoryContext === undefined) {\n return this.initialHistory;\n }\n\n const memoryHistory = await memory.store.load(this.memoryContext);\n const chatHistory = [...memoryHistory, ...this.initialHistory];\n if (memory.options.savePolicy === \"message\") {\n await memory.store.append({\n context: this.memoryContext,\n runId,\n turn: 1,\n messages: newMessages,\n });\n }\n return chatHistory;\n }\n\n async commitMessages(\n runId: string,\n turn: number,\n messages: MessageType[],\n pendingTurnMessages: MessageType[],\n ): Promise<void> {\n const memory = this.memory();\n if (memory === undefined || this.memoryContext === undefined || messages.length === 0) {\n return;\n }\n if (memory.options.savePolicy === \"message\") {\n await memory.store.append({\n context: this.memoryContext,\n runId,\n turn,\n messages,\n });\n } else if (memory.options.savePolicy === \"turn\") {\n pendingTurnMessages.push(...messages);\n }\n }\n\n async commitCompletedTurn(\n runId: string,\n turn: number,\n pendingTurnMessages: MessageType[],\n ): Promise<void> {\n const memory = this.memory();\n if (\n memory === undefined ||\n this.memoryContext === undefined ||\n memory.options.savePolicy !== \"turn\" ||\n pendingTurnMessages.length === 0\n ) {\n return;\n }\n await memory.store.append({\n context: this.memoryContext,\n runId,\n turn,\n messages: [...pendingTurnMessages],\n });\n pendingTurnMessages.length = 0;\n }\n\n async commitCompletedRun(\n runId: string,\n turn: number,\n newMessages: MessageType[],\n pendingTurnMessages: MessageType[],\n ): Promise<void> {\n await this.commitCompletedTurn(runId, turn, pendingTurnMessages);\n const memory = this.memory();\n if (\n memory === undefined ||\n this.memoryContext === undefined ||\n memory.options.savePolicy !== \"run\"\n ) {\n return;\n }\n await memory.store.append({\n context: this.memoryContext,\n runId,\n turn,\n messages: [...newMessages],\n });\n }\n\n async recordError(runId: string, error: unknown, newMessages: MessageType[]): Promise<void> {\n const memory = this.memory();\n if (memory === undefined || this.memoryContext === undefined) {\n return;\n }\n await memory.store.recordError?.({\n context: this.memoryContext,\n runId,\n error,\n messages: [...newMessages],\n });\n }\n\n private memory(): MemoryRegistration | undefined {\n return this.memoryContext === undefined ? undefined : this.agent.memory;\n }\n}\n","import type { Agent } from \"../../agent/agent\";\nimport type { Document, ToolDefinition } from \"../../completion/index\";\nimport { compact } from \"../compact\";\n\nexport async function fetchDynamicContext(\n agent: Agent,\n ragText: string | undefined,\n): Promise<Document[]> {\n if (ragText === undefined || ragText.length === 0 || agent.dynamicContexts.length === 0) {\n return [];\n }\n\n const documents: Document[] = [];\n for (const registration of agent.dynamicContexts) {\n const results = await registration.index.search({\n query: ragText,\n topK: registration.options.topK,\n threshold: registration.options.threshold,\n filter: registration.options.filter,\n });\n for (const result of results) {\n const formatted = registration.options.format?.(result);\n if (formatted !== undefined) {\n documents.push(formatted);\n } else {\n const metadata = formatMetadata(result.metadata);\n documents.push(\n compact({\n id: result.id,\n text:\n typeof result.document === \"string\"\n ? result.document\n : JSON.stringify(result.document, null, 2),\n additionalProps: metadata,\n }) as Document,\n );\n }\n }\n }\n return documents;\n}\n\nexport async function fetchToolDefinitions(\n agent: Agent,\n ragText: string | undefined,\n): Promise<ToolDefinition[]> {\n const staticDefinitions = await agent.toolSet.getToolDefinitions(ragText);\n if (ragText === undefined || ragText.length === 0 || agent.dynamicTools.length === 0) {\n return staticDefinitions;\n }\n\n const definitions = [...staticDefinitions];\n const names = new Set(staticDefinitions.map((definition) => definition.name));\n for (const registration of agent.dynamicTools) {\n const results = await registration.index.search({\n query: ragText,\n topK: registration.options.topK,\n threshold: registration.options.threshold,\n filter: registration.options.filter,\n });\n for (const result of results) {\n if (names.has(result.document.toolName)) {\n continue;\n }\n names.add(result.document.toolName);\n definitions.push(result.document.definition);\n }\n }\n return definitions;\n}\n\nfunction formatMetadata(\n metadata: Record<string, unknown> | undefined,\n): Record<string, string> | undefined {\n if (metadata === undefined) {\n return undefined;\n }\n\n return Object.fromEntries(Object.entries(metadata).map(([key, value]) => [key, String(value)]));\n}\n","import type {\n AssistantContent as AssistantContentType,\n CompletionResponse,\n CompletionStreamEvent,\n JsonValue,\n ReasoningContent,\n ToolCall,\n} from \"../../completion/index\";\nimport { Usage } from \"../../completion/index\";\nimport type { AgentDeltaEvent } from \"../../request/types\";\n\ntype ReasoningState = {\n text: string;\n content?: ReasoningContent[];\n};\n\ntype PartialToolCall = {\n id: string;\n callId?: string;\n name: string;\n argumentsText: string;\n signature?: string;\n};\n\nexport class CompletionStreamAccumulator<RawResponse = unknown> {\n private static readonly defaultReasoningKey = \"reasoning\";\n private text = \"\";\n private reasoningById = new Map<string, ReasoningState>();\n private reasoningOrder: string[] = [];\n private toolCalls = new Map<string, PartialToolCall>();\n private toolCallOrder: string[] = [];\n private finalResponse: CompletionResponse<RawResponse> | undefined;\n private messageId: string | undefined;\n\n accept(event: CompletionStreamEvent<RawResponse>): AgentDeltaEvent | undefined {\n if (event.type === \"text_delta\") {\n this.text += event.delta;\n return { type: \"text_delta\", delta: event.delta };\n }\n\n if (event.type === \"reasoning_delta\") {\n const key = event.id ?? CompletionStreamAccumulator.defaultReasoningKey;\n const existing = this.reasoningById.get(key);\n const reasoning = existing ?? { text: \"\" };\n if (!existing) {\n this.reasoningOrder.push(key);\n }\n this.appendReasoning(reasoning, event);\n this.reasoningById.set(key, reasoning);\n return reasoningDeltaEvent(event);\n }\n\n if (event.type === \"tool_call_delta\") {\n const existing = this.toolCalls.get(event.id);\n const toolCall = existing ?? {\n id: event.id,\n name: \"\",\n argumentsText: \"\",\n };\n if (!existing) {\n this.toolCallOrder.push(event.id);\n }\n if (event.callId !== undefined) toolCall.callId = event.callId;\n if (event.name !== undefined) toolCall.name = event.name;\n if (event.signature !== undefined) toolCall.signature = event.signature;\n if (event.argumentsDelta !== undefined) {\n toolCall.argumentsText += event.argumentsDelta;\n }\n this.toolCalls.set(event.id, toolCall);\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 === \"message_id\") {\n this.messageId = event.id;\n return undefined;\n }\n\n if (event.type === \"final\") {\n this.finalResponse = event.response;\n return undefined;\n }\n\n return undefined;\n }\n\n response(): CompletionResponse<RawResponse> {\n const accumulatedResponse = this.buildAccumulatedResponse();\n if (this.finalResponse !== undefined) {\n if (this.finalResponse.choice.length === 0) {\n const response = {\n ...accumulatedResponse,\n usage: this.finalResponse.usage,\n rawResponse: this.finalResponse.rawResponse,\n };\n if (this.finalResponse.messageId !== undefined) {\n response.messageId = this.finalResponse.messageId;\n }\n return response;\n }\n return this.mergeFinalResponse(accumulatedResponse, this.finalResponse);\n }\n\n return accumulatedResponse;\n }\n\n private buildAccumulatedResponse(): CompletionResponse<RawResponse> {\n const choice: AssistantContentType[] = [];\n if (this.text.length > 0) {\n choice.push({ type: \"text\", text: this.text });\n }\n for (const key of this.reasoningOrder) {\n const reasoning = this.reasoningById.get(key) ?? { text: \"\" };\n const id = key === CompletionStreamAccumulator.defaultReasoningKey ? undefined : key;\n const content =\n reasoning.content === undefined\n ? { type: \"reasoning\" as const, text: reasoning.text }\n : { type: \"reasoning\" as const, text: reasoning.text, content: reasoning.content };\n choice.push(id === undefined ? content : { ...content, id });\n }\n for (const id of this.toolCallOrder) {\n const toolCall = this.toolCalls.get(id);\n if (toolCall !== undefined) {\n const content: ToolCall = {\n type: \"tool_call\",\n id: toolCall.id,\n function: {\n name: toolCall.name,\n arguments: parseJsonValue(toolCall.argumentsText),\n },\n };\n if (toolCall.callId !== undefined) {\n content.callId = toolCall.callId;\n }\n if (toolCall.signature !== undefined) {\n content.signature = toolCall.signature;\n }\n choice.push(content);\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 return response;\n }\n\n private upsertToolCall(toolCall: ToolCall): void {\n if (!this.toolCalls.has(toolCall.id)) {\n this.toolCallOrder.push(toolCall.id);\n }\n const partial: PartialToolCall = {\n id: toolCall.id,\n name: toolCall.function.name,\n argumentsText: JSON.stringify(toolCall.function.arguments ?? {}),\n };\n if (toolCall.callId !== undefined) {\n partial.callId = toolCall.callId;\n }\n if (toolCall.signature !== undefined) {\n partial.signature = toolCall.signature;\n }\n this.toolCalls.set(toolCall.id, partial);\n }\n\n private mergeFinalResponse(\n accumulatedResponse: CompletionResponse<RawResponse>,\n finalResponse: CompletionResponse<RawResponse>,\n ): CompletionResponse<RawResponse> {\n const accumulatedById = new Map<string, ToolCall>();\n const accumulatedByCallId = new Map<string, ToolCall>();\n for (const content of accumulatedResponse.choice) {\n if (content.type !== \"tool_call\") {\n continue;\n }\n accumulatedById.set(content.id, content);\n if (content.callId !== undefined) {\n accumulatedByCallId.set(content.callId, content);\n }\n }\n\n return {\n ...finalResponse,\n choice: finalResponse.choice.map((content) => {\n if (content.type !== \"tool_call\" || !isEmptyToolArguments(content.function.arguments)) {\n return content;\n }\n\n const accumulated =\n accumulatedById.get(content.id) ??\n (content.callId === undefined ? undefined : accumulatedByCallId.get(content.callId));\n if (accumulated === undefined || isEmptyToolArguments(accumulated.function.arguments)) {\n return content;\n }\n\n return {\n ...content,\n function: {\n ...content.function,\n arguments: accumulated.function.arguments,\n },\n };\n }),\n };\n }\n\n private appendReasoning(\n reasoning: ReasoningState,\n event: Extract<CompletionStreamEvent<RawResponse>, { type: \"reasoning_delta\" }>,\n ): void {\n const contentType = event.contentType ?? \"text\";\n if (contentType === \"text\" || contentType === \"summary\") {\n reasoning.text += event.delta;\n }\n\n if (event.contentType === undefined && event.signature === undefined) {\n return;\n }\n\n reasoning.content ??= [];\n const last = reasoning.content.at(-1);\n if (contentType === \"text\") {\n if (last?.type === \"text\") {\n last.text += event.delta;\n if (event.signature !== undefined) {\n last.signature = event.signature;\n }\n } else {\n reasoning.content.push(\n event.signature === undefined\n ? { type: \"text\", text: event.delta }\n : { type: \"text\", text: event.delta, signature: event.signature },\n );\n }\n return;\n }\n\n if (contentType === \"summary\") {\n if (last?.type === \"summary\") {\n last.text += event.delta;\n } else {\n reasoning.content.push({ type: \"summary\", text: event.delta });\n }\n return;\n }\n\n if (contentType === \"encrypted\") {\n reasoning.content.push({ type: \"encrypted\", data: event.delta });\n return;\n }\n\n reasoning.content.push({ type: \"redacted\", data: event.delta });\n }\n}\n\nfunction reasoningDeltaEvent(\n event: Extract<CompletionStreamEvent, { type: \"reasoning_delta\" }>,\n): AgentDeltaEvent {\n const mapped: AgentDeltaEvent = { type: \"reasoning_delta\", delta: event.delta };\n if (event.id !== undefined) mapped.id = event.id;\n if (event.contentType !== undefined) mapped.contentType = event.contentType;\n if (event.signature !== undefined) mapped.signature = event.signature;\n return mapped;\n}\n\nfunction isEmptyToolArguments(value: unknown): boolean {\n if (value === undefined || value === null) {\n return true;\n }\n if (typeof value === \"string\") {\n return value.trim().length === 0;\n }\n if (Array.isArray(value)) {\n return value.length === 0;\n }\n if (typeof value === \"object\") {\n return Object.values(value).every((item) => item === undefined);\n }\n return false;\n}\n\nfunction parseJsonValue(text: string): JsonValue {\n if (text.trim().length === 0) {\n return {};\n }\n try {\n return JSON.parse(text) as JsonValue;\n } catch {\n return text;\n }\n}\n","import type { AgentDeltaEvent, AgentStreamEvent } from \"../../request/types\";\n\nexport function addTurn(turn: number, event: AgentDeltaEvent): AgentStreamEvent {\n if (event.type === \"text_delta\") {\n return { type: \"text_delta\", turn, delta: event.delta };\n }\n if (event.type === \"reasoning_delta\") {\n const mapped: AgentStreamEvent = { type: \"reasoning_delta\", turn, delta: event.delta };\n if (event.id !== undefined) mapped.id = event.id;\n if (event.contentType !== undefined) mapped.contentType = event.contentType;\n if (event.signature !== undefined) mapped.signature = event.signature;\n return mapped;\n }\n return { type: \"tool_call\", turn, toolCall: event.toolCall };\n}\n\nexport function isGenerationDeltaEvent(type: string): boolean {\n return (\n type === \"text_delta\" ||\n type === \"reasoning_delta\" ||\n type === \"tool_call_delta\" ||\n type === \"tool_call\"\n );\n}\n","import type { Agent } from \"../../agent/agent\";\nimport type {\n JsonObject,\n ToolCall,\n ToolDefinition,\n ToolResult,\n ToolResultContent,\n} from \"../../completion\";\nimport { ToolContent } from \"../../completion\";\nimport type { PromptHook, ToolApprovalRequestOptions, ToolHookArgs } from \"../../hooks\";\nimport { runControl, toolCallControl } from \"../../hooks\";\nimport type { ActiveAgentRunObservers, ActiveToolObservers } from \"../../observability/group\";\nimport { ToolApprovalRequiredError } from \"../../request/errors\";\nimport type { AgentChildStreamEvent } from \"../../request/types\";\nimport type {\n AnyTool,\n NormalizedToolOutput,\n ToolApprovalContext,\n ToolApprovalDecision,\n ToolApprovalPolicy,\n ToolApprovalRequest,\n ToolApprovalsOptions,\n ToolCallStreamEvent,\n} from \"../../tool\";\nimport { parseToolArgs, toolResultContentToText } from \"../../tool\";\nimport type {\n AgentMiddleware,\n ToolOutputMiddlewareArgs,\n ToolOutputMiddlewareResult,\n} from \"../../tool/middleware\";\nimport { compact } from \"../compact\";\nimport { mapWithConcurrency } from \"../concurrency\";\n\nconst MCP_TOOL_METADATA_KEY = Symbol.for(\"anvia.mcp.tool.metadata\");\n\nexport type ToolResultEventPayload = {\n type: \"tool_result\";\n toolName: string;\n toolCallId?: string;\n internalCallId: string;\n args: string;\n result: string;\n structuredResult?: ToolResultContent[] | undefined;\n};\n\nexport type AgentToolEventPayload = {\n type: \"agent_tool_event\";\n toolName: string;\n toolCallId?: string;\n internalCallId: string;\n agentId: string;\n agentName?: string;\n event: AgentChildStreamEvent;\n};\n\nexport type ToolExecutionEventPayload = ToolResultEventPayload | AgentToolEventPayload;\n\nexport type ToolExecutionObservation = {\n turn: number;\n runObservers: ActiveAgentRunObservers;\n toolDefinitions?: ToolDefinition[];\n};\n\nexport type ToolExecutionRunContext = {\n runId: string;\n sessionId?: string | undefined;\n metadata?: JsonObject | undefined;\n};\n\nexport class ToolCallExecutor {\n constructor(\n private readonly agent: Agent,\n private readonly activeHook: PromptHook | undefined,\n private readonly approvals: ToolApprovalsOptions | undefined,\n private readonly runContext: ToolExecutionRunContext,\n private readonly concurrency: number,\n private readonly requestMiddlewares: AgentMiddleware[],\n private readonly cancel: (reason: string) => Error,\n ) {}\n\n async execute(\n toolCalls: ToolCall[],\n onResult?: (result: ToolResultEventPayload) => void,\n onStreamEvent?: (event: AgentToolEventPayload) => void,\n observation?: ToolExecutionObservation,\n ): Promise<ToolResult[]> {\n return mapWithConcurrency(toolCalls, this.concurrency, async (toolCall) => {\n const args = JSON.stringify(toolCall.function.arguments ?? {});\n const internalCallId = globalThis.crypto.randomUUID();\n const hookArgs: ToolHookArgs = {\n toolName: toolCall.function.name,\n internalCallId,\n args,\n };\n if (toolCall.callId !== undefined) {\n hookArgs.toolCallId = toolCall.callId;\n }\n const tool = this.agent.getTool(toolCall.function.name);\n const toolDefinition = observation?.toolDefinitions?.find(\n (definition) => definition.name === toolCall.function.name,\n );\n const toolMetadata = toolTraceMetadata(tool);\n\n const toolObservers = await observation?.runObservers.startTool(\n compact({\n turn: observation.turn,\n toolCall,\n toolName: toolCall.function.name,\n internalCallId,\n args,\n toolCallId: toolCall.callId,\n toolDefinition,\n toolMetadata,\n }),\n );\n\n const callAction = await this.activeHook?.onToolCall?.({\n ...hookArgs,\n tool: toolCallControl,\n });\n if (callAction?.type === \"terminate\") {\n await recordToolError(\n toolObservers,\n observation?.turn,\n toolCall,\n internalCallId,\n args,\n callAction.reason,\n );\n throw this.cancel(callAction.reason);\n }\n let output: NormalizedToolOutput;\n let skipped = false;\n let effectiveArgs = args;\n if (callAction?.type === \"skip\") {\n output = callAction.reason;\n skipped = true;\n } else {\n let approvalDecision: { approved: true } | { approved: false; result: string };\n try {\n effectiveArgs = await this.runToolInputMiddlewares({\n ...hookArgs,\n turn: observation?.turn ?? 0,\n originalArgs: args,\n });\n const effectiveHookArgs = { ...hookArgs, args: effectiveArgs };\n approvalDecision =\n callAction?.type === \"approval_request\"\n ? await this.requestApproval(tool, effectiveHookArgs, callAction)\n : ((await this.evaluateToolApproval(tool, effectiveHookArgs)) ?? { approved: true });\n } catch (error) {\n await recordToolError(\n toolObservers,\n observation?.turn,\n toolCall,\n internalCallId,\n effectiveArgs,\n error,\n );\n throw error;\n }\n\n if (!approvalDecision.approved) {\n output = approvalDecision.result;\n skipped = true;\n } else {\n try {\n output = await this.agent.callTool(toolCall.function.name, effectiveArgs, {\n emitStreamEvent: async (event) => {\n await toolObservers?.streamEvent(\n compact({\n turn: observation?.turn ?? 0,\n toolCall,\n toolName: toolCall.function.name,\n internalCallId,\n args: effectiveArgs,\n toolCallId: toolCall.callId,\n event,\n }),\n );\n const payload = agentToolEventPayload(toolCall, internalCallId, event);\n if (payload !== undefined) {\n onStreamEvent?.(payload);\n }\n },\n });\n } catch (error) {\n const errorAction = await this.activeHook?.onToolError?.({\n ...hookArgs,\n args: effectiveArgs,\n error,\n run: runControl,\n });\n await toolObservers?.error({\n turn: observation?.turn ?? 0,\n toolCall,\n toolName: toolCall.function.name,\n internalCallId,\n args: effectiveArgs,\n ...(toolCall.callId !== undefined && { toolCallId: toolCall.callId }),\n error,\n });\n if (errorAction?.type === \"terminate\") {\n throw this.cancel(errorAction.reason);\n }\n output = error instanceof Error ? error.toString() : String(error);\n }\n }\n }\n\n let result = toolOutputToText(output);\n let structuredResult = toolOutputToStructuredResult(output);\n if (this.agent.shouldApplyToolMiddleware(toolCall.function.name)) {\n const middlewareReplacement = await this.runToolResultMiddlewares({\n ...hookArgs,\n args: effectiveArgs,\n result,\n originalResult: result,\n structuredResult,\n originalStructuredResult: structuredResult,\n turn: observation?.turn ?? 0,\n });\n if (middlewareReplacement !== undefined) {\n output = middlewareReplacement;\n result = toolOutputToText(middlewareReplacement);\n structuredResult = toolOutputToStructuredResult(middlewareReplacement);\n }\n }\n\n const resultAction = await this.activeHook?.onToolResult?.({\n ...hookArgs,\n args: effectiveArgs,\n result,\n structuredResult,\n run: runControl,\n });\n await toolObservers?.end({\n turn: observation?.turn ?? 0,\n toolCall,\n toolName: toolCall.function.name,\n internalCallId,\n args: effectiveArgs,\n result,\n structuredResult,\n skipped,\n toolCallId: toolCall.callId,\n });\n if (resultAction?.type === \"terminate\") {\n throw this.cancel(resultAction.reason);\n }\n\n const resultPayload: ToolResultEventPayload = {\n type: \"tool_result\",\n toolName: toolCall.function.name,\n internalCallId,\n args: effectiveArgs,\n result,\n structuredResult,\n };\n if (toolCall.callId !== undefined) {\n resultPayload.toolCallId = toolCall.callId;\n }\n onResult?.(resultPayload);\n return ToolContent.toolResult(toolCall.id, output, toolCall.callId);\n });\n }\n\n private async runToolResultMiddlewares(\n args: ToolOutputMiddlewareArgs,\n ): Promise<NormalizedToolOutput | undefined> {\n let result = args.result;\n let structuredResult = args.structuredResult;\n let replaced = false;\n for (const middleware of this.activeMiddlewares()) {\n const outputReplacement = await middleware.onToolOutput?.({\n ...args,\n result,\n structuredResult,\n });\n if (outputReplacement !== undefined) {\n const normalized = normalizeToolOutputMiddlewareResult(outputReplacement);\n if (normalized.result !== undefined) {\n result = normalized.result;\n structuredResult = undefined;\n }\n if (normalized.structuredResult !== undefined) {\n structuredResult = normalized.structuredResult;\n result = toolResultContentToText(normalized.structuredResult);\n }\n replaced = true;\n }\n const legacyReplacement = await middleware.onResult?.({\n ...args,\n result,\n structuredResult,\n });\n if (legacyReplacement !== undefined) {\n result = legacyReplacement;\n structuredResult = undefined;\n replaced = true;\n }\n }\n return replaced ? (structuredResult ?? result) : undefined;\n }\n\n private async runToolInputMiddlewares(\n args: ToolHookArgs & { turn: number; originalArgs: string },\n ): Promise<string> {\n let current = args.args;\n for (const middleware of this.activeMiddlewares()) {\n const replacement = await middleware.onToolInput?.({\n ...args,\n args: current,\n });\n if (replacement?.args !== undefined) {\n current =\n typeof replacement.args === \"string\"\n ? replacement.args\n : JSON.stringify(replacement.args);\n }\n }\n return current;\n }\n\n private activeMiddlewares(): AgentMiddleware[] {\n return [...this.agent.middlewares, ...this.requestMiddlewares];\n }\n\n private async evaluateToolApproval(\n tool: AnyTool | undefined,\n hookArgs: ToolHookArgs,\n ): Promise<{ approved: true } | { approved: false; result: string } | undefined> {\n if (tool?.approval === undefined) {\n return undefined;\n }\n const policy = tool.approval as ToolApprovalPolicy<unknown>;\n const context = approvalContext(tool, hookArgs, this.agent, this.runContext);\n const required = await policy.when(context);\n if (!required) {\n return { approved: true };\n }\n\n const reason = await resolveApprovalText(policy.reason, context);\n const rejectMessage = await resolveApprovalText(policy.rejectMessage, context);\n return this.requestApproval(tool, hookArgs, compact({ reason, rejectMessage }));\n }\n\n private async requestApproval(\n tool: AnyTool | undefined,\n hookArgs: ToolHookArgs,\n options: ToolApprovalRequestOptions,\n ): Promise<{ approved: true } | { approved: false; result: string }> {\n const request = compact({\n ...approvalContext(tool, hookArgs, this.agent, this.runContext),\n reason: options.reason,\n rejectMessage: options.rejectMessage,\n }) as ToolApprovalRequest;\n if (this.approvals === undefined) {\n throw new ToolApprovalRequiredError(request);\n }\n\n const decision = normalizeApprovalDecision(await this.approvals.handler(request));\n if (decision.approved) {\n return { approved: true };\n }\n return {\n approved: false,\n result:\n decision.rejectMessage ??\n decision.reason ??\n request.rejectMessage ??\n \"Tool approval was rejected.\",\n };\n }\n}\n\nfunction approvalContext(\n tool: AnyTool | undefined,\n hookArgs: ToolHookArgs,\n agent: Agent,\n run: ToolExecutionRunContext,\n): ToolApprovalContext {\n const rawParsedArgs = parseToolArgs(hookArgs.args);\n const parsedArgs = tool?.parseApprovalArgs?.(rawParsedArgs) ?? rawParsedArgs;\n return compact({\n toolName: hookArgs.toolName,\n args: parsedArgs,\n rawArgs: hookArgs.args,\n toolCallId: hookArgs.toolCallId,\n internalCallId: hookArgs.internalCallId,\n run: compact({\n agentId: agent.id,\n runId: run.runId,\n sessionId: run.sessionId,\n metadata: run.metadata,\n }),\n }) as ToolApprovalContext;\n}\n\nfunction normalizeApprovalDecision(decision: ToolApprovalDecision): {\n approved: boolean;\n reason?: string;\n rejectMessage?: string;\n} {\n if (typeof decision === \"boolean\") {\n return { approved: decision };\n }\n return decision;\n}\n\nasync function resolveApprovalText<Args>(\n value: string | ((ctx: ToolApprovalContext<Args>) => string | Promise<string>) | undefined,\n context: ToolApprovalContext<Args>,\n): Promise<string | undefined> {\n return typeof value === \"function\" ? value(context as ToolApprovalContext<Args>) : value;\n}\n\nfunction normalizeToolOutputMiddlewareResult(result: ToolOutputMiddlewareResult): {\n result?: string | undefined;\n structuredResult?: ToolResultContent[] | undefined;\n} {\n if (typeof result === \"string\") {\n return { result };\n }\n return result ?? {};\n}\n\nfunction toolTraceMetadata(tool: AnyTool | undefined): JsonObject | undefined {\n if (tool === undefined) {\n return undefined;\n }\n const metadata = (tool as { [MCP_TOOL_METADATA_KEY]?: unknown })[MCP_TOOL_METADATA_KEY];\n const mcpMetadata =\n typeof metadata === \"object\" && metadata !== null\n ? (metadata as { serverName?: unknown })\n : undefined;\n return {\n approvalRequired: tool.approval !== undefined,\n ...(typeof mcpMetadata?.serverName === \"string\" && mcpMetadata.serverName.length > 0\n ? { mcpServerName: mcpMetadata.serverName }\n : {}),\n };\n}\n\nasync function recordToolError(\n toolObservers: ActiveToolObservers | undefined,\n turn: number | undefined,\n toolCall: ToolCall,\n internalCallId: string,\n args: string,\n error: unknown,\n): Promise<void> {\n await toolObservers?.error({\n turn: turn ?? 0,\n toolCall,\n toolName: toolCall.function.name,\n internalCallId,\n args,\n error,\n toolCallId: toolCall.callId,\n });\n}\n\nfunction toolOutputToText(output: NormalizedToolOutput): string {\n return typeof output === \"string\" ? output : toolResultContentToText(output);\n}\n\nfunction toolOutputToStructuredResult(\n output: NormalizedToolOutput,\n): ToolResultContent[] | undefined {\n return typeof output === \"string\" ? undefined : output;\n}\n\nfunction agentToolEventPayload(\n toolCall: ToolCall,\n internalCallId: string,\n event: ToolCallStreamEvent,\n): AgentToolEventPayload | undefined {\n if (typeof event.agentId !== \"string\" || event.agentId.length === 0) {\n return undefined;\n }\n return compact({\n type: \"agent_tool_event\" as const,\n toolName: toolCall.function.name,\n toolCallId: toolCall.callId,\n internalCallId,\n agentId: event.agentId,\n agentName: event.agentName,\n event: event.event as AgentChildStreamEvent,\n });\n}\n","import type { Message as MessageType } from \"../completion/index\";\n\nexport function extractRagText(message: MessageType): string | undefined {\n if (message.role === \"user\") {\n return message.content.flatMap((item) => (item.type === \"text\" ? [item.text] : [])).join(\"\\n\");\n }\n\n if (message.role === \"tool\") {\n return message.content\n .flatMap((item) => item.content.flatMap((part) => (part.type === \"text\" ? [part.text] : [])))\n .join(\"\\n\");\n }\n\n return undefined;\n}\n","import type {\n AgentGenerationEndArgs,\n AgentGenerationErrorArgs,\n AgentGenerationObserver,\n AgentGenerationStartArgs,\n AgentGenerationUpdateArgs,\n AgentObserverRegistration,\n AgentRunEndArgs,\n AgentRunErrorArgs,\n AgentRunEventArgs,\n AgentRunObserver,\n AgentRunStartArgs,\n AgentToolEndArgs,\n AgentToolErrorArgs,\n AgentToolObserver,\n AgentToolStartArgs,\n AgentToolStreamEventArgs,\n AgentTraceInfo,\n} from \"./types\";\n\nexport async function startAgentRunObservers(\n registrations: AgentObserverRegistration[],\n args: AgentRunStartArgs,\n failOnObserverError: boolean,\n): Promise<ActiveAgentRunObservers> {\n const runObservers: AgentRunObserver[] = [];\n for (const registration of registrations) {\n try {\n const runObserver = await registration.observer.startRun(args);\n if (runObserver !== undefined) {\n runObservers.push(runObserver);\n }\n } catch (error) {\n if (failOnObserverError || registration.failOnObserverError === true) {\n throw error;\n }\n }\n }\n\n return new ActiveAgentRunObservers(runObservers, failOnObserverError);\n}\n\nexport class ActiveAgentRunObservers {\n readonly trace: AgentTraceInfo | undefined;\n\n constructor(\n private readonly runObservers: AgentRunObserver[],\n private readonly failOnObserverError: boolean,\n ) {\n this.trace = runObservers.find((observer) => observer.trace !== undefined)?.trace;\n }\n\n async startGeneration(args: AgentGenerationStartArgs): Promise<ActiveGenerationObservers> {\n const generationObservers: AgentGenerationObserver[] = [];\n for (const runObserver of this.runObservers) {\n if (runObserver.startGeneration === undefined) {\n continue;\n }\n try {\n const generationObserver = await runObserver.startGeneration(args);\n if (generationObserver !== undefined) {\n generationObservers.push(generationObserver);\n }\n } catch (error) {\n this.handleError(error);\n }\n }\n return new ActiveGenerationObservers(generationObservers, this.failOnObserverError);\n }\n\n async startTool(args: AgentToolStartArgs): Promise<ActiveToolObservers> {\n const toolObservers: AgentToolObserver[] = [];\n for (const runObserver of this.runObservers) {\n if (runObserver.startTool === undefined) {\n continue;\n }\n try {\n const toolObserver = await runObserver.startTool(args);\n if (toolObserver !== undefined) {\n toolObservers.push(toolObserver);\n }\n } catch (error) {\n this.handleError(error);\n }\n }\n return new ActiveToolObservers(toolObservers, this.failOnObserverError);\n }\n\n async end(args: AgentRunEndArgs): Promise<void> {\n for (const runObserver of this.runObservers) {\n try {\n await runObserver.end(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n async error(args: AgentRunErrorArgs): Promise<void> {\n for (const runObserver of this.runObservers) {\n if (runObserver.error === undefined) {\n continue;\n }\n try {\n await runObserver.error(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n async event(args: AgentRunEventArgs): Promise<void> {\n for (const runObserver of this.runObservers) {\n if (runObserver.event === undefined) {\n continue;\n }\n try {\n await runObserver.event(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n private handleError(error: unknown): void {\n if (this.failOnObserverError) {\n throw error;\n }\n }\n}\n\nexport class ActiveGenerationObservers {\n constructor(\n private readonly generationObservers: AgentGenerationObserver[],\n private readonly failOnObserverError: boolean,\n ) {}\n\n async end(args: AgentGenerationEndArgs): Promise<void> {\n for (const observer of this.generationObservers) {\n try {\n await observer.end(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n async error(args: AgentGenerationErrorArgs): Promise<void> {\n for (const observer of this.generationObservers) {\n if (observer.error === undefined) {\n continue;\n }\n try {\n await observer.error(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n async update(args: AgentGenerationUpdateArgs): Promise<void> {\n for (const observer of this.generationObservers) {\n if (observer.update === undefined) {\n continue;\n }\n try {\n await observer.update(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n private handleError(error: unknown): void {\n if (this.failOnObserverError) {\n throw error;\n }\n }\n}\n\nexport class ActiveToolObservers {\n constructor(\n private readonly toolObservers: AgentToolObserver[],\n private readonly failOnObserverError: boolean,\n ) {}\n\n async streamEvent(args: AgentToolStreamEventArgs): Promise<void> {\n for (const observer of this.toolObservers) {\n if (observer.streamEvent === undefined) {\n continue;\n }\n try {\n await observer.streamEvent(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n async end(args: AgentToolEndArgs): Promise<void> {\n for (const observer of this.toolObservers) {\n try {\n await observer.end(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n async error(args: AgentToolErrorArgs): Promise<void> {\n for (const observer of this.toolObservers) {\n if (observer.error === undefined) {\n continue;\n }\n try {\n await observer.error(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n private handleError(error: unknown): void {\n if (this.failOnObserverError) {\n throw error;\n }\n }\n}\n","import type { Agent } from \"../agent/agent\";\nimport { isStreamingCompletionModel } from \"../completion/create-completion\";\nimport {\n assertCompletionRequestSupported,\n type CompletionModel,\n CompletionRequestBuilder,\n type CompletionResponse,\n type JsonObject,\n Message,\n type Message as MessageType,\n type ToolCall,\n type ToolDefinition,\n type ToolResult,\n textFromAssistantContent,\n Usage,\n} from \"../completion/index\";\nimport type { PromptHook } from \"../hooks\";\nimport { runControl } from \"../hooks\";\nimport { createAsyncQueue } from \"../internal/async-queue\";\nimport { compact } from \"../internal/compact\";\nimport { PromptRequestMemory } from \"../internal/prompt-runtime/memory\";\nimport { fetchDynamicContext, fetchToolDefinitions } from \"../internal/prompt-runtime/retrieval\";\nimport { CompletionStreamAccumulator } from \"../internal/prompt-runtime/stream-accumulator\";\nimport { addTurn, isGenerationDeltaEvent } from \"../internal/prompt-runtime/stream-events\";\nimport {\n type AgentToolEventPayload,\n ToolCallExecutor,\n type ToolExecutionEventPayload,\n type ToolResultEventPayload,\n} from \"../internal/prompt-runtime/tool-execution\";\nimport { extractRagText } from \"../internal/rag-text\";\nimport type { MemoryContext } from \"../memory/types\";\nimport { type ActiveAgentRunObservers, startAgentRunObservers } from \"../observability/group\";\nimport type { AgentTraceOptions } from \"../observability/types\";\nimport { toReadableStream } from \"../streaming\";\nimport type { ToolApprovalsOptions } from \"../tool\";\nimport type { AgentMiddleware, ToolMiddleware } from \"../tool/middleware\";\nimport { MaxTurnsError, PromptCancelledError } from \"./errors\";\nimport type { AgentStreamEvent, PromptResponse } from \"./types\";\n\nexport class PromptRequest<M extends CompletionModel = CompletionModel> {\n private chatHistory: MessageType[];\n private maxTurnCount: number;\n private activeHook: PromptHook | undefined;\n private approvalOptions: ToolApprovalsOptions | undefined;\n private concurrency = 1;\n private traceOptions: AgentTraceOptions | undefined;\n private requestMiddlewares: AgentMiddleware[] = [];\n private readonly steeringMessages: MessageType[] = [];\n private runState: \"idle\" | \"running\" | \"completed\" | \"errored\" | \"cancelled\" = \"idle\";\n private readonly memoryRecorder: PromptRequestMemory;\n\n private constructor(\n private readonly agent: Agent<M>,\n private readonly promptMessage: MessageType,\n initialHistory: MessageType[] = [],\n private readonly memoryContext: MemoryContext | undefined = undefined,\n ) {\n this.chatHistory = initialHistory;\n this.maxTurnCount = agent.defaultMaxTurns ?? 0;\n this.activeHook = agent.hook;\n this.approvalOptions = agent.approvals;\n this.memoryRecorder = new PromptRequestMemory(agent, memoryContext, initialHistory);\n }\n\n static fromAgent<M extends CompletionModel>(\n agent: Agent<M>,\n prompt: string | MessageType | MessageType[],\n options: { memoryContext?: MemoryContext | undefined } = {},\n ): PromptRequest<M> {\n const normalized = normalizePromptInput(prompt);\n return new PromptRequest(agent, normalized.prompt, normalized.history, options.memoryContext);\n }\n\n maxTurns(maxTurns: number): this {\n this.maxTurnCount = maxTurns;\n return this;\n }\n\n withHook(hook: PromptHook): this {\n this.activeHook = hook;\n return this;\n }\n\n approvals(options: ToolApprovalsOptions): this {\n this.approvalOptions = options;\n return this;\n }\n\n /**\n * @deprecated Use `withHook` instead.\n */\n requestHook(hook: PromptHook): this {\n return this.withHook(hook);\n }\n\n withToolConcurrency(concurrency: number): this {\n this.concurrency = Math.max(1, concurrency);\n return this;\n }\n\n withMiddleware(middleware: AgentMiddleware): this {\n this.requestMiddlewares.push(middleware);\n return this;\n }\n\n withMiddlewares(middlewares: AgentMiddleware[]): this {\n this.requestMiddlewares.push(...middlewares);\n return this;\n }\n\n /**\n * @deprecated Use `withMiddleware` instead.\n */\n withToolMiddleware(middleware: ToolMiddleware): this {\n return this.withMiddleware(middleware);\n }\n\n /**\n * @deprecated Use `withMiddlewares` instead.\n */\n withToolMiddlewares(middlewares: ToolMiddleware[]): this {\n return this.withMiddlewares(middlewares);\n }\n\n withTrace(trace: AgentTraceOptions): this {\n this.traceOptions = trace;\n return this;\n }\n\n steer(input: string | MessageType | MessageType[]): boolean {\n if (this.isTerminal()) {\n return false;\n }\n\n this.steeringMessages.push(...normalizeSteeringInput(input));\n return true;\n }\n\n async send(): Promise<PromptResponse> {\n this.startRun();\n const runId = globalThis.crypto.randomUUID();\n const newMessages: MessageType[] = [this.promptMessage];\n this.chatHistory = await this.memoryRecorder.prepareRun(runId, newMessages);\n const pendingTurnMessages = this.memoryRecorder.pendingTurnMessages(newMessages);\n let usage = Usage.empty();\n let currentTurns = 0;\n let lastPrompt = this.promptMessage;\n const runObservers = await this.startRunObservers();\n\n try {\n await this.runRunStartHook(newMessages);\n while (currentTurns <= this.maxTurnCount + 1) {\n const prompt = newMessages.at(-1);\n if (prompt === undefined) {\n throw new Error(\"PromptRequest requires at least one message\");\n }\n\n lastPrompt = prompt;\n currentTurns += 1;\n\n const historyForRequest = [...this.chatHistory, ...newMessages.slice(0, -1)];\n await this.runTurnStartHook(currentTurns, prompt, historyForRequest, newMessages);\n await this.runCompletionCallHook(prompt, historyForRequest, newMessages);\n\n const ragText = extractRagText(prompt);\n const dynamicContext = await fetchDynamicContext(this.agent, ragText);\n const toolDefs = await fetchToolDefinitions(this.agent, ragText);\n let request = new CompletionRequestBuilder(this.agent.model, prompt)\n .instructions(this.agent.instructions)\n .messages(historyForRequest)\n .documents([...this.agent.staticContext, ...dynamicContext])\n .tools(toolDefs)\n .temperature(this.agent.temperature)\n .maxTokens(this.agent.maxTokens)\n .additionalParams(this.agent.additionalParams)\n .toolChoice(this.agent.toolChoice)\n .outputSchema(this.agent.outputSchema)\n .build();\n request = (await this.runCompletionRequestMiddlewares(\n request,\n currentTurns,\n )) as typeof request;\n\n let response: CompletionResponse;\n try {\n response = await this.runCompletion(request, currentTurns, runObservers);\n } catch (error) {\n await this.runCompletionErrorHook(prompt, error, newMessages);\n throw error;\n }\n response = await this.runCompletionResponseMiddlewares(request, response, currentTurns);\n usage = Usage.add(usage, response.usage);\n await this.runCompletionResponseHook(prompt, response, newMessages);\n await this.runTurnEndHook(currentTurns, response, newMessages);\n\n const assistantMessage = Message.assistant(response.choice, response.messageId);\n newMessages.push(assistantMessage);\n await this.memoryRecorder.commitMessages(\n runId,\n currentTurns,\n [assistantMessage],\n pendingTurnMessages,\n );\n const toolCalls = response.choice.filter(\n (item): item is ToolCall => item.type === \"tool_call\",\n );\n if (toolCalls.length === 0) {\n if (\n await this.drainSteeringMessages(runId, currentTurns, newMessages, pendingTurnMessages)\n ) {\n await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);\n continue;\n }\n\n const result: PromptResponse = {\n output: textFromAssistantContent(response.choice),\n usage,\n messages: [...newMessages],\n trace: runObservers.trace,\n };\n await this.runRunEndHook(result, newMessages);\n await runObservers.end(result);\n await this.memoryRecorder.commitCompletedRun(\n runId,\n currentTurns,\n newMessages,\n pendingTurnMessages,\n );\n this.runState = \"completed\";\n return result;\n }\n\n const toolResults = await this.executeToolCalls(\n runId,\n toolCalls,\n newMessages,\n undefined,\n undefined,\n {\n turn: currentTurns,\n runObservers,\n toolDefinitions: request.tools,\n },\n );\n const toolMessage = Message.tool(toolResults);\n newMessages.push(toolMessage);\n await this.memoryRecorder.commitMessages(\n runId,\n currentTurns,\n [toolMessage],\n pendingTurnMessages,\n );\n await this.drainSteeringMessages(runId, currentTurns, newMessages, pendingTurnMessages);\n await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);\n }\n\n throw new MaxTurnsError(this.maxTurnCount, [...this.chatHistory, ...newMessages], lastPrompt);\n } catch (error) {\n const finalError = await this.runRunErrorHook(error, usage, newMessages);\n this.runState = finalError instanceof PromptCancelledError ? \"cancelled\" : \"errored\";\n await runObservers.error({ error: finalError, usage, messages: [...newMessages] });\n await this.memoryRecorder.recordError(runId, finalError, newMessages);\n throw finalError;\n }\n }\n\n async *stream(): AsyncIterable<AgentStreamEvent> {\n if (!this.agent.model.capabilities.streaming || !isStreamingCompletionModel(this.agent.model)) {\n throw new Error(\"This completion model does not support streaming\");\n }\n\n this.startRun();\n const runId = globalThis.crypto.randomUUID();\n const newMessages: MessageType[] = [this.promptMessage];\n this.chatHistory = await this.memoryRecorder.prepareRun(runId, newMessages);\n const pendingTurnMessages = this.memoryRecorder.pendingTurnMessages(newMessages);\n let usage = Usage.empty();\n let currentTurns = 0;\n let lastPrompt = this.promptMessage;\n const runObservers = await this.startRunObservers();\n const emit = async (event: AgentStreamEvent): Promise<AgentStreamEvent> => {\n await this.recordAgentEvent(runId, event);\n return event;\n };\n\n try {\n await this.runRunStartHook(newMessages);\n while (currentTurns <= this.maxTurnCount + 1) {\n const prompt = newMessages.at(-1);\n if (prompt === undefined) {\n throw new Error(\"PromptRequest requires at least one message\");\n }\n\n lastPrompt = prompt;\n currentTurns += 1;\n\n const historyForRequest = [...this.chatHistory, ...newMessages.slice(0, -1)];\n yield await emit({\n type: \"turn_start\",\n turn: currentTurns,\n prompt,\n history: historyForRequest,\n });\n await this.runTurnStartHook(currentTurns, prompt, historyForRequest, newMessages);\n await this.runCompletionCallHook(prompt, historyForRequest, newMessages);\n\n const ragText = extractRagText(prompt);\n const dynamicContext = await fetchDynamicContext(this.agent, ragText);\n const toolDefs = await fetchToolDefinitions(this.agent, ragText);\n let request = new CompletionRequestBuilder(this.agent.model, prompt)\n .instructions(this.agent.instructions)\n .messages(historyForRequest)\n .documents([...this.agent.staticContext, ...dynamicContext])\n .tools(toolDefs)\n .temperature(this.agent.temperature)\n .maxTokens(this.agent.maxTokens)\n .additionalParams(this.agent.additionalParams)\n .toolChoice(this.agent.toolChoice)\n .outputSchema(this.agent.outputSchema)\n .build();\n request = (await this.runCompletionRequestMiddlewares(\n request,\n currentTurns,\n )) as typeof request;\n\n assertCompletionRequestSupported(this.agent.model, request, { streaming: true });\n const providerRequest = this.providerTraceRequest(request, { stream: true });\n const generationObservers = await runObservers.startGeneration(\n compact({\n turn: currentTurns,\n request,\n providerRequest,\n modelInfo: {\n provider: this.agent.model.provider,\n defaultModel: this.agent.model.defaultModel,\n capabilities: this.agent.model.capabilities,\n },\n }),\n );\n const accumulator = new CompletionStreamAccumulator();\n const generationStartedAt = Date.now();\n let firstDeltaMs: number | undefined;\n const bufferResponseEvents = this.shouldBufferStreamResponseEvents();\n const emittedToolCallIds = new Set<string>();\n try {\n for await (const event of this.agent.model.streamCompletion(request)) {\n if (firstDeltaMs === undefined && isGenerationDeltaEvent(event.type)) {\n firstDeltaMs = Date.now() - generationStartedAt;\n }\n const mapped = accumulator.accept(event);\n if (event.type === \"error\") {\n throw event.error;\n }\n if (mapped !== undefined) {\n await generationObservers.update?.({ turn: currentTurns, delta: mapped });\n if (mapped.type === \"tool_call\") {\n emittedToolCallIds.add(mapped.toolCall.id);\n }\n if (!bufferResponseEvents) {\n yield await emit(addTurn(currentTurns, mapped));\n }\n }\n }\n } catch (error) {\n await generationObservers.error({ turn: currentTurns, error });\n await this.runCompletionErrorHook(prompt, error, newMessages);\n throw error;\n }\n\n let response = accumulator.response();\n await generationObservers.end(\n compact({\n turn: currentTurns,\n response,\n firstDeltaMs,\n }),\n );\n response = await this.runCompletionResponseMiddlewares(request, response, currentTurns);\n usage = Usage.add(usage, response.usage);\n await this.runCompletionResponseHook(prompt, response, newMessages);\n await this.runTurnEndHook(currentTurns, response, newMessages);\n\n const assistantMessage = Message.assistant(response.choice, response.messageId);\n newMessages.push(assistantMessage);\n await this.memoryRecorder.commitMessages(\n runId,\n currentTurns,\n [assistantMessage],\n pendingTurnMessages,\n );\n const toolCalls = response.choice.filter(\n (item): item is ToolCall => item.type === \"tool_call\",\n );\n if (bufferResponseEvents) {\n for (const event of responseStreamEvents(currentTurns, response)) {\n yield await emit(event);\n }\n } else {\n for (const toolCall of toolCalls) {\n if (!emittedToolCallIds.has(toolCall.id)) {\n yield await emit({ type: \"tool_call\", turn: currentTurns, toolCall });\n }\n }\n }\n yield await emit({ type: \"turn_end\", turn: currentTurns, response });\n\n if (toolCalls.length === 0) {\n if (\n await this.drainSteeringMessages(runId, currentTurns, newMessages, pendingTurnMessages)\n ) {\n await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);\n continue;\n }\n\n const result: PromptResponse = {\n output: textFromAssistantContent(response.choice),\n usage,\n messages: [...newMessages],\n trace: runObservers.trace,\n };\n await this.runRunEndHook(result, newMessages);\n await runObservers.end(result);\n await this.memoryRecorder.commitCompletedRun(\n runId,\n currentTurns,\n newMessages,\n pendingTurnMessages,\n );\n this.runState = \"completed\";\n yield await emit({\n type: \"final\",\n runId,\n output: result.output,\n usage: result.usage,\n messages: result.messages,\n trace: result.trace,\n });\n return;\n }\n\n const toolResultEvents = createAsyncQueue<ToolExecutionEventPayload>();\n const toolResultsPromise = this.executeToolCalls(\n runId,\n toolCalls,\n newMessages,\n (result) => {\n toolResultEvents.enqueue(result);\n },\n (event) => {\n toolResultEvents.enqueue(event);\n },\n {\n turn: currentTurns,\n runObservers,\n toolDefinitions: request.tools,\n },\n );\n toolResultsPromise.then(\n () => toolResultEvents.close(),\n (error: unknown) => toolResultEvents.throw(error),\n );\n for await (const result of toolResultEvents) {\n yield await emit({ turn: currentTurns, ...result });\n }\n const toolResults = await toolResultsPromise;\n const toolMessage = Message.tool(toolResults);\n newMessages.push(toolMessage);\n await this.memoryRecorder.commitMessages(\n runId,\n currentTurns,\n [toolMessage],\n pendingTurnMessages,\n );\n await this.drainSteeringMessages(runId, currentTurns, newMessages, pendingTurnMessages);\n await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);\n }\n\n throw new MaxTurnsError(this.maxTurnCount, [...this.chatHistory, ...newMessages], lastPrompt);\n } catch (error) {\n const finalError = await this.runRunErrorHook(error, usage, newMessages);\n this.runState = finalError instanceof PromptCancelledError ? \"cancelled\" : \"errored\";\n await runObservers.error({ error: finalError, usage, messages: [...newMessages] });\n await this.memoryRecorder.recordError(runId, finalError, newMessages);\n yield await emit({ type: \"error\", error: finalError });\n throw finalError;\n }\n }\n\n readableStream(): ReadableStream<Uint8Array> {\n return toReadableStream(this.stream());\n }\n\n private async runCompletion(\n request: ReturnType<CompletionRequestBuilder[\"build\"]>,\n turn: number,\n runObservers: ActiveAgentRunObservers,\n ): Promise<CompletionResponse> {\n assertCompletionRequestSupported(this.agent.model, request);\n const providerRequest = this.providerTraceRequest(request);\n const generationObservers = await runObservers.startGeneration(\n compact({\n turn,\n request,\n providerRequest,\n modelInfo: {\n provider: this.agent.model.provider,\n defaultModel: this.agent.model.defaultModel,\n capabilities: this.agent.model.capabilities,\n },\n }),\n );\n try {\n const response = await this.agent.model.completion(request);\n await generationObservers.end({ turn, response });\n return response;\n } catch (error) {\n await generationObservers.error({ turn, error });\n throw error;\n }\n }\n\n private providerTraceRequest(\n request: ReturnType<CompletionRequestBuilder[\"build\"]>,\n options: { stream?: boolean | undefined } = {},\n ): JsonObject | undefined {\n try {\n return this.agent.model.traceRequest?.(request, options);\n } catch (error) {\n return {\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n private async executeToolCalls(\n runId: string,\n toolCalls: ToolCall[],\n newMessages: MessageType[],\n onResult?: (result: ToolResultEventPayload) => void,\n onStreamEvent?: (event: AgentToolEventPayload) => void,\n observation?: {\n turn: number;\n runObservers: ActiveAgentRunObservers;\n toolDefinitions?: ToolDefinition[];\n },\n ): Promise<ToolResult[]> {\n const executor = new ToolCallExecutor(\n this.agent,\n this.activeHook,\n this.approvalOptions,\n {\n runId,\n sessionId: this.memoryContext?.sessionId,\n metadata: this.memoryContext?.metadata,\n },\n this.concurrency,\n this.requestMiddlewares,\n (reason) => this.cancelled(newMessages, reason),\n );\n return executor.execute(toolCalls, onResult, onStreamEvent, observation);\n }\n\n private async startRunObservers(): Promise<ActiveAgentRunObservers> {\n const failOnObserverError =\n this.traceOptions?.failOnObserverError === true ||\n this.agent.observers.some((registration) => registration.failOnObserverError === true);\n return startAgentRunObservers(\n this.agent.observers,\n {\n agentName: this.agent.name,\n agentDescription: this.agent.description,\n instructions: this.agent.instructions,\n trace: this.traceOptions,\n prompt: this.promptMessage,\n history: this.chatHistory,\n maxTurns: this.maxTurnCount,\n },\n failOnObserverError,\n );\n }\n\n private async recordAgentEvent(runId: string, event: AgentStreamEvent): Promise<void> {\n const registration = this.agent.eventStore;\n if (registration === undefined) {\n return;\n }\n if (registration.options.include === \"agent_tool_events\" && event.type !== \"agent_tool_event\") {\n return;\n }\n\n const turn = \"turn\" in event ? event.turn : undefined;\n const agentId = event.type === \"agent_tool_event\" ? event.agentId : this.agent.id;\n const agentName = event.type === \"agent_tool_event\" ? event.agentName : this.agent.name;\n await registration.store.append({\n runId,\n agentId,\n ...compact({ agentName, turn }),\n ...(event.type === \"agent_tool_event\"\n ? compact({\n toolName: event.toolName,\n toolCallId: event.toolCallId,\n internalCallId: event.internalCallId,\n })\n : {}),\n event,\n });\n }\n\n private async runCompletionCallHook(\n prompt: MessageType,\n history: MessageType[],\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onCompletionCall?.({\n prompt,\n history,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runRunStartHook(newMessages: MessageType[]): Promise<void> {\n const action = await this.activeHook?.onRunStart?.({\n prompt: this.promptMessage,\n history: this.chatHistory,\n maxTurns: this.maxTurnCount,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runRunEndHook(result: PromptResponse, newMessages: MessageType[]): Promise<void> {\n const action = await this.activeHook?.onRunEnd?.({\n output: result.output,\n usage: result.usage,\n messages: result.messages,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runRunErrorHook(\n error: unknown,\n usage: Usage,\n newMessages: MessageType[],\n ): Promise<unknown> {\n const action = await this.activeHook?.onRunError?.({\n error,\n usage,\n messages: [...this.chatHistory, ...newMessages],\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n return this.cancelled(newMessages, action.reason);\n }\n return error;\n }\n\n private async runTurnStartHook(\n turn: number,\n prompt: MessageType,\n history: MessageType[],\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onTurnStart?.({\n turn,\n prompt,\n history,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runTurnEndHook(\n turn: number,\n response: CompletionResponse,\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onTurnEnd?.({\n turn,\n response,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runCompletionRequestMiddlewares(\n request: ReturnType<CompletionRequestBuilder[\"build\"]>,\n turn: number,\n ): Promise<ReturnType<CompletionRequestBuilder[\"build\"]>> {\n let current = request;\n for (const middleware of this.activeMiddlewares()) {\n const replacement = await middleware.onCompletionRequest?.({\n turn,\n request: current,\n originalRequest: request,\n });\n if (replacement?.request !== undefined) {\n current = replacement.request;\n }\n }\n return current;\n }\n\n private async runCompletionResponseMiddlewares(\n request: ReturnType<CompletionRequestBuilder[\"build\"]>,\n response: CompletionResponse,\n turn: number,\n ): Promise<CompletionResponse> {\n let current = response;\n for (const middleware of this.activeMiddlewares()) {\n const replacement = await middleware.onCompletionResponse?.({\n turn,\n request,\n response: current,\n originalResponse: response,\n });\n if (replacement?.response !== undefined) {\n current = replacement.response;\n }\n }\n return current;\n }\n\n private async runCompletionResponseHook(\n prompt: MessageType,\n response:\n | Awaited<ReturnType<M[\"completion\"]>>\n | Awaited<ReturnType<CompletionModel[\"completion\"]>>,\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onCompletionResponse?.({\n prompt,\n response,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runCompletionErrorHook(\n prompt: MessageType,\n error: unknown,\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onCompletionError?.({\n prompt,\n error,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private activeMiddlewares(): AgentMiddleware[] {\n return [...this.agent.middlewares, ...this.requestMiddlewares];\n }\n\n private shouldBufferStreamResponseEvents(): boolean {\n return (\n this.activeHook?.onCompletionResponse !== undefined ||\n this.activeMiddlewares().some((middleware) => middleware.onCompletionResponse !== undefined)\n );\n }\n\n private async drainSteeringMessages(\n runId: string,\n turn: number,\n newMessages: MessageType[],\n pendingTurnMessages: MessageType[],\n ): Promise<boolean> {\n const messages = this.steeringMessages.splice(0);\n if (messages.length === 0) {\n return false;\n }\n\n newMessages.push(...messages);\n await this.memoryRecorder.commitMessages(runId, turn, messages, pendingTurnMessages);\n return true;\n }\n\n private startRun(): void {\n if (this.runState === \"idle\") {\n this.runState = \"running\";\n return;\n }\n if (this.runState === \"running\") {\n throw new Error(\"PromptRequest is already running.\");\n }\n throw new Error(\"PromptRequest has already been used.\");\n }\n\n private isTerminal(): boolean {\n return (\n this.runState === \"completed\" || this.runState === \"errored\" || this.runState === \"cancelled\"\n );\n }\n\n private cancelled(newMessages: MessageType[], reason: string): PromptCancelledError {\n return new PromptCancelledError([...this.chatHistory, ...newMessages], reason);\n }\n}\n\nfunction normalizePromptInput(prompt: string | MessageType | MessageType[]): {\n prompt: MessageType;\n history: MessageType[];\n} {\n if (typeof prompt === \"string\") {\n return { prompt: Message.user(prompt), history: [] };\n }\n if (!Array.isArray(prompt)) {\n return { prompt, history: [] };\n }\n if (prompt.length === 0) {\n throw new TypeError(\"Prompt transcript must contain at least one message.\");\n }\n const activePrompt = prompt.at(-1);\n if (activePrompt === undefined) {\n throw new TypeError(\"Prompt transcript must contain at least one message.\");\n }\n return {\n prompt: activePrompt,\n history: prompt.slice(0, -1),\n };\n}\n\nfunction normalizeSteeringInput(input: string | MessageType | MessageType[]): MessageType[] {\n if (typeof input === \"string\") {\n return [Message.user(input)];\n }\n return Array.isArray(input) ? [...input] : [input];\n}\n\nfunction responseStreamEvents(turn: number, response: CompletionResponse): AgentStreamEvent[] {\n const events: AgentStreamEvent[] = [];\n for (const item of response.choice) {\n if (item.type === \"text\") {\n if (item.text.length > 0) {\n events.push({ type: \"text_delta\", turn, delta: item.text });\n }\n continue;\n }\n\n if (item.type === \"reasoning\") {\n if (item.content === undefined) {\n if (item.text.length > 0) {\n events.push(\n compact({ type: \"reasoning_delta\" as const, turn, delta: item.text, id: item.id }),\n );\n }\n continue;\n }\n\n for (const content of item.content) {\n const delta =\n content.type === \"encrypted\" || content.type === \"redacted\" ? content.data : content.text;\n events.push(\n compact({\n type: \"reasoning_delta\" as const,\n turn,\n delta,\n id: item.id,\n contentType: content.type,\n signature: content.type === \"text\" ? content.signature : undefined,\n }),\n );\n }\n continue;\n }\n\n if (item.type === \"tool_call\") {\n events.push({ type: \"tool_call\", turn, toolCall: item });\n }\n }\n return events;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGO,IAAM,gBAAN,cAA4B,MAAM;AAAA,EACvC,YACW,UACA,aACA,QACT;AACA,UAAM,2BAA2B,QAAQ,EAAE;AAJlC;AACA;AACA;AAGT,SAAK,OAAO;AAAA,EACd;AAAA,EANW;AAAA,EACA;AAAA,EACA;AAKb;AAEO,IAAM,uBAAN,cAAmC,MAAM;AAAA,EAC9C,YACW,aACA,QACT;AACA,UAAM,qBAAqB,MAAM,EAAE;AAH1B;AACA;AAGT,SAAK,OAAO;AAAA,EACd;AAAA,EALW;AAAA,EACA;AAKb;AAEO,IAAM,4BAAN,cAAwC,MAAM;AAAA,EACnD,YAAqB,SAA8B;AACjD,UAAM,8BAA8B,QAAQ,QAAQ,0CAA0C;AAD3E;AAEnB,SAAK,OAAO;AAAA,EACd;AAAA,EAHqB;AAIvB;;;AClBO,SAAS,mBAAqC;AACnD,QAAM,SAAc,CAAC;AACrB,QAAM,UAAiC,CAAC;AACxC,MAAI,SAAS;AACb,MAAI;AAEJ,WAAS,QAAc;AACrB,WAAO,QAAQ,SAAS,KAAK,OAAO,SAAS,GAAG;AAC9C,YAAM,SAAS,QAAQ,MAAM;AAC7B,YAAM,QAAQ,OAAO,MAAM;AAC3B,UAAI,WAAW,QAAW;AACxB,eAAO,QAAQ,EAAE,OAAO,MAAM,M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ACH;AAAA,MACF;AACA;AAAA,IACF;AAEA,QAAI,KAAK,SAAS,aAAa;AAC7B,aAAO,KAAK,EAAE,MAAM,aAAa,MAAM,UAAU,KAAK,CAAC;AAAA,IACzD;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
@@ -8,7 +8,7 @@ import {
8
8
  import {
9
9
  isToolResultContentArray,
10
10
  serializeToolResultOutput
11
- } from "./chunk-WJO6NVE2.js";
11
+ } from "./chunk-5LFGEMIW.js";
12
12
  import {
13
13
  compact
14
14
  } from "./chunk-MMHG7WAM.js";
@@ -225,4 +225,4 @@ export {
225
225
  createToolMiddleware,
226
226
  createThinkTool
227
227
  };
228
- //# sourceMappingURL=chunk-X3SWV6W6.js.map
228
+ //# sourceMappingURL=chunk-FV5B4SGK.js.map
@@ -5,7 +5,7 @@ import {
5
5
  UserContent,
6
6
  reasoningDisplayText,
7
7
  serializeToolResultOutput
8
- } from "./chunk-WJO6NVE2.js";
8
+ } from "./chunk-5LFGEMIW.js";
9
9
 
10
10
  // src/ui/messages.ts
11
11
  function uiMessagesToCoreMessages(messages) {
@@ -262,4 +262,4 @@ export {
262
262
  uiMessagesToCoreMessages,
263
263
  coreMessagesToUIMessages
264
264
  };
265
- //# sourceMappingURL=chunk-DOS77JZC.js.map
265
+ //# sourceMappingURL=chunk-JNO4AR7Q.js.map
@@ -1,18 +1,18 @@
1
1
  import {
2
2
  PromptRequest
3
- } from "./chunk-SISUMRUX.js";
3
+ } from "./chunk-7CQAERL3.js";
4
4
  import {
5
5
  isSkillTool
6
6
  } from "./chunk-YK4WAAS4.js";
7
7
  import {
8
8
  ToolSet
9
- } from "./chunk-X3SWV6W6.js";
9
+ } from "./chunk-FV5B4SGK.js";
10
10
  import {
11
11
  createTool
12
12
  } from "./chunk-5EDHXYH5.js";
13
13
  import {
14
14
  isStreamingCompletionModel
15
- } from "./chunk-5G3VME2D.js";
15
+ } from "./chunk-SRBW3LD7.js";
16
16
  import {
17
17
  compact
18
18
  } from "./chunk-MMHG7WAM.js";
@@ -202,4 +202,4 @@ export {
202
202
  Agent,
203
203
  AgentSession
204
204
  };
205
- //# sourceMappingURL=chunk-N6REB3DH.js.map
205
+ //# sourceMappingURL=chunk-MLMXQ2OV.js.map