@anvia/core 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +7 -8
  2. package/dist/agent/index.d.ts +10 -10
  3. package/dist/agent/index.js +10 -18
  4. package/dist/{agent-D_jXqPAZ.d.ts → agent-B-ls5y_g.d.ts} +6 -19
  5. package/dist/audio-generation/index.d.ts +1 -1
  6. package/dist/audio-generation/index.js +37 -4
  7. package/dist/audio-generation/index.js.map +1 -1
  8. package/dist/{chunk-QRZ2HPUX.js → chunk-4PHDOEKY.js} +3 -3
  9. package/dist/chunk-4PHDOEKY.js.map +1 -0
  10. package/dist/chunk-BD66WU2B.js +188 -0
  11. package/dist/chunk-BD66WU2B.js.map +1 -0
  12. package/dist/{chunk-I2HOMD3R.js → chunk-CY7SB5FG.js} +3 -3
  13. package/dist/{chunk-A7VDIZQN.js → chunk-EFGX3EX5.js} +5 -14
  14. package/dist/chunk-EFGX3EX5.js.map +1 -0
  15. package/dist/{chunk-TILE6Z2N.js → chunk-L6JCKFAX.js} +2 -2
  16. package/dist/{chunk-65QV627O.js → chunk-OIA4CN5V.js} +2 -2
  17. package/dist/chunk-OIMLU4SF.js +20 -0
  18. package/dist/chunk-OIMLU4SF.js.map +1 -0
  19. package/dist/{chunk-GSFQZYS7.js → chunk-TVIADATY.js} +579 -723
  20. package/dist/chunk-TVIADATY.js.map +1 -0
  21. package/dist/completion/index.d.ts +2 -2
  22. package/dist/embeddings/index.d.ts +4 -24
  23. package/dist/embeddings/index.js +2 -1
  24. package/dist/evals/index.d.ts +26 -21
  25. package/dist/evals/index.js +298 -15
  26. package/dist/evals/index.js.map +1 -1
  27. package/dist/extractor/index.d.ts +6 -5
  28. package/dist/extractor/index.js +8 -6
  29. package/dist/image-generation/index.d.ts +1 -1
  30. package/dist/image-generation/index.js +37 -4
  31. package/dist/image-generation/index.js.map +1 -1
  32. package/dist/index.d.ts +12 -21
  33. package/dist/index.js +14 -160
  34. package/dist/internal/agent.d.ts +8 -0
  35. package/dist/internal/agent.js +18 -0
  36. package/dist/internal/agent.js.map +1 -0
  37. package/dist/loaders/index.d.ts +1 -1
  38. package/dist/mcp/index.d.ts +4 -4
  39. package/dist/mcp/index.js +140 -4
  40. package/dist/mcp/index.js.map +1 -1
  41. package/dist/memory/index.d.ts +1 -1
  42. package/dist/{middleware-2FR89muX.d.ts → middleware-CGiEIaBx.d.ts} +4 -7
  43. package/dist/model-listing/index.js +13 -3
  44. package/dist/model-listing/index.js.map +1 -1
  45. package/dist/observability/index.d.ts +2 -2
  46. package/dist/observability/index.js +4 -3
  47. package/dist/observability/index.js.map +1 -1
  48. package/dist/pipeline/index.d.ts +9 -6
  49. package/dist/pipeline/index.js +334 -3
  50. package/dist/pipeline/index.js.map +1 -1
  51. package/dist/skills/index.d.ts +4 -4
  52. package/dist/skills/index.js +5 -4
  53. package/dist/think-tool-ByArsrxe.d.ts +26 -0
  54. package/dist/tool/index.d.ts +8 -29
  55. package/dist/tool/index.js +4 -3
  56. package/dist/{tool-ClZYES-Z.d.ts → tool-C3ciF-VG.d.ts} +2 -2
  57. package/dist/transcription/index.d.ts +1 -1
  58. package/dist/transcription/index.js +55 -4
  59. package/dist/transcription/index.js.map +1 -1
  60. package/dist/{types-BM8-Y8Hy.d.ts → types-C54aNoCd.d.ts} +1 -1
  61. package/dist/types-IB2e9u5M.d.ts +25 -0
  62. package/dist/{types-B0iXLkqi.d.ts → types-T9rlOIUc.d.ts} +2 -2
  63. package/dist/{types-fLi8uM5R.d.ts → types-UhcgW8Fo.d.ts} +3 -3
  64. package/dist/vector-store/index.d.ts +3 -3
  65. package/dist/vector-store/index.js +3 -2
  66. package/dist/zod-schema-C7F4clpm.d.ts +5 -0
  67. package/package.json +6 -2
  68. package/dist/chunk-6JCCM2K4.js +0 -304
  69. package/dist/chunk-6JCCM2K4.js.map +0 -1
  70. package/dist/chunk-7QI6ZAFI.js +0 -61
  71. package/dist/chunk-7QI6ZAFI.js.map +0 -1
  72. package/dist/chunk-A7VDIZQN.js.map +0 -1
  73. package/dist/chunk-B24Q2ZYM.js +0 -43
  74. package/dist/chunk-B24Q2ZYM.js.map +0 -1
  75. package/dist/chunk-GSFQZYS7.js.map +0 -1
  76. package/dist/chunk-I77SDTFE.js +0 -43
  77. package/dist/chunk-I77SDTFE.js.map +0 -1
  78. package/dist/chunk-NYUOBGVI.js +0 -146
  79. package/dist/chunk-NYUOBGVI.js.map +0 -1
  80. package/dist/chunk-QRZ2HPUX.js.map +0 -1
  81. package/dist/chunk-RTOGIJH2.js +0 -345
  82. package/dist/chunk-RTOGIJH2.js.map +0 -1
  83. package/dist/chunk-WJT22R3T.js +0 -18
  84. package/dist/chunk-WJT22R3T.js.map +0 -1
  85. package/dist/chunk-ZSYIQYTV.js +0 -9
  86. package/dist/chunk-ZSYIQYTV.js.map +0 -1
  87. /package/dist/{chunk-I2HOMD3R.js.map → chunk-CY7SB5FG.js.map} +0 -0
  88. /package/dist/{chunk-TILE6Z2N.js.map → chunk-L6JCKFAX.js.map} +0 -0
  89. /package/dist/{chunk-65QV627O.js.map → chunk-OIA4CN5V.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/agent/agent.ts","../src/observability/group.ts","../src/agent/errors.ts","../src/agent/hooks.ts","../src/agent/utils.ts","../src/agent/stream-accumulator.ts","../src/agent/request.ts","../src/agent/builder.ts"],"sourcesContent":["import { z } from \"zod\";\nimport type {\n CompletionModel,\n Document,\n JsonObject,\n JsonValue,\n Message as MessageType,\n ToolChoice,\n} from \"../completion/index\";\nimport type { MemoryRegistration, SessionOptions } from \"../memory\";\nimport type { AgentObserverRegistration } from \"../observability\";\nimport { createTool } from \"../tool/create-tool\";\nimport type { ToolSearchDocument } from \"../tool/dynamic-tools\";\nimport type { ToolMiddleware } from \"../tool/middleware\";\nimport { isSkillTool } from \"../tool/skill-tool-marker\";\nimport type { AnyTool, NormalizedToolOutput, Tool, ToolCallContext } from \"../tool/tool\";\nimport { ToolSet } from \"../tool/tool-set\";\nimport type { VectorFilter, VectorSearchIndex, VectorSearchResult } from \"../vector-store\";\nimport type { PromptHook } from \"./hooks\";\nimport { PromptRequest } from \"./request\";\nimport { isStreamingCompletionModel } from \"./utils\";\n\nexport type AgentOptions<M extends CompletionModel = CompletionModel> = {\n id: string;\n name?: string | undefined;\n description?: string | undefined;\n model: M;\n instructions?: string | undefined;\n staticContext?: Document[];\n temperature?: number | undefined;\n maxTokens?: number | undefined;\n additionalParams?: JsonValue | undefined;\n toolSet?: ToolSet | undefined;\n toolChoice?: ToolChoice | undefined;\n defaultMaxTurns?: number | undefined;\n hook?: PromptHook | undefined;\n outputSchema?: JsonObject | undefined;\n observers?: AgentObserverRegistration[] | undefined;\n dynamicContexts?: DynamicContextRegistration[] | undefined;\n dynamicTools?: DynamicToolRegistration[] | undefined;\n toolMiddlewares?: ToolMiddleware[] | undefined;\n memory?: MemoryRegistration | undefined;\n eventStore?: AgentEventStoreRegistration | undefined;\n};\n\nexport const DEFAULT_MAX_TURNS = 20;\n\nexport type AgentToolOptions = {\n name: string;\n description?: string | undefined;\n maxTurns?: number | undefined;\n stream?: boolean | undefined;\n};\n\nexport type AgentEventStoreInclude = \"all\" | \"agent_tool_events\";\n\nexport type AgentEventStoreOptions = {\n include?: AgentEventStoreInclude | undefined;\n};\n\nexport type AgentEventAppendInput = {\n runId: string;\n agentId: string;\n agentName?: string | undefined;\n turn?: number | undefined;\n toolName?: string | undefined;\n toolCallId?: string | undefined;\n internalCallId?: string | undefined;\n event: unknown;\n};\n\nexport type AgentEventRecord = AgentEventAppendInput & {\n createdAt?: Date | undefined;\n};\n\nexport interface AgentEventStore {\n append(input: AgentEventAppendInput): Promise<void>;\n load(runId: string): Promise<AgentEventRecord[]>;\n clear?(runId: string): Promise<void>;\n}\n\nexport type AgentEventStoreRegistration = {\n store: AgentEventStore;\n options: Required<AgentEventStoreOptions>;\n};\n\nexport type DynamicContextOptions<T = unknown> = {\n topK: number;\n threshold?: number | undefined;\n filter?: VectorFilter | undefined;\n format?: ((result: VectorSearchResult<T>) => Document) | undefined;\n};\n\nexport type DynamicContextRegistration<T = unknown> = {\n index: VectorSearchIndex<T>;\n options: DynamicContextOptions<T>;\n};\n\nexport type DynamicToolOptions = {\n topK: number;\n threshold?: number | undefined;\n filter?: VectorFilter | undefined;\n};\n\nexport type DynamicToolRegistration = {\n index: VectorSearchIndex<ToolSearchDocument>;\n options: DynamicToolOptions;\n};\n\nexport class Agent<M extends CompletionModel = CompletionModel> {\n readonly id: string;\n readonly name: string | undefined;\n readonly description: string | undefined;\n readonly model: M;\n readonly instructions: string | undefined;\n readonly staticContext: Document[];\n readonly temperature: number | undefined;\n readonly maxTokens: number | undefined;\n readonly additionalParams: JsonValue | undefined;\n readonly toolSet: ToolSet;\n readonly toolChoice: ToolChoice | undefined;\n readonly defaultMaxTurns: number | undefined;\n readonly hook: PromptHook | undefined;\n readonly outputSchema: JsonObject | undefined;\n readonly observers: AgentObserverRegistration[];\n readonly dynamicContexts: DynamicContextRegistration[];\n readonly dynamicTools: DynamicToolRegistration[];\n readonly toolMiddlewares: ToolMiddleware[];\n readonly memory: MemoryRegistration | undefined;\n readonly eventStore: AgentEventStoreRegistration | undefined;\n\n constructor(options: AgentOptions<M>) {\n this.id = normalizeAgentId(options.id);\n this.name = options.name;\n this.description = options.description;\n this.model = options.model;\n this.instructions = options.instructions;\n this.staticContext = options.staticContext ?? [];\n this.temperature = options.temperature;\n this.maxTokens = options.maxTokens;\n this.additionalParams = options.additionalParams;\n this.toolSet = options.toolSet ?? new ToolSet();\n this.toolChoice = options.toolChoice;\n this.defaultMaxTurns = options.defaultMaxTurns ?? DEFAULT_MAX_TURNS;\n this.hook = options.hook;\n this.outputSchema = options.outputSchema;\n this.observers = options.observers ?? [];\n this.dynamicContexts = options.dynamicContexts ?? [];\n this.dynamicTools = options.dynamicTools ?? [];\n this.toolMiddlewares = options.toolMiddlewares ?? [];\n this.memory = options.memory;\n this.eventStore = options.eventStore;\n }\n\n prompt(prompt: string | MessageType | MessageType[]): PromptRequest<M> {\n return PromptRequest.fromAgent(this, prompt);\n }\n\n session(sessionId: string, options: SessionOptions = {}): AgentSession<M> {\n if (this.memory === undefined) {\n throw new Error(`Agent \"${this.id}\" has no memory store configured.`);\n }\n const normalized = sessionId.trim();\n if (normalized.length === 0) {\n throw new TypeError(\"Session id must be a non-empty string.\");\n }\n return new AgentSession(this, {\n sessionId: normalized,\n ...(options.userId === undefined ? {} : { userId: options.userId }),\n ...(options.metadata === undefined ? {} : { metadata: options.metadata }),\n });\n }\n\n asTool(options: AgentToolOptions): Tool<{ prompt: string }, string> {\n const description =\n options.description ?? this.description ?? `Prompt the ${options.name} agent.`;\n\n return createTool({\n name: options.name,\n description,\n input: z.object({\n prompt: z.string().describe(\"The prompt to send to the agent.\"),\n }),\n output: z.string(),\n execute: async ({ prompt }, context: ToolCallContext) => {\n const request = this.prompt(prompt);\n const childRequest =\n options.maxTurns === undefined ? request : request.maxTurns(options.maxTurns);\n if (\n options.stream === true &&\n context.emitStreamEvent !== undefined &&\n this.model.capabilities.streaming &&\n isStreamingCompletionModel(this.model)\n ) {\n let output = \"\";\n for await (const event of childRequest.stream()) {\n await context.emitStreamEvent({\n agentId: this.id,\n ...(this.name === undefined ? {} : { agentName: this.name }),\n event,\n });\n if (event.type === \"final\") {\n output = event.output;\n }\n }\n return output;\n }\n const response = await childRequest.send();\n return response.output;\n },\n });\n }\n\n getTool(toolName: string): AnyTool | undefined {\n const staticTool = this.toolSet.get(toolName);\n if (staticTool !== undefined) {\n return staticTool;\n }\n\n for (const registration of this.dynamicTools) {\n const dynamicTool = dynamicToolSetFromIndex(registration.index)?.get(toolName);\n if (dynamicTool !== undefined) {\n return dynamicTool;\n }\n }\n\n return undefined;\n }\n\n async callTool(\n toolName: string,\n args: string,\n context?: ToolCallContext,\n ): Promise<NormalizedToolOutput> {\n if (this.toolSet.contains(toolName)) {\n return this.toolSet.call(toolName, args, context);\n }\n\n for (const registration of this.dynamicTools) {\n const toolSet = dynamicToolSetFromIndex(registration.index);\n if (toolSet?.contains(toolName)) {\n return toolSet.call(toolName, args, context);\n }\n }\n\n return this.toolSet.call(toolName, args, context);\n }\n\n shouldApplyToolMiddleware(toolName: string): boolean {\n return !isSkillTool(this.getTool(toolName));\n }\n}\n\nexport class AgentSession<M extends CompletionModel = CompletionModel> {\n constructor(\n private readonly agent: Agent<M>,\n private readonly context: {\n sessionId: string;\n userId?: string | undefined;\n metadata?: JsonObject | undefined;\n },\n ) {}\n\n prompt(prompt: string | MessageType): PromptRequest<M> {\n if (Array.isArray(prompt)) {\n throw new TypeError(\"AgentSession.prompt does not accept Message[] transcripts.\");\n }\n return PromptRequest.fromAgent(this.agent, prompt, { memoryContext: this.context });\n }\n\n async messages(): Promise<MessageType[]> {\n const memory = this.agent.memory;\n if (memory === undefined) {\n throw new Error(`Agent \"${this.agent.id}\" has no memory store configured.`);\n }\n return memory.store.load(this.context);\n }\n\n async clear(): Promise<void> {\n const memory = this.agent.memory;\n if (memory === undefined) {\n throw new Error(`Agent \"${this.agent.id}\" has no memory store configured.`);\n }\n await memory.store.clear(this.context);\n }\n}\n\nfunction dynamicToolSetFromIndex(\n index: VectorSearchIndex<ToolSearchDocument>,\n): ToolSet | undefined {\n const maybeIndex = index as { toolSet?: unknown };\n return maybeIndex.toolSet instanceof ToolSet ? maybeIndex.toolSet : undefined;\n}\n\nfunction normalizeAgentId(id: string): string {\n if (typeof id !== \"string\") {\n throw new TypeError(\"Agent id must be a string.\");\n }\n\n const normalized = id.trim();\n if (normalized.length === 0) {\n throw new TypeError(\"Agent id must be a non-empty string.\");\n }\n\n return normalized;\n}\n","import type {\n AgentGenerationEndArgs,\n AgentGenerationErrorArgs,\n AgentGenerationObserver,\n AgentGenerationStartArgs,\n AgentObserverRegistration,\n AgentRunEndArgs,\n AgentRunErrorArgs,\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 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 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 { Message } from \"../completion/index\";\n\nexport class MaxTurnsError extends Error {\n constructor(\n readonly maxTurns: number,\n readonly chatHistory: Message[],\n readonly prompt: Message,\n ) {\n super(`Reached max turn limit: ${maxTurns}`);\n this.name = \"MaxTurnsError\";\n }\n}\n\nexport class 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","import type { CompletionResponse, Message, ToolResultContent } from \"../completion/index\";\n\nexport type HookAction = { type: \"continue\" } | { type: \"terminate\"; reason: string };\nexport type ToolApprovalRequestOptions = {\n reason?: string;\n rejectMessage?: string;\n};\n\nexport type ToolCallHookAction =\n | { type: \"continue\" }\n | { type: \"skip\"; reason: string }\n | { type: \"terminate\"; reason: string }\n | ({ type: \"approval_request\" } & ToolApprovalRequestOptions);\n\nexport type RunControl = {\n continue(): HookAction;\n cancel(reason: string): HookAction;\n};\n\nexport type ToolCallControl = {\n run(): ToolCallHookAction;\n skip(reason: string): ToolCallHookAction;\n cancel(reason: string): ToolCallHookAction;\n requestApproval(options?: ToolApprovalRequestOptions): ToolCallHookAction;\n};\n\nexport type HookResult = HookAction | undefined;\nexport type ToolCallHookResult = ToolCallHookAction | undefined;\n\ntype HookCallback<Args> = (\n args: Args,\n) => HookAction | Promise<HookAction | undefined> | Promise<void> | void;\ntype ToolCallHookCallback<Args> = (\n args: Args,\n) => ToolCallHookAction | Promise<ToolCallHookAction | undefined> | Promise<void> | void;\n\nexport type CompletionCallHookArgs = {\n prompt: Message;\n history: Message[];\n run: RunControl;\n};\n\nexport type CompletionResponseHookArgs<RawResponse = unknown> = {\n prompt: Message;\n response: CompletionResponse<RawResponse>;\n run: RunControl;\n};\n\nexport type ToolHookArgs = {\n toolName: string;\n toolCallId?: string;\n internalCallId: string;\n args: string;\n};\n\nexport type ToolCallHookArgs = ToolHookArgs & {\n tool: ToolCallControl;\n};\n\nexport type ToolResultHookArgs = ToolHookArgs & {\n result: string;\n structuredResult?: ToolResultContent[] | undefined;\n run: RunControl;\n};\n\nexport function createHook<RawResponse = unknown>(\n hook: PromptHook<RawResponse>,\n): PromptHook<RawResponse> {\n return hook;\n}\n\nexport function cancelPrompt(reason: string): HookAction {\n return { type: \"terminate\", reason };\n}\n\nexport function skipTool(reason: string): ToolCallHookAction {\n return { type: \"skip\", reason };\n}\n\nexport function requestToolApproval(options: ToolApprovalRequestOptions = {}): ToolCallHookAction {\n return {\n type: \"approval_request\",\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n ...(options.rejectMessage === undefined ? {} : { rejectMessage: options.rejectMessage }),\n };\n}\n\nexport const runControl: RunControl = {\n continue() {\n return { type: \"continue\" };\n },\n cancel(reason: string) {\n return cancelPrompt(reason);\n },\n};\n\nexport const toolCallControl: ToolCallControl = {\n run() {\n return { type: \"continue\" };\n },\n skip(reason: string) {\n return skipTool(reason);\n },\n cancel(reason: string) {\n return { type: \"terminate\", reason };\n },\n requestApproval(options) {\n return requestToolApproval(options);\n },\n};\n\nexport interface PromptHook<RawResponse = unknown> {\n onCompletionCall?: HookCallback<CompletionCallHookArgs>;\n onCompletionResponse?: HookCallback<CompletionResponseHookArgs<RawResponse>>;\n onToolCall?: ToolCallHookCallback<ToolCallHookArgs>;\n onToolResult?: HookCallback<ToolResultHookArgs>;\n}\n","import type {\n CompletionModel,\n JsonValue,\n Message as MessageType,\n StreamingCompletionModel,\n} from \"../completion/index\";\n\nexport function isStreamingCompletionModel(\n model: CompletionModel,\n): model is StreamingCompletionModel {\n return \"streamCompletion\" in model && typeof model.streamCompletion === \"function\";\n}\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\nexport function 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\nexport async function mapWithConcurrency<T, R>(\n items: T[],\n concurrency: number,\n mapper: (item: T) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = [];\n let next = 0;\n\n async function worker(): Promise<void> {\n while (next < items.length) {\n const index = next;\n next += 1;\n const item = items[index];\n if (item !== undefined) {\n results[index] = await mapper(item);\n }\n }\n }\n\n const workerCount = Math.min(concurrency, items.length);\n await Promise.all(Array.from({ length: workerCount }, () => worker()));\n return results;\n}\n","import type {\n AssistantContent as AssistantContentType,\n CompletionResponse,\n CompletionStreamEvent,\n ReasoningContent,\n ReasoningContentType,\n ToolCall,\n} from \"../completion/index\";\nimport { Usage } from \"../completion/index\";\nimport { parseJsonValue } from \"./utils\";\n\nexport type AgentDeltaEvent =\n | { type: \"text_delta\"; delta: string }\n | {\n type: \"reasoning_delta\";\n delta: string;\n id?: string;\n contentType?: ReasoningContentType;\n signature?: string;\n }\n | { type: \"tool_call\"; toolCall: ToolCall };\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 undefined;\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","import {\n assertCompletionRequestSupported,\n type CompletionModel,\n CompletionRequestBuilder,\n type CompletionResponse,\n type Document,\n type JsonObject,\n Message,\n type Message as MessageType,\n type ReasoningContentType,\n type ToolCall,\n ToolContent,\n type ToolDefinition,\n type ToolResult,\n type ToolResultContent,\n textFromAssistantContent,\n Usage,\n} from \"../completion/index\";\nimport type { MemoryContext, MemoryRegistration, MemorySavePolicy } from \"../memory\";\nimport {\n type ActiveAgentRunObservers,\n type ActiveToolObservers,\n startAgentRunObservers,\n} from \"../observability/group\";\nimport type { AgentTraceInfo, AgentTraceOptions } from \"../observability/types\";\nimport { toReadableStream } from \"../streaming\";\nimport {\n type AnyTool,\n type NormalizedToolOutput,\n type ToolCallStreamEvent,\n toolResultContentToText,\n} from \"../tool\";\nimport type { ToolMiddleware, ToolResultMiddlewareArgs } from \"../tool/middleware\";\nimport type { Agent } from \"./agent\";\nimport { MaxTurnsError, PromptCancelledError } from \"./errors\";\nimport type { PromptHook, ToolHookArgs } from \"./hooks\";\nimport { runControl, toolCallControl } from \"./hooks\";\nimport { type AgentDeltaEvent, CompletionStreamAccumulator } from \"./stream-accumulator\";\nimport { extractRagText, isStreamingCompletionModel, mapWithConcurrency } from \"./utils\";\n\nconst MCP_TOOL_METADATA_KEY = Symbol.for(\"anvia.mcp.tool.metadata\");\n\nexport type PromptResponse = {\n output: string;\n usage: Usage;\n messages: MessageType[];\n trace?: AgentTraceInfo | undefined;\n};\n\nexport type AgentChildStreamEvent<RawResponse = unknown> =\n | {\n type: \"turn_start\";\n turn: number;\n prompt: MessageType;\n history: MessageType[];\n }\n | {\n type: \"text_delta\";\n turn: number;\n delta: string;\n }\n | {\n type: \"reasoning_delta\";\n turn: number;\n delta: string;\n id?: string;\n contentType?: ReasoningContentType;\n signature?: string;\n }\n | {\n type: \"tool_call\";\n turn: number;\n toolCall: ToolCall;\n }\n | {\n type: \"tool_result\";\n turn: number;\n toolName: string;\n toolCallId?: string;\n internalCallId: string;\n args: string;\n result: string;\n structuredResult?: ToolResultContent[] | undefined;\n }\n | {\n type: \"turn_end\";\n turn: number;\n response: CompletionResponse<RawResponse>;\n }\n | {\n type: \"final\";\n runId: string;\n output: string;\n usage: Usage;\n messages: MessageType[];\n trace?: AgentTraceInfo | undefined;\n }\n | {\n type: \"error\";\n error: unknown;\n };\n\nexport type AgentStreamEvent<RawResponse = unknown> =\n | AgentChildStreamEvent<RawResponse>\n | {\n type: \"agent_tool_event\";\n turn: number;\n toolName: string;\n toolCallId?: string;\n internalCallId: string;\n agentId: string;\n agentName?: string;\n event: AgentChildStreamEvent<RawResponse>;\n };\n\nexport class PromptRequest<M extends CompletionModel = CompletionModel> {\n private chatHistory: MessageType[];\n private maxTurnCount: number;\n private activeHook: PromptHook | undefined;\n private concurrency = 1;\n private traceOptions: AgentTraceOptions | undefined;\n private requestToolMiddlewares: ToolMiddleware[] = [];\n\n private constructor(\n private readonly agent: Agent<M>,\n private readonly promptMessage: MessageType,\n private readonly 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 }\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 requestHook(hook: PromptHook): this {\n this.activeHook = hook;\n return this;\n }\n\n withToolConcurrency(concurrency: number): this {\n this.concurrency = Math.max(1, concurrency);\n return this;\n }\n\n withToolMiddleware(middleware: ToolMiddleware): this {\n this.requestToolMiddlewares.push(middleware);\n return this;\n }\n\n withToolMiddlewares(middlewares: ToolMiddleware[]): this {\n this.requestToolMiddlewares.push(...middlewares);\n return this;\n }\n\n withTrace(trace: AgentTraceOptions): this {\n this.traceOptions = trace;\n return this;\n }\n\n async send(): Promise<PromptResponse> {\n const runId = globalThis.crypto.randomUUID();\n const newMessages: MessageType[] = [this.promptMessage];\n await this.prepareMemoryRun(runId, newMessages);\n const pendingTurnMessages = this.memoryPolicy() === \"turn\" ? [...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 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.runCompletionCallHook(prompt, historyForRequest, newMessages);\n\n const ragText = extractRagText(prompt);\n const dynamicContext = await this.fetchDynamicContext(ragText);\n const toolDefs = await this.fetchToolDefinitions(ragText);\n const 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\n const response = await this.runCompletion(request, currentTurns, runObservers);\n usage = Usage.add(usage, response.usage);\n await this.runCompletionResponseHook(prompt, response, newMessages);\n\n const assistantMessage = Message.assistant(response.choice, response.messageId);\n newMessages.push(assistantMessage);\n await this.commitMemoryMessages(\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 await this.commitCompletedMemoryRun(\n runId,\n currentTurns,\n newMessages,\n pendingTurnMessages,\n );\n const result: PromptResponse = {\n output: textFromAssistantContent(response.choice),\n usage,\n messages: [...newMessages],\n trace: runObservers.trace,\n };\n await runObservers.end(result);\n return result;\n }\n\n const toolResults = await this.executeToolCalls(\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.commitMemoryMessages(runId, currentTurns, [toolMessage], pendingTurnMessages);\n await this.commitCompletedMemoryTurn(runId, currentTurns, pendingTurnMessages);\n }\n\n throw new MaxTurnsError(this.maxTurnCount, [...this.chatHistory, ...newMessages], lastPrompt);\n } catch (error) {\n await runObservers.error({ error, usage, messages: [...newMessages] });\n await this.recordMemoryError(runId, error, newMessages);\n throw error;\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 const runId = globalThis.crypto.randomUUID();\n const newMessages: MessageType[] = [this.promptMessage];\n await this.prepareMemoryRun(runId, newMessages);\n const pendingTurnMessages = this.memoryPolicy() === \"turn\" ? [...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 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.runCompletionCallHook(prompt, historyForRequest, newMessages);\n\n const ragText = extractRagText(prompt);\n const dynamicContext = await this.fetchDynamicContext(ragText);\n const toolDefs = await this.fetchToolDefinitions(ragText);\n const 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\n assertCompletionRequestSupported(this.agent.model, request, { streaming: true });\n const providerRequest = this.providerTraceRequest(request, { stream: true });\n const generationObservers = await runObservers.startGeneration({\n turn: currentTurns,\n request,\n ...(providerRequest === undefined ? {} : { providerRequest }),\n modelInfo: {\n provider: this.agent.model.provider,\n defaultModel: this.agent.model.defaultModel,\n capabilities: this.agent.model.capabilities,\n },\n });\n const accumulator = new CompletionStreamAccumulator();\n const generationStartedAt = Date.now();\n let firstDeltaMs: number | undefined;\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 yield await emit(addTurn(currentTurns, mapped));\n }\n }\n } catch (error) {\n await generationObservers.error({ turn: currentTurns, error });\n throw error;\n }\n\n const response = accumulator.response();\n await generationObservers.end({\n turn: currentTurns,\n response,\n ...(firstDeltaMs === undefined ? {} : { firstDeltaMs }),\n });\n usage = Usage.add(usage, response.usage);\n await this.runCompletionResponseHook(prompt, response, newMessages);\n\n const assistantMessage = Message.assistant(response.choice, response.messageId);\n newMessages.push(assistantMessage);\n await this.commitMemoryMessages(\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 for (const toolCall of toolCalls) {\n yield await emit({ type: \"tool_call\", turn: currentTurns, toolCall });\n }\n yield await emit({ type: \"turn_end\", turn: currentTurns, response });\n\n if (toolCalls.length === 0) {\n const output = textFromAssistantContent(response.choice);\n await this.commitCompletedMemoryRun(\n runId,\n currentTurns,\n newMessages,\n pendingTurnMessages,\n );\n yield await emit({\n type: \"final\",\n runId,\n output,\n usage,\n messages: [...newMessages],\n trace: runObservers.trace,\n });\n await runObservers.end({ output, usage, messages: [...newMessages] });\n return;\n }\n\n const toolResultEvents = createAsyncQueue<ToolExecutionEventPayload>();\n const toolResultsPromise = this.executeToolCalls(\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.commitMemoryMessages(runId, currentTurns, [toolMessage], pendingTurnMessages);\n await this.commitCompletedMemoryTurn(runId, currentTurns, pendingTurnMessages);\n }\n\n throw new MaxTurnsError(this.maxTurnCount, [...this.chatHistory, ...newMessages], lastPrompt);\n } catch (error) {\n await runObservers.error({ error, usage, messages: [...newMessages] });\n await this.recordMemoryError(runId, error, newMessages);\n yield await emit({ type: \"error\", error });\n throw error;\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 turn,\n request,\n ...(providerRequest === undefined ? {} : { providerRequest }),\n modelInfo: {\n provider: this.agent.model.provider,\n defaultModel: this.agent.model.defaultModel,\n capabilities: this.agent.model.capabilities,\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 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\n private async executeToolCalls(\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 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 = this.toolTraceMetadata(tool);\n\n const toolObservers = await observation?.runObservers.startTool({\n turn: observation.turn,\n toolCall,\n toolName: toolCall.function.name,\n internalCallId,\n args,\n toolCallId: toolCall.callId,\n ...(toolDefinition === undefined ? {} : { toolDefinition }),\n ...(toolMetadata === undefined ? {} : { toolMetadata }),\n });\n\n const callAction = await this.activeHook?.onToolCall?.({\n ...hookArgs,\n tool: toolCallControl,\n });\n if (callAction?.type === \"terminate\") {\n await this.recordToolError(\n toolObservers,\n observation?.turn,\n toolCall,\n internalCallId,\n args,\n callAction.reason,\n );\n throw this.cancelled(newMessages, callAction.reason);\n }\n if (callAction?.type === \"approval_request\") {\n const reason = `Tool approval was requested for ${toolCall.function.name}, but no approval handler is installed.`;\n await this.recordToolError(\n toolObservers,\n observation?.turn,\n toolCall,\n internalCallId,\n args,\n reason,\n );\n throw this.cancelled(newMessages, reason);\n }\n\n let output: NormalizedToolOutput;\n let skipped = false;\n if (callAction?.type === \"skip\") {\n output = callAction.reason;\n skipped = true;\n } else {\n try {\n output = await this.agent.callTool(toolCall.function.name, args, {\n emitStreamEvent: async (event) => {\n await toolObservers?.streamEvent({\n turn: observation?.turn ?? 0,\n toolCall,\n toolName: toolCall.function.name,\n internalCallId,\n args,\n ...(toolCall.callId === undefined ? {} : { toolCallId: toolCall.callId }),\n event,\n });\n const payload = agentToolEventPayload(toolCall, internalCallId, event);\n if (payload !== undefined) {\n onStreamEvent?.(payload);\n }\n },\n });\n } catch (error) {\n output = error instanceof Error ? error.toString() : String(error);\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 result,\n originalResult: result,\n structuredResult,\n originalStructuredResult: structuredResult,\n turn: observation?.turn ?? 0,\n });\n if (middlewareReplacement !== undefined) {\n output = middlewareReplacement;\n result = middlewareReplacement;\n structuredResult = undefined;\n }\n }\n\n const resultAction = await this.activeHook?.onToolResult?.({\n ...hookArgs,\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,\n result,\n structuredResult,\n skipped,\n toolCallId: toolCall.callId,\n });\n if (resultAction?.type === \"terminate\") {\n throw this.cancelled(newMessages, resultAction.reason);\n }\n\n const resultPayload: ToolResultEventPayload = {\n type: \"tool_result\",\n toolName: toolCall.function.name,\n internalCallId,\n args,\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: ToolResultMiddlewareArgs,\n ): Promise<string | undefined> {\n let result = args.result;\n let replaced = false;\n for (const middleware of [...this.agent.toolMiddlewares, ...this.requestToolMiddlewares]) {\n const replacement = await middleware.onResult?.({\n ...args,\n result,\n });\n if (replacement !== undefined) {\n result = replacement;\n replaced = true;\n }\n }\n return replaced ? result : undefined;\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 ...(agentName === undefined ? {} : { agentName }),\n ...(turn === undefined ? {} : { turn }),\n ...(event.type === \"agent_tool_event\"\n ? {\n toolName: event.toolName,\n ...(event.toolCallId === undefined ? {} : { toolCallId: event.toolCallId }),\n internalCallId: event.internalCallId,\n }\n : {}),\n event,\n });\n }\n\n private async fetchDynamicContext(ragText: string | undefined): Promise<Document[]> {\n if (ragText === undefined || ragText.length === 0 || this.agent.dynamicContexts.length === 0) {\n return [];\n }\n\n const documents: Document[] = [];\n for (const registration of this.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 id: result.id,\n text:\n typeof result.document === \"string\"\n ? result.document\n : JSON.stringify(result.document, null, 2),\n ...(metadata === undefined ? {} : { additionalProps: metadata }),\n });\n }\n }\n }\n return documents;\n }\n\n private async fetchToolDefinitions(ragText: string | undefined): Promise<ToolDefinition[]> {\n const staticDefinitions = await this.agent.toolSet.getToolDefinitions(ragText);\n if (ragText === undefined || ragText.length === 0 || this.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 this.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\n private async 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\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 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 cancelled(newMessages: MessageType[], reason: string): PromptCancelledError {\n return new PromptCancelledError([...this.chatHistory, ...newMessages], reason);\n }\n\n private memory(): MemoryRegistration | undefined {\n return this.memoryContext === undefined ? undefined : this.agent.memory;\n }\n\n private memoryPolicy(): MemorySavePolicy | undefined {\n return this.memory()?.options.savePolicy;\n }\n\n private async prepareMemoryRun(runId: string, newMessages: MessageType[]): Promise<void> {\n const memory = this.memory();\n if (memory === undefined || this.memoryContext === undefined) {\n this.chatHistory = this.initialHistory;\n return;\n }\n\n const memoryHistory = await memory.store.load(this.memoryContext);\n this.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 }\n\n private async commitMemoryMessages(\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 private async commitCompletedMemoryTurn(\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 private async commitCompletedMemoryRun(\n runId: string,\n turn: number,\n newMessages: MessageType[],\n pendingTurnMessages: MessageType[],\n ): Promise<void> {\n await this.commitCompletedMemoryTurn(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 private async recordMemoryError(\n runId: string,\n error: unknown,\n newMessages: MessageType[],\n ): 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\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\ntype 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\ntype 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\ntype ToolExecutionEventPayload = ToolResultEventPayload | AgentToolEventPayload;\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 {\n type: \"agent_tool_event\",\n toolName: toolCall.function.name,\n ...(toolCall.callId === undefined ? {} : { toolCallId: toolCall.callId }),\n internalCallId,\n agentId: event.agentId,\n ...(event.agentName === undefined ? {} : { agentName: event.agentName }),\n event: event.event as AgentChildStreamEvent,\n };\n}\n\ntype AsyncQueueWaiter<T> = {\n resolve: (result: IteratorResult<T>) => void;\n reject: (error: unknown) => void;\n};\n\nfunction createAsyncQueue<T>(): AsyncIterable<T> & {\n enqueue(value: T): void;\n close(): void;\n throw(error: unknown): void;\n} {\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\nfunction 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\nfunction 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\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 { CompletionModel, Document, JsonObject, JsonValue, ToolChoice } from \"../completion\";\nimport type { McpServer } from \"../mcp\";\nimport {\n type MemoryOptions,\n type MemoryRegistration,\n type MemoryStore,\n resolveMemoryOptions,\n} from \"../memory\";\nimport type { AgentObserver, AgentObserverRegistration, ObserveOptions } from \"../observability\";\nimport { toProviderJsonSchema, type ZodSchema } from \"../schema/zod-schema\";\nimport type { SkillSet } from \"../skills\";\nimport type { ToolSearchDocument } from \"../tool/dynamic-tools\";\nimport type { ToolMiddleware } from \"../tool/middleware\";\nimport type { AnyTool } from \"../tool/tool\";\nimport { ToolSet } from \"../tool/tool-set\";\nimport type { VectorSearchIndex } from \"../vector-store\";\nimport {\n Agent,\n type AgentEventStore,\n type AgentEventStoreOptions,\n type AgentEventStoreRegistration,\n type DynamicContextOptions,\n type DynamicContextRegistration,\n type DynamicToolOptions,\n type DynamicToolRegistration,\n} from \"./agent\";\nimport type { PromptHook } from \"./hooks\";\n\nexport class AgentBuilder<M extends CompletionModel = CompletionModel> {\n private readonly agentId: string;\n private agentName: string | undefined;\n private agentDescription: string | undefined;\n private instructionBlocks: string[] = [];\n private contextDocs: Document[] = [];\n private temp: number | undefined;\n private maxTokenCount: number | undefined;\n private params: JsonValue | undefined;\n private choice: ToolChoice | undefined;\n private turns: number | undefined;\n private requestHook: PromptHook | undefined;\n private schema: JsonObject | undefined;\n private skillInstructionBlocks: string[] = [];\n private observerRegistrations: AgentObserverRegistration[] = [];\n private dynamicContextRegistrations: DynamicContextRegistration[] = [];\n private dynamicToolRegistrations: DynamicToolRegistration[] = [];\n private middlewareRegistrations: ToolMiddleware[] = [];\n private memoryRegistration: MemoryRegistration | undefined;\n private eventStoreRegistration: AgentEventStoreRegistration | undefined;\n private activeToolSet = new ToolSet();\n\n constructor(\n agentId: string,\n private readonly completionModel: M,\n ) {\n this.agentId = normalizeAgentId(agentId);\n }\n\n name(name: string): this {\n this.agentName = name;\n return this;\n }\n\n description(description: string): this {\n this.agentDescription = description;\n return this;\n }\n\n instructions(instructions: string): this {\n if (instructions.length > 0) {\n this.instructionBlocks.push(instructions);\n }\n return this;\n }\n\n context(text: string, id = `static_doc_${this.contextDocs.length}`): this {\n this.contextDocs.push({ id, text });\n return this;\n }\n\n dynamicContext<T>(index: VectorSearchIndex<T>, options: DynamicContextOptions<T>): this {\n this.dynamicContextRegistrations.push({ index, options } as DynamicContextRegistration);\n return this;\n }\n\n dynamicTools(index: VectorSearchIndex<ToolSearchDocument>, options: DynamicToolOptions): this {\n this.dynamicToolRegistrations.push({ index, options });\n return this;\n }\n\n tool(tool: AnyTool): this {\n this.activeToolSet.addTool(tool);\n return this;\n }\n\n tools(tools: AnyTool[]): this {\n this.activeToolSet.addTools(tools);\n return this;\n }\n\n mcp(servers: McpServer[]): this {\n for (const server of servers) {\n this.activeToolSet.addTools(server.tools);\n }\n return this;\n }\n\n skills(skillSet: SkillSet): this {\n if (skillSet.instructions.length > 0) {\n this.skillInstructionBlocks.push(skillSet.instructions);\n }\n this.activeToolSet.addTools(skillSet.tools);\n return this;\n }\n\n useToolSet(toolSet: ToolSet): this {\n toolSet.addTools(this.activeToolSet);\n this.activeToolSet = toolSet;\n return this;\n }\n\n temperature(temperature: number): this {\n this.temp = temperature;\n return this;\n }\n\n maxTokens(maxTokens: number): this {\n this.maxTokenCount = maxTokens;\n return this;\n }\n\n additionalParams(params: JsonValue): this {\n this.params = params;\n return this;\n }\n\n toolChoice(toolChoice: ToolChoice): this {\n this.choice = toolChoice;\n return this;\n }\n\n defaultMaxTurns(defaultMaxTurns: number): this {\n this.turns = defaultMaxTurns;\n return this;\n }\n\n hook(hook: PromptHook): this {\n this.requestHook = hook;\n return this;\n }\n\n toolMiddleware(middleware: ToolMiddleware): this {\n this.middlewareRegistrations.push(middleware);\n return this;\n }\n\n toolMiddlewares(middlewares: ToolMiddleware[]): this {\n this.middlewareRegistrations.push(...middlewares);\n return this;\n }\n\n observe(observer: AgentObserver, options: ObserveOptions = {}): this {\n this.observerRegistrations.push({\n observer,\n failOnObserverError: options.failOnObserverError,\n });\n return this;\n }\n\n memory(store: MemoryStore, options: MemoryOptions = {}): this {\n this.memoryRegistration = {\n store,\n options: resolveMemoryOptions(options),\n };\n return this;\n }\n\n eventStore(store: AgentEventStore, options: AgentEventStoreOptions = {}): this {\n this.eventStoreRegistration = {\n store,\n options: {\n include: options.include ?? \"all\",\n },\n };\n return this;\n }\n\n outputSchema(schema: ZodSchema): this {\n this.schema = toProviderJsonSchema(schema);\n return this;\n }\n\n build(): Agent<M> {\n return new Agent({\n id: this.agentId,\n name: this.agentName,\n description: this.agentDescription,\n model: this.completionModel,\n instructions: this.buildInstructions(),\n staticContext: this.contextDocs,\n temperature: this.temp,\n maxTokens: this.maxTokenCount,\n additionalParams: this.params,\n toolSet: this.activeToolSet,\n toolChoice: this.choice,\n defaultMaxTurns: this.turns,\n hook: this.requestHook,\n outputSchema: this.schema,\n observers: this.observerRegistrations,\n dynamicContexts: this.dynamicContextRegistrations,\n dynamicTools: this.dynamicToolRegistrations,\n toolMiddlewares: this.middlewareRegistrations,\n memory: this.memoryRegistration,\n eventStore: this.eventStoreRegistration,\n });\n }\n\n private buildInstructions(): string | undefined {\n const parts = [...this.instructionBlocks, ...this.skillInstructionBlocks].filter(\n (part): part is string => part !== undefined && part.length > 0,\n );\n return parts.length === 0 ? undefined : parts.join(\"\\n\\n\");\n }\n}\n\nfunction normalizeAgentId(id: string): string {\n if (typeof id !== \"string\") {\n throw new TypeError(\"Agent id must be a string.\");\n }\n\n const normalized = id.trim();\n if (normalized.length === 0) {\n throw new TypeError(\"Agent id must be a non-empty string.\");\n }\n\n return normalized;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS;;;ACkBlB,eAAsB,uBACpB,eACA,MACA,qBACkC;AAClC,QAAM,eAAmC,CAAC;AAC1C,aAAW,gBAAgB,eAAe;AACxC,QAAI;AACF,YAAM,cAAc,MAAM,aAAa,SAAS,SAAS,IAAI;AAC7D,UAAI,gBAAgB,QAAW;AAC7B,qBAAa,KAAK,WAAW;AAAA,MAC/B;AAAA,IACF,SAAS,OAAO;AACd,UAAI,uBAAuB,aAAa,wBAAwB,MAAM;AACpE,cAAM;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,SAAO,IAAI,wBAAwB,cAAc,mBAAmB;AACtE;AAEO,IAAM,0BAAN,MAA8B;AAAA,EAGnC,YACmB,cACA,qBACjB;AAFiB;AACA;AAEjB,SAAK,QAAQ,aAAa,KAAK,CAAC,aAAa,SAAS,UAAU,MAAS,GAAG;AAAA,EAC9E;AAAA,EAJmB;AAAA,EACA;AAAA,EAJV;AAAA,EAST,MAAM,gBAAgB,MAAoE;AACxF,UAAM,sBAAiD,CAAC;AACxD,eAAW,eAAe,KAAK,cAAc;AAC3C,UAAI,YAAY,oBAAoB,QAAW;AAC7C;AAAA,MACF;AACA,UAAI;AACF,cAAM,qBAAqB,MAAM,YAAY,gBAAgB,IAAI;AACjE,YAAI,uBAAuB,QAAW;AACpC,8BAAoB,KAAK,kBAAkB;AAAA,QAC7C;AAAA,MACF,SAAS,OAAO;AACd,aAAK,YAAY,KAAK;AAAA,MACxB;AAAA,IACF;AACA,WAAO,IAAI,0BAA0B,qBAAqB,KAAK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;AAAA,MACtB,MAAM,KAAK;AAAA,MACX,cAAc,KAAK;AAAA,MACnB,WAAW,KAAK;AAAA,MAChB,iBAAiB,KAAK;AAAA,MACtB,cAAc,KAAK;AAAA,MACnB,iBAAiB,KAAK;AAAA,MACtB,QAAQ,KAAK;AAAA,MACb,YAAY,KAAK;AAAA,IACnB,CAAC;AAAA,EACH;AAAA,EAEQ,oBAAwC;AAC9C,UAAM,QAAQ,CAAC,GAAG,KAAK,mBAAmB,GAAG,KAAK,sBAAsB,EAAE;AAAA,MACxE,CAAC,SAAyB,SAAS,UAAa,KAAK,SAAS;AAAA,IAChE;AACA,WAAO,MAAM,WAAW,IAAI,SAAY,MAAM,KAAK,MAAM;AAAA,EAC3D;AACF;AAEA,SAASA,kBAAiB,IAAoB;AAC5C,MAAI,OAAO,OAAO,UAAU;AAC1B,UAAM,IAAI,UAAU,4BAA4B;AAAA,EAClD;AAEA,QAAM,aAAa,GAAG,KAAK;AAC3B,MAAI,WAAW,WAAW,GAAG;AAC3B,UAAM,IAAI,UAAU,sCAAsC;AAAA,EAC5D;AAEA,SAAO;AACT;","names":["normalizeAgentId"]}
@@ -1,43 +0,0 @@
1
- // src/audio-generation/index.ts
2
- var AudioGenerationRequestBuilder = class {
3
- constructor(model) {
4
- this.model = model;
5
- }
6
- model;
7
- request = {
8
- text: "",
9
- voice: "",
10
- speed: 1
11
- };
12
- text(text) {
13
- this.request = { ...this.request, text };
14
- return this;
15
- }
16
- voice(voice) {
17
- this.request = { ...this.request, voice };
18
- return this;
19
- }
20
- speed(speed) {
21
- this.request = { ...this.request, speed };
22
- return this;
23
- }
24
- additionalParams(additionalParams) {
25
- this.request = { ...this.request, additionalParams };
26
- return this;
27
- }
28
- build() {
29
- return { ...this.request };
30
- }
31
- send() {
32
- return this.model.audioGeneration(this.build());
33
- }
34
- };
35
- function audioGenerationRequest(model) {
36
- return new AudioGenerationRequestBuilder(model);
37
- }
38
-
39
- export {
40
- AudioGenerationRequestBuilder,
41
- audioGenerationRequest
42
- };
43
- //# sourceMappingURL=chunk-I77SDTFE.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/audio-generation/index.ts"],"sourcesContent":["import type { JsonValue } from \"../completion\";\n\nexport type AudioGenerationRequest = {\n text: string;\n voice: string;\n speed: number;\n additionalParams?: JsonValue | undefined;\n};\n\nexport type AudioGenerationResponse<RawResponse = unknown> = {\n audio: Uint8Array;\n mediaType?: string | undefined;\n rawResponse: RawResponse;\n};\n\nexport interface AudioGenerationModel<RawResponse = unknown> {\n readonly provider?: string | undefined;\n readonly defaultModel?: string | undefined;\n audioGeneration(request: AudioGenerationRequest): Promise<AudioGenerationResponse<RawResponse>>;\n}\n\nexport class AudioGenerationRequestBuilder<\n Model extends AudioGenerationModel = AudioGenerationModel,\n> {\n private request: AudioGenerationRequest = {\n text: \"\",\n voice: \"\",\n speed: 1,\n };\n\n constructor(private readonly model: Model) {}\n\n text(text: string): this {\n this.request = { ...this.request, text };\n return this;\n }\n\n voice(voice: string): this {\n this.request = { ...this.request, voice };\n return this;\n }\n\n speed(speed: number): this {\n this.request = { ...this.request, speed };\n return this;\n }\n\n additionalParams(additionalParams: JsonValue): this {\n this.request = { ...this.request, additionalParams };\n return this;\n }\n\n build(): AudioGenerationRequest {\n return { ...this.request };\n }\n\n send(): Promise<Awaited<ReturnType<Model[\"audioGeneration\"]>>> {\n return this.model.audioGeneration(this.build()) as Promise<\n Awaited<ReturnType<Model[\"audioGeneration\"]>>\n >;\n }\n}\n\nexport function audioGenerationRequest<Model extends AudioGenerationModel>(\n model: Model,\n): AudioGenerationRequestBuilder<Model> {\n return new AudioGenerationRequestBuilder(model);\n}\n"],"mappings":";AAqBO,IAAM,gCAAN,MAEL;AAAA,EAOA,YAA6B,OAAc;AAAd;AAAA,EAAe;AAAA,EAAf;AAAA,EANrB,UAAkC;AAAA,IACxC,MAAM;AAAA,IACN,OAAO;AAAA,IACP,OAAO;AAAA,EACT;AAAA,EAIA,KAAK,MAAoB;AACvB,SAAK,UAAU,EAAE,GAAG,KAAK,SAAS,KAAK;AACvC,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,OAAqB;AACzB,SAAK,UAAU,EAAE,GAAG,KAAK,SAAS,MAAM;AACxC,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,OAAqB;AACzB,SAAK,UAAU,EAAE,GAAG,KAAK,SAAS,MAAM;AACxC,WAAO;AAAA,EACT;AAAA,EAEA,iBAAiB,kBAAmC;AAClD,SAAK,UAAU,EAAE,GAAG,KAAK,SAAS,iBAAiB;AACnD,WAAO;AAAA,EACT;AAAA,EAEA,QAAgC;AAC9B,WAAO,EAAE,GAAG,KAAK,QAAQ;AAAA,EAC3B;AAAA,EAEA,OAA+D;AAC7D,WAAO,KAAK,MAAM,gBAAgB,KAAK,MAAM,CAAC;AAAA,EAGhD;AACF;AAEO,SAAS,uBACd,OACsC;AACtC,SAAO,IAAI,8BAA8B,KAAK;AAChD;","names":[]}
@@ -1,146 +0,0 @@
1
- // src/mcp/result.ts
2
- function createCallToolParams(name, args) {
3
- if (args === null || args === void 0) {
4
- return { name };
5
- }
6
- if (!isPlainRecord(args)) {
7
- throw new Error("MCP tool arguments must be a JSON object");
8
- }
9
- return { name, arguments: args };
10
- }
11
- function mapMcpToolResult(result) {
12
- if ("toolResult" in result) {
13
- return serializeMcpValue(result.toolResult);
14
- }
15
- if (result.isError === true) {
16
- throw new Error(mcpErrorMessage(result.content));
17
- }
18
- return result.content.map(mapMcpContent).join("");
19
- }
20
- function mcpErrorMessage(content) {
21
- const text = content.map((item) => item.type === "text" ? item.text : void 0).filter((item) => item !== void 0).join("\n");
22
- return text === "" ? "MCP tool returned an error" : text;
23
- }
24
- function mapMcpContent(content) {
25
- if (content.type === "text") {
26
- return content.text;
27
- }
28
- if (content.type === "image") {
29
- return `data:${content.mimeType};base64,${content.data}`;
30
- }
31
- if (content.type === "resource") {
32
- const mimeType = content.resource.mimeType === void 0 ? "" : `data:${content.resource.mimeType};`;
33
- if ("text" in content.resource) {
34
- return `${mimeType}${content.resource.uri}:${content.resource.text}`;
35
- }
36
- return `${mimeType}${content.resource.uri}:${content.resource.blob}`;
37
- }
38
- throw new Error(`Unsupported MCP tool result content: ${serializeMcpValue(content)}`);
39
- }
40
- function serializeMcpValue(value) {
41
- if (typeof value === "string") {
42
- return value;
43
- }
44
- const serialized = JSON.stringify(value);
45
- return serialized === void 0 ? String(value) : serialized;
46
- }
47
- function isPlainRecord(value) {
48
- return typeof value === "object" && value !== null && !Array.isArray(value);
49
- }
50
-
51
- // src/mcp/tool.ts
52
- var MCP_TOOL_METADATA_KEY = /* @__PURE__ */ Symbol.for("anvia.mcp.tool.metadata");
53
- function createMcpTool(definition, client, serverName) {
54
- const tool = {
55
- name: definition.name,
56
- definition() {
57
- return {
58
- name: definition.name,
59
- description: definition.description ?? "",
60
- parameters: definition.inputSchema
61
- };
62
- },
63
- async call(args) {
64
- const result = await client.callTool(createCallToolParams(definition.name, args));
65
- return mapMcpToolResult(result);
66
- }
67
- };
68
- if (serverName !== void 0) {
69
- Object.defineProperty(tool, MCP_TOOL_METADATA_KEY, {
70
- value: { serverName },
71
- enumerable: false
72
- });
73
- }
74
- return tool;
75
- }
76
-
77
- // src/mcp/connect.ts
78
- async function connectMcp(connection) {
79
- const client = await connection.connect();
80
- const { tools } = await client.listTools();
81
- return {
82
- name: connection.name,
83
- tools: tools.map((tool) => createMcpTool(tool, client, connection.name)),
84
- close: () => client.close()
85
- };
86
- }
87
-
88
- // src/mcp/connections.ts
89
- import { Client } from "@modelcontextprotocol/sdk/client/index.js";
90
- import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
91
- import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
92
- import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
93
- var mcp = {
94
- stdio(options) {
95
- return {
96
- name: options.name,
97
- async connect() {
98
- const { name: _name, ...server } = options;
99
- const client = createSdkClient();
100
- await client.connect(asSdkTransport(new StdioClientTransport(server)));
101
- return client;
102
- }
103
- };
104
- },
105
- http(options) {
106
- return {
107
- name: options.name,
108
- async connect() {
109
- const client = createSdkClient();
110
- await client.connect(
111
- asSdkTransport(
112
- new StreamableHTTPClientTransport(new URL(options.url), options.transport)
113
- )
114
- );
115
- return client;
116
- }
117
- };
118
- },
119
- sse(options) {
120
- return {
121
- name: options.name,
122
- async connect() {
123
- const client = createSdkClient();
124
- await client.connect(
125
- asSdkTransport(new SSEClientTransport(new URL(options.url), options.transport))
126
- );
127
- return client;
128
- }
129
- };
130
- }
131
- };
132
- function createSdkClient() {
133
- return new Client({
134
- name: "@anvia/core",
135
- version: "0.1.0"
136
- });
137
- }
138
- function asSdkTransport(transport) {
139
- return transport;
140
- }
141
-
142
- export {
143
- connectMcp,
144
- mcp
145
- };
146
- //# sourceMappingURL=chunk-NYUOBGVI.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/mcp/result.ts","../src/mcp/tool.ts","../src/mcp/connect.ts","../src/mcp/connections.ts"],"sourcesContent":["import type { JsonValue } from \"../completion/index\";\nimport type { McpToolCallContent, McpToolCallResult } from \"./types\";\n\nexport function createCallToolParams(\n name: string,\n args: unknown,\n): { name: string; arguments?: Record<string, unknown> } {\n if (args === null || args === undefined) {\n return { name };\n }\n\n if (!isPlainRecord(args)) {\n throw new Error(\"MCP tool arguments must be a JSON object\");\n }\n\n return { name, arguments: args };\n}\n\nexport function mapMcpToolResult(result: McpToolCallResult): string {\n if (\"toolResult\" in result) {\n return serializeMcpValue(result.toolResult);\n }\n\n if (result.isError === true) {\n throw new Error(mcpErrorMessage(result.content));\n }\n\n return result.content.map(mapMcpContent).join(\"\");\n}\n\nfunction mcpErrorMessage(content: McpToolCallContent[]): string {\n const text = content\n .map((item) => (item.type === \"text\" ? item.text : undefined))\n .filter((item): item is string => item !== undefined)\n .join(\"\\n\");\n\n return text === \"\" ? \"MCP tool returned an error\" : text;\n}\n\nfunction mapMcpContent(content: McpToolCallContent): string {\n if (content.type === \"text\") {\n return content.text;\n }\n\n if (content.type === \"image\") {\n return `data:${content.mimeType};base64,${content.data}`;\n }\n\n if (content.type === \"resource\") {\n const mimeType =\n content.resource.mimeType === undefined ? \"\" : `data:${content.resource.mimeType};`;\n if (\"text\" in content.resource) {\n return `${mimeType}${content.resource.uri}:${content.resource.text}`;\n }\n\n return `${mimeType}${content.resource.uri}:${content.resource.blob}`;\n }\n\n throw new Error(`Unsupported MCP tool result content: ${serializeMcpValue(content)}`);\n}\n\nfunction serializeMcpValue(value: unknown): string {\n if (typeof value === \"string\") {\n return value;\n }\n\n const serialized = JSON.stringify(value);\n return serialized === undefined ? String(value) : serialized;\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, JsonValue> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import type { ToolDefinition } from \"../completion/index\";\nimport type { Tool } from \"../tool/index\";\nimport { createCallToolParams, mapMcpToolResult } from \"./result\";\nimport type { McpClient, McpToolDefinition } from \"./types\";\n\nconst MCP_TOOL_METADATA_KEY = Symbol.for(\"anvia.mcp.tool.metadata\");\n\nexport function createMcpTool(\n definition: McpToolDefinition,\n client: McpClient,\n serverName?: string,\n): Tool {\n const tool: Tool = {\n name: definition.name,\n definition(): ToolDefinition {\n return {\n name: definition.name,\n description: definition.description ?? \"\",\n parameters: definition.inputSchema,\n };\n },\n async call(args): Promise<string> {\n const result = await client.callTool(createCallToolParams(definition.name, args));\n return mapMcpToolResult(result);\n },\n };\n if (serverName !== undefined) {\n Object.defineProperty(tool, MCP_TOOL_METADATA_KEY, {\n value: { serverName },\n enumerable: false,\n });\n }\n return tool;\n}\n","import { createMcpTool } from \"./tool\";\nimport type { McpConnection, McpServer } from \"./types\";\n\nexport async function connectMcp(connection: McpConnection): Promise<McpServer> {\n const client = await connection.connect();\n const { tools } = await client.listTools();\n\n return {\n name: connection.name,\n tools: tools.map((tool) => createMcpTool(tool, client, connection.name)),\n close: () => client.close(),\n };\n}\n","import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { StdioClientTransport } from \"@modelcontextprotocol/sdk/client/stdio.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport type {\n McpClient,\n McpConnection,\n McpHttpOptions,\n McpSseOptions,\n McpStdioOptions,\n} from \"./types\";\n\nexport const mcp = {\n stdio(options: McpStdioOptions): McpConnection {\n return {\n name: options.name,\n async connect(): Promise<McpClient> {\n const { name: _name, ...server } = options;\n const client = createSdkClient();\n await client.connect(asSdkTransport(new StdioClientTransport(server)));\n return client as McpClient;\n },\n };\n },\n\n http(options: McpHttpOptions): McpConnection {\n return {\n name: options.name,\n async connect(): Promise<McpClient> {\n const client = createSdkClient();\n await client.connect(\n asSdkTransport(\n new StreamableHTTPClientTransport(new URL(options.url), options.transport),\n ),\n );\n return client as McpClient;\n },\n };\n },\n\n sse(options: McpSseOptions): McpConnection {\n return {\n name: options.name,\n async connect(): Promise<McpClient> {\n const client = createSdkClient();\n await client.connect(\n asSdkTransport(new SSEClientTransport(new URL(options.url), options.transport)),\n );\n return client as McpClient;\n },\n };\n },\n};\n\nfunction createSdkClient(): Client {\n return new Client({\n name: \"@anvia/core\",\n version: \"0.1.0\",\n });\n}\n\nfunction asSdkTransport(transport: unknown): Parameters<Client[\"connect\"]>[0] {\n return transport as Parameters<Client[\"connect\"]>[0];\n}\n"],"mappings":";AAGO,SAAS,qBACd,MACA,MACuD;AACvD,MAAI,SAAS,QAAQ,SAAS,QAAW;AACvC,WAAO,EAAE,KAAK;AAAA,EAChB;AAEA,MAAI,CAAC,cAAc,IAAI,GAAG;AACxB,UAAM,IAAI,MAAM,0CAA0C;AAAA,EAC5D;AAEA,SAAO,EAAE,MAAM,WAAW,KAAK;AACjC;AAEO,SAAS,iBAAiB,QAAmC;AAClE,MAAI,gBAAgB,QAAQ;AAC1B,WAAO,kBAAkB,OAAO,UAAU;AAA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,QAAQ;AAAA,MACd,MAAM,UAA8B;AAClC,cAAM,SAAS,gBAAgB;AAC/B,cAAM,OAAO;AAAA,UACX;AAAA,YACE,IAAI,8BAA8B,IAAI,IAAI,QAAQ,GAAG,GAAG,QAAQ,SAAS;AAAA,UAC3E;AAAA,QACF;AACA,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AAAA,EAEA,IAAI,SAAuC;AACzC,WAAO;AAAA,MACL,MAAM,QAAQ;AAAA,MACd,MAAM,UAA8B;AAClC,cAAM,SAAS,gBAAgB;AAC/B,cAAM,OAAO;AAAA,UACX,eAAe,IAAI,mBAAmB,IAAI,IAAI,QAAQ,GAAG,GAAG,QAAQ,SAAS,CAAC;AAAA,QAChF;AACA,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AACF;AAEA,SAAS,kBAA0B;AACjC,SAAO,IAAI,OAAO;AAAA,IAChB,MAAM;AAAA,IACN,SAAS;AAAA,EACX,CAAC;AACH;AAEA,SAAS,eAAe,WAAsD;AAC5E,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/extractor/extractor.ts"],"sourcesContent":["import { type Agent, AgentBuilder } from \"../agent/index\";\nimport {\n CompletionCapabilityError,\n type CompletionModel,\n CompletionRequestBuilder,\n type CompletionResponse,\n type JsonValue,\n type Message,\n Message as MessageFactory,\n type ToolChoice,\n Usage,\n} from \"../completion/index\";\nimport type { ZodSchema } from \"../schema/zod-schema\";\nimport { createTool } from \"../tool/index\";\n\nconst SUBMIT_TOOL_NAME = \"submit\";\n\nconst DEFAULT_EXTRACTOR_INSTRUCTIONS =\n \"You are an AI assistant whose purpose is to extract structured data from the provided text.\\n\" +\n \"You have access to a `submit` function that defines the structure of the data to extract.\\n\" +\n \"Always call the `submit` function with the structured data. Use default or null values when information is missing.\";\n\nexport type ExtractionResponse<T> = {\n data: T;\n usage: Usage;\n messages: Message[];\n};\n\nexport class ExtractionError extends Error {\n constructor(\n message: string,\n readonly cause?: unknown,\n ) {\n super(message);\n this.name = \"ExtractionError\";\n }\n}\n\nexport class Extractor<T, M extends CompletionModel = CompletionModel> {\n constructor(\n private readonly agent: Agent<M>,\n private readonly schema: ZodSchema<T>,\n private readonly retryCount: number,\n ) {}\n\n async extract(text: string | Message): Promise<T> {\n return (await this.extractWithUsage(text)).data;\n }\n\n async extractWithUsage(text: string | Message): Promise<ExtractionResponse<T>> {\n return this.run(text);\n }\n\n async extractWithHistory(text: string | Message, history: Message[]): Promise<T> {\n return (await this.run(text, history)).data;\n }\n\n getInner(): Agent<M> {\n return this.agent;\n }\n\n private async run(text: string | Message, history?: Message[]): Promise<ExtractionResponse<T>> {\n let usage = Usage.empty();\n let lastError: unknown;\n const prompt = typeof text === \"string\" ? MessageFactory.user(text) : text;\n\n for (let attempt = 0; attempt <= this.retryCount; attempt += 1) {\n try {\n const toolDefs = await this.agent.toolSet.getToolDefinitions(extractRagText(prompt));\n const response = await new CompletionRequestBuilder(this.agent.model, prompt)\n .instructions(this.agent.instructions)\n .messages(history ?? [])\n .documents(this.agent.staticContext)\n .tools(toolDefs)\n .temperature(this.agent.temperature)\n .maxTokens(this.agent.maxTokens)\n .additionalParams(this.agent.additionalParams)\n .toolChoice(this.agent.toolChoice)\n .send();\n usage = Usage.add(usage, response.usage);\n const data = extractSubmittedData(response, this.schema);\n return {\n data,\n usage,\n messages: [\n ...(history ?? []),\n prompt,\n MessageFactory.assistant(response.choice, response.messageId),\n ],\n };\n } catch (error) {\n if (error instanceof CompletionCapabilityError) {\n throw error;\n }\n lastError = error;\n }\n }\n\n throw new ExtractionError(\"No data extracted\", lastError);\n }\n}\n\nexport class ExtractorBuilder<T, M extends CompletionModel = CompletionModel> {\n private readonly agentBuilder: AgentBuilder<M>;\n private retryCount = 0;\n\n constructor(\n model: M,\n private readonly schema: ZodSchema<T>,\n ) {\n this.agentBuilder = new AgentBuilder(\"extractor\", model)\n .instructions(DEFAULT_EXTRACTOR_INSTRUCTIONS)\n .tool(\n createTool({\n name: SUBMIT_TOOL_NAME,\n description: \"Submit the structured data extracted from the provided text.\",\n input: schema,\n output: schema,\n execute: (args) => args,\n }),\n )\n .toolChoice(\"required\");\n }\n\n instructions(instructions: string): this {\n this.agentBuilder.instructions(instructions);\n return this;\n }\n\n context(text: string, id?: string): this {\n this.agentBuilder.context(text, id);\n return this;\n }\n\n temperature(temperature: number): this {\n this.agentBuilder.temperature(temperature);\n return this;\n }\n\n maxTokens(maxTokens: number): this {\n this.agentBuilder.maxTokens(maxTokens);\n return this;\n }\n\n additionalParams(params: JsonValue): this {\n this.agentBuilder.additionalParams(params);\n return this;\n }\n\n toolChoice(toolChoice: ToolChoice): this {\n this.agentBuilder.toolChoice(toolChoice);\n return this;\n }\n\n retries(retries: number): this {\n this.retryCount = Math.max(0, Math.trunc(retries));\n return this;\n }\n\n build(): Extractor<T, M> {\n return new Extractor(this.agentBuilder.build(), this.schema, this.retryCount);\n }\n}\n\nfunction extractSubmittedData<T>(response: CompletionResponse, schema: ZodSchema<T>): T {\n const submitted = response.choice\n .filter((content) => content.type === \"tool_call\")\n .filter((toolCall) => toolCall.function.name === SUBMIT_TOOL_NAME)\n .at(-1);\n\n if (submitted === undefined) {\n throw new ExtractionError(\"The model did not call the submit tool\");\n }\n\n return schema.parse(submitted.function.arguments);\n}\n\nfunction extractRagText(message: Message): string | undefined {\n if (message.role === \"user\") {\n return message.content.flatMap((item) => (item.type === \"text\" ? [item.text] : [])).join(\"\\n\");\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;AAeA,IAAM,mBAAmB;AAEzB,IAAM,iCACJ;AAUK,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YACE,SACS,OACT;AACA,UAAM,OAAO;AAFJ;AAGT,SAAK,OAAO;AAAA,EACd;AAAA,EAJW;AAKb;AAEO,IAAM,YAAN,MAAgE;AAAA,EACrE,YACmB,OACA,QACA,YACjB;AAHiB;AACA;AACA;AAAA,EAChB;AAAA,EAHgB;AAAA,EACA;AAA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