@anvia/core 0.13.0 → 0.13.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 (63) hide show
  1. package/dist/agent/index.d.ts +2 -2
  2. package/dist/agent/index.js +10 -11
  3. package/dist/{agent-CXvjoW0J.d.ts → agent-3qSfIKIj.d.ts} +1 -0
  4. package/dist/{chunk-NPZDYOE6.js → chunk-2ODTMRHP.js} +11 -10
  5. package/dist/chunk-2ODTMRHP.js.map +1 -0
  6. package/dist/{chunk-OCYL4AB6.js → chunk-CLFDBOH3.js} +6 -6
  7. package/dist/{chunk-7H3TQN3I.js → chunk-CNTGKNZ3.js} +7 -7
  8. package/dist/chunk-CNTGKNZ3.js.map +1 -0
  9. package/dist/chunk-CQNNSZPG.js +9 -0
  10. package/dist/chunk-CQNNSZPG.js.map +1 -0
  11. package/dist/{chunk-HF4KHHNM.js → chunk-DC2GJDPR.js} +5 -5
  12. package/dist/chunk-DC2GJDPR.js.map +1 -0
  13. package/dist/{chunk-IZM6FNCT.js → chunk-I7TM7TKX.js} +48 -42
  14. package/dist/chunk-I7TM7TKX.js.map +1 -0
  15. package/dist/{chunk-JT4U4FGG.js → chunk-KXXFWLKP.js} +3 -3
  16. package/dist/{chunk-7BV5JBJW.js → chunk-L52YHJ5L.js} +23 -20
  17. package/dist/chunk-L52YHJ5L.js.map +1 -0
  18. package/dist/{chunk-MU3UPROJ.js → chunk-NS7W4G26.js} +21 -12
  19. package/dist/chunk-NS7W4G26.js.map +1 -0
  20. package/dist/{chunk-46IR5ZTN.js → chunk-WHHQWT7D.js} +12 -13
  21. package/dist/chunk-WHHQWT7D.js.map +1 -0
  22. package/dist/{chunk-HLISYYCB.js → chunk-WWNXZWST.js} +208 -132
  23. package/dist/chunk-WWNXZWST.js.map +1 -0
  24. package/dist/{chunk-JS5MGVNM.js → chunk-YBBD4HZ3.js} +8 -7
  25. package/dist/{chunk-JS5MGVNM.js.map → chunk-YBBD4HZ3.js.map} +1 -1
  26. package/dist/{chunk-W53PLBOL.js → chunk-YTF65GYU.js} +2 -2
  27. package/dist/completion/index.js +2 -2
  28. package/dist/embeddings/index.js +1 -1
  29. package/dist/evals/index.d.ts +1 -1
  30. package/dist/evals/index.js +59 -36
  31. package/dist/evals/index.js.map +1 -1
  32. package/dist/extractor/index.d.ts +1 -1
  33. package/dist/extractor/index.js +11 -12
  34. package/dist/hooks/index.js +1 -2
  35. package/dist/index.d.ts +1 -1
  36. package/dist/index.js +13 -13
  37. package/dist/internal/agent.d.ts +1 -1
  38. package/dist/internal/agent.js +9 -10
  39. package/dist/mcp/index.js +1 -1
  40. package/dist/mcp/index.js.map +1 -1
  41. package/dist/pipeline/index.d.ts +1 -1
  42. package/dist/pipeline/index.js +34 -19
  43. package/dist/pipeline/index.js.map +1 -1
  44. package/dist/request/index.d.ts +1 -1
  45. package/dist/request/index.js +8 -9
  46. package/dist/skills/index.js +7 -7
  47. package/dist/tool/index.js +5 -6
  48. package/dist/ui/index.js +2 -2
  49. package/dist/vector-store/index.js +3 -4
  50. package/package.json +1 -1
  51. package/dist/chunk-46IR5ZTN.js.map +0 -1
  52. package/dist/chunk-7BV5JBJW.js.map +0 -1
  53. package/dist/chunk-7H3TQN3I.js.map +0 -1
  54. package/dist/chunk-HF4KHHNM.js.map +0 -1
  55. package/dist/chunk-HLISYYCB.js.map +0 -1
  56. package/dist/chunk-IZM6FNCT.js.map +0 -1
  57. package/dist/chunk-MMHG7WAM.js +0 -19
  58. package/dist/chunk-MMHG7WAM.js.map +0 -1
  59. package/dist/chunk-MU3UPROJ.js.map +0 -1
  60. package/dist/chunk-NPZDYOE6.js.map +0 -1
  61. /package/dist/{chunk-OCYL4AB6.js.map → chunk-CLFDBOH3.js.map} +0 -0
  62. /package/dist/{chunk-JT4U4FGG.js.map → chunk-KXXFWLKP.js.map} +0 -0
  63. /package/dist/{chunk-W53PLBOL.js.map → chunk-YTF65GYU.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/request/errors.ts","../src/internal/async-queue.ts","../src/internal/prompt-runtime/memory.ts","../src/internal/prompt-runtime/retrieval.ts","../src/internal/prompt-runtime/stream-accumulator.ts","../src/internal/prompt-runtime/stream-events.ts","../src/internal/prompt-runtime/tool-execution.ts","../src/internal/rag-text.ts","../src/observability/group.ts","../src/request/prompt-request.ts"],"sourcesContent":["import type { Message } from \"../completion/index\";\nimport type { ToolApprovalRequest } from \"../tool\";\n\nexport class MaxTurnsError extends Error {\n constructor(\n readonly maxTurns: number,\n readonly chatHistory: Message[],\n readonly prompt: Message,\n ) {\n super(`Reached max turn limit: ${maxTurns}`);\n this.name = \"MaxTurnsError\";\n }\n}\n\nexport class PromptCancelledError extends Error {\n constructor(\n readonly chatHistory: Message[],\n readonly reason: string,\n ) {\n super(`Prompt cancelled: ${reason}`);\n this.name = \"PromptCancelledError\";\n }\n}\n\nexport class ToolApprovalRequiredError extends Error {\n constructor(readonly request: ToolApprovalRequest) {\n super(`Tool approval required for ${request.toolName}, but no approval handler is configured.`);\n this.name = \"ToolApprovalRequiredError\";\n }\n}\n","type AsyncQueueWaiter<T> = {\n resolve: (result: IteratorResult<T>) => void;\n reject: (error: unknown) => void;\n};\n\nexport type AsyncQueue<T> = AsyncIterable<T> & {\n enqueue(value: T): void;\n close(): void;\n throw(error: unknown): void;\n};\n\nexport function createAsyncQueue<T>(): AsyncQueue<T> {\n const values: T[] = [];\n const waiters: AsyncQueueWaiter<T>[] = [];\n let closed = false;\n let error: unknown;\n\n function flush(): void {\n while (waiters.length > 0 && values.length > 0) {\n const waiter = waiters.shift();\n const value = values.shift() as T;\n if (waiter !== undefined) {\n waiter.resolve({ value, done: false });\n }\n }\n\n if (values.length > 0 || waiters.length === 0 || !closed) {\n return;\n }\n\n while (waiters.length > 0) {\n const waiter = waiters.shift();\n if (waiter === undefined) {\n continue;\n }\n if (error !== undefined) {\n waiter.reject(error);\n } else {\n waiter.resolve({ value: undefined, done: true });\n }\n }\n }\n\n return {\n enqueue(value: T): void {\n if (closed) {\n return;\n }\n values.push(value);\n flush();\n },\n close(): void {\n closed = true;\n flush();\n },\n throw(thrown: unknown): void {\n closed = true;\n error = thrown;\n flush();\n },\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return {\n next(): Promise<IteratorResult<T>> {\n if (values.length > 0) {\n const value = values.shift() as T;\n return Promise.resolve({ value, done: false });\n }\n if (error !== undefined) {\n return Promise.reject(error);\n }\n if (closed) {\n return Promise.resolve({ value: undefined, done: true });\n }\n return new Promise((resolve, reject) => {\n waiters.push({ resolve, reject });\n });\n },\n };\n },\n };\n}\n","import type { Agent } from \"../../agent/agent\";\nimport type { Message as MessageType } from \"../../completion/index\";\nimport type { MemoryContext, MemoryRegistration, MemorySavePolicy } from \"../../memory/types\";\n\nexport class PromptRequestMemory {\n constructor(\n private readonly agent: Agent,\n private readonly memoryContext: MemoryContext | undefined,\n private readonly initialHistory: MessageType[],\n ) {}\n\n memoryPolicy(): MemorySavePolicy | undefined {\n return this.memory()?.options.savePolicy;\n }\n\n pendingTurnMessages(newMessages: MessageType[]): MessageType[] {\n return this.memoryPolicy() === \"turn\" ? [...newMessages] : [];\n }\n\n async prepareRun(runId: string, newMessages: MessageType[]): Promise<MessageType[]> {\n const memory = this.memory();\n if (memory === undefined || this.memoryContext === undefined) {\n return this.initialHistory;\n }\n\n const memoryHistory = await memory.store.load(this.memoryContext);\n const chatHistory = [...memoryHistory, ...this.initialHistory];\n if (memory.options.savePolicy === \"message\") {\n await memory.store.append({\n context: this.memoryContext,\n runId,\n turn: 1,\n messages: newMessages,\n });\n }\n return chatHistory;\n }\n\n async commitMessages(\n runId: string,\n turn: number,\n messages: MessageType[],\n pendingTurnMessages: MessageType[],\n ): Promise<void> {\n const memory = this.memory();\n if (memory === undefined || this.memoryContext === undefined || messages.length === 0) {\n return;\n }\n if (memory.options.savePolicy === \"message\") {\n await memory.store.append({\n context: this.memoryContext,\n runId,\n turn,\n messages,\n });\n } else if (memory.options.savePolicy === \"turn\") {\n pendingTurnMessages.push(...messages);\n }\n }\n\n async commitCompletedTurn(\n runId: string,\n turn: number,\n pendingTurnMessages: MessageType[],\n ): Promise<void> {\n const memory = this.memory();\n if (\n memory === undefined ||\n this.memoryContext === undefined ||\n memory.options.savePolicy !== \"turn\" ||\n pendingTurnMessages.length === 0\n ) {\n return;\n }\n await memory.store.append({\n context: this.memoryContext,\n runId,\n turn,\n messages: [...pendingTurnMessages],\n });\n pendingTurnMessages.length = 0;\n }\n\n async commitCompletedRun(\n runId: string,\n turn: number,\n newMessages: MessageType[],\n pendingTurnMessages: MessageType[],\n ): Promise<void> {\n await this.commitCompletedTurn(runId, turn, pendingTurnMessages);\n const memory = this.memory();\n if (\n memory === undefined ||\n this.memoryContext === undefined ||\n memory.options.savePolicy !== \"run\"\n ) {\n return;\n }\n await memory.store.append({\n context: this.memoryContext,\n runId,\n turn,\n messages: [...newMessages],\n });\n }\n\n async recordError(runId: string, error: unknown, newMessages: MessageType[]): Promise<void> {\n const memory = this.memory();\n if (memory === undefined || this.memoryContext === undefined) {\n return;\n }\n await memory.store.recordError?.({\n context: this.memoryContext,\n runId,\n error,\n messages: [...newMessages],\n });\n }\n\n private memory(): MemoryRegistration | undefined {\n return this.memoryContext === undefined ? undefined : this.agent.memory;\n }\n}\n","import type { Agent } from \"../../agent/agent\";\nimport type { Document, ToolDefinition } from \"../../completion/index\";\nimport { compact } from \"../compact\";\n\nexport async function fetchDynamicContext(\n agent: Agent,\n ragText: string | undefined,\n): Promise<Document[]> {\n if (ragText === undefined || ragText.length === 0 || agent.dynamicContexts.length === 0) {\n return [];\n }\n\n const documents: Document[] = [];\n for (const registration of agent.dynamicContexts) {\n const results = await registration.index.search({\n query: ragText,\n topK: registration.options.topK,\n threshold: registration.options.threshold,\n filter: registration.options.filter,\n });\n for (const result of results) {\n const formatted = registration.options.format?.(result);\n if (formatted !== undefined) {\n documents.push(formatted);\n } else {\n const metadata = formatMetadata(result.metadata);\n documents.push(\n compact({\n id: result.id,\n text:\n typeof result.document === \"string\"\n ? result.document\n : JSON.stringify(result.document, null, 2),\n additionalProps: metadata,\n }) as Document,\n );\n }\n }\n }\n return documents;\n}\n\nexport async function fetchToolDefinitions(\n agent: Agent,\n ragText: string | undefined,\n): Promise<ToolDefinition[]> {\n const staticDefinitions = await agent.toolSet.getToolDefinitions(ragText);\n if (ragText === undefined || ragText.length === 0 || agent.dynamicTools.length === 0) {\n return staticDefinitions;\n }\n\n const definitions = [...staticDefinitions];\n const names = new Set(staticDefinitions.map((definition) => definition.name));\n for (const registration of agent.dynamicTools) {\n const results = await registration.index.search({\n query: ragText,\n topK: registration.options.topK,\n threshold: registration.options.threshold,\n filter: registration.options.filter,\n });\n for (const result of results) {\n if (names.has(result.document.toolName)) {\n continue;\n }\n names.add(result.document.toolName);\n definitions.push(result.document.definition);\n }\n }\n return definitions;\n}\n\nfunction formatMetadata(\n metadata: Record<string, unknown> | undefined,\n): Record<string, string> | undefined {\n if (metadata === undefined) {\n return undefined;\n }\n\n return Object.fromEntries(Object.entries(metadata).map(([key, value]) => [key, String(value)]));\n}\n","import type {\n AssistantContent as AssistantContentType,\n CompletionResponse,\n CompletionStreamEvent,\n JsonValue,\n ReasoningContent,\n ToolCall,\n} from \"../../completion/index\";\nimport { Usage } from \"../../completion/index\";\nimport type { AgentDeltaEvent } from \"../../request/types\";\n\ntype ReasoningState = {\n id?: string;\n text: string;\n content?: ReasoningContent[];\n};\n\ntype PartialToolCall = {\n id: string;\n callId?: string;\n name: string;\n argumentsText: string;\n signature?: string;\n additionalParams?: JsonValue;\n};\n\ntype OrderedPartRef =\n | { type: \"text\"; key: string }\n | { type: \"reasoning\"; key: string }\n | { type: \"tool_call\"; key: string };\n\nexport class CompletionStreamAccumulator<RawResponse = unknown> {\n private orderedParts: OrderedPartRef[] = [];\n private textParts = new Map<string, string>();\n private reasoningByKey = new Map<string, ReasoningState>();\n private reasoningKeyById = new Map<string, string>();\n private toolCalls = new Map<string, PartialToolCall>();\n private finalResponse: CompletionResponse<RawResponse> | undefined;\n private messageId: string | undefined;\n private nextTextKey = 0;\n private nextReasoningKey = 0;\n\n accept(event: CompletionStreamEvent<RawResponse>): AgentDeltaEvent | undefined {\n if (event.type === \"text_delta\") {\n this.appendText(event.delta);\n return { type: \"text_delta\", delta: event.delta };\n }\n\n if (event.type === \"reasoning_delta\") {\n const reasoning = this.reasoningStateForEvent(event);\n this.appendReasoning(reasoning, event);\n return reasoningDeltaEvent(event);\n }\n\n if (event.type === \"tool_call_delta\") {\n const toolCall = this.toolCallStateForId(event.id);\n if (event.callId !== undefined) 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 return undefined;\n }\n\n if (event.type === \"tool_call\") {\n this.upsertToolCall(event.toolCall);\n return { type: \"tool_call\", toolCall: event.toolCall };\n }\n\n if (event.type === \"message_id\") {\n this.messageId = event.id;\n return undefined;\n }\n\n if (event.type === \"final\") {\n this.finalResponse = event.response;\n return undefined;\n }\n\n return undefined;\n }\n\n response(): CompletionResponse<RawResponse> {\n const accumulatedResponse = this.buildAccumulatedResponse();\n if (this.finalResponse !== undefined) {\n if (accumulatedResponse.choice.length === 0) {\n return this.withMessageIdFallback(this.finalResponse, accumulatedResponse);\n }\n return this.mergeFinalResponse(accumulatedResponse, this.finalResponse);\n }\n\n return accumulatedResponse;\n }\n\n private buildAccumulatedResponse(): CompletionResponse<RawResponse> {\n const choice: AssistantContentType[] = [];\n\n for (const part of this.orderedParts) {\n if (part.type === \"text\") {\n const text = this.textParts.get(part.key) ?? \"\";\n if (text.length > 0) {\n choice.push({ type: \"text\", text });\n }\n continue;\n }\n\n if (part.type === \"reasoning\") {\n const reasoning = this.reasoningByKey.get(part.key);\n if (reasoning !== undefined) {\n choice.push(reasoningContent(reasoning));\n }\n continue;\n }\n\n const toolCall = this.toolCalls.get(part.key);\n if (toolCall !== undefined) {\n choice.push(toolCallContent(toolCall));\n }\n }\n\n const response: CompletionResponse<RawResponse> = {\n choice,\n usage: Usage.empty(),\n rawResponse: undefined as RawResponse,\n };\n if (this.messageId !== undefined) {\n response.messageId = this.messageId;\n }\n return response;\n }\n\n private upsertToolCall(toolCall: ToolCall): void {\n if (!this.toolCalls.has(toolCall.id)) {\n this.orderedParts.push({ type: \"tool_call\", key: toolCall.id });\n }\n const partial: PartialToolCall = {\n id: toolCall.id,\n name: toolCall.function.name,\n argumentsText: JSON.stringify(toolCall.function.arguments ?? {}),\n };\n if (toolCall.callId !== undefined) {\n partial.callId = toolCall.callId;\n }\n if (toolCall.signature !== undefined) {\n partial.signature = toolCall.signature;\n }\n if (toolCall.additionalParams !== undefined) {\n partial.additionalParams = toolCall.additionalParams;\n }\n this.toolCalls.set(toolCall.id, partial);\n }\n\n private mergeFinalResponse(\n accumulatedResponse: CompletionResponse<RawResponse>,\n finalResponse: CompletionResponse<RawResponse>,\n ): CompletionResponse<RawResponse> {\n if (finalResponse.choice.length === 0) {\n return this.withMessageIdFallback(\n {\n ...accumulatedResponse,\n usage: finalResponse.usage,\n rawResponse: finalResponse.rawResponse,\n ...(finalResponse.messageId === undefined ? {} : { messageId: finalResponse.messageId }),\n },\n accumulatedResponse,\n );\n }\n\n const finalById = new Map<string, ToolCall>();\n const finalByCallId = new Map<string, ToolCall>();\n for (const content of finalResponse.choice) {\n if (content.type !== \"tool_call\") {\n continue;\n }\n finalById.set(content.id, content);\n if (content.callId !== undefined) {\n finalByCallId.set(content.callId, content);\n }\n }\n\n const matchedFinalToolCalls = new Set<ToolCall>();\n const choice = accumulatedResponse.choice.map((content) => {\n if (content.type !== \"tool_call\") {\n return content;\n }\n\n const finalToolCall =\n finalById.get(content.id) ??\n (content.callId === undefined ? undefined : finalByCallId.get(content.callId));\n if (finalToolCall === undefined) {\n return content;\n }\n\n matchedFinalToolCalls.add(finalToolCall);\n return mergeFinalToolCall(content, finalToolCall);\n });\n\n for (const content of finalResponse.choice) {\n if (content.type !== \"tool_call\") {\n continue;\n }\n if (!matchedFinalToolCalls.has(content)) {\n choice.push(content);\n }\n }\n\n return this.withMessageIdFallback({ ...finalResponse, choice }, accumulatedResponse);\n }\n\n private appendText(delta: string): void {\n const lastPart = this.orderedParts.at(-1);\n const key = lastPart?.type === \"text\" ? lastPart.key : this.createTextKey();\n if (lastPart?.type !== \"text\") {\n this.orderedParts.push({ type: \"text\", key });\n }\n this.textParts.set(key, `${this.textParts.get(key) ?? \"\"}${delta}`);\n }\n\n private reasoningStateForEvent(\n event: Extract<CompletionStreamEvent<RawResponse>, { type: \"reasoning_delta\" }>,\n ): ReasoningState {\n if (event.id !== undefined) {\n const existingKey = this.reasoningKeyById.get(event.id);\n if (existingKey !== undefined) {\n const existing = this.reasoningByKey.get(existingKey);\n if (existing !== undefined) {\n return existing;\n }\n }\n\n const key = this.createReasoningKey();\n const reasoning: ReasoningState = { id: event.id, text: \"\" };\n this.reasoningKeyById.set(event.id, key);\n this.reasoningByKey.set(key, reasoning);\n this.orderedParts.push({ type: \"reasoning\", key });\n return reasoning;\n }\n\n const lastPart = this.orderedParts.at(-1);\n if (lastPart?.type === \"reasoning\") {\n const lastReasoning = this.reasoningByKey.get(lastPart.key);\n if (lastReasoning !== undefined && lastReasoning.id === undefined) {\n return lastReasoning;\n }\n }\n\n const key = this.createReasoningKey();\n const reasoning: ReasoningState = { text: \"\" };\n this.reasoningByKey.set(key, reasoning);\n this.orderedParts.push({ type: \"reasoning\", key });\n return reasoning;\n }\n\n private toolCallStateForId(id: string): PartialToolCall {\n const existing = this.toolCalls.get(id);\n if (existing !== undefined) {\n return existing;\n }\n\n const toolCall: PartialToolCall = {\n id,\n name: \"\",\n argumentsText: \"\",\n };\n this.toolCalls.set(id, toolCall);\n this.orderedParts.push({ type: \"tool_call\", key: id });\n return toolCall;\n }\n\n private withMessageIdFallback(\n response: CompletionResponse<RawResponse>,\n accumulatedResponse: CompletionResponse<RawResponse>,\n ): CompletionResponse<RawResponse> {\n if (response.messageId !== undefined || accumulatedResponse.messageId === undefined) {\n return response;\n }\n return { ...response, messageId: accumulatedResponse.messageId };\n }\n\n private createTextKey(): string {\n this.nextTextKey += 1;\n return `text_${this.nextTextKey.toString()}`;\n }\n\n private createReasoningKey(): string {\n this.nextReasoningKey += 1;\n return `reasoning_${this.nextReasoningKey.toString()}`;\n }\n\n private appendReasoning(\n reasoning: ReasoningState,\n event: Extract<CompletionStreamEvent<RawResponse>, { type: \"reasoning_delta\" }>,\n ): void {\n const contentType = event.contentType ?? \"text\";\n if (contentType === \"text\" || contentType === \"summary\") {\n reasoning.text += event.delta;\n }\n\n if (event.contentType === undefined && event.signature === undefined) {\n return;\n }\n\n reasoning.content ??= [];\n const last = reasoning.content.at(-1);\n if (contentType === \"text\") {\n if (last?.type === \"text\") {\n last.text += event.delta;\n if (event.signature !== undefined) {\n last.signature = event.signature;\n }\n } else {\n reasoning.content.push(\n event.signature === undefined\n ? { type: \"text\", text: event.delta }\n : { type: \"text\", text: event.delta, signature: event.signature },\n );\n }\n return;\n }\n\n if (contentType === \"summary\") {\n if (last?.type === \"summary\") {\n last.text += event.delta;\n } else {\n reasoning.content.push({ type: \"summary\", text: event.delta });\n }\n return;\n }\n\n if (contentType === \"encrypted\") {\n reasoning.content.push({ type: \"encrypted\", data: event.delta });\n return;\n }\n\n reasoning.content.push({ type: \"redacted\", data: event.delta });\n }\n}\n\nfunction reasoningContent(reasoning: ReasoningState): AssistantContentType {\n const content =\n reasoning.content === undefined\n ? { type: \"reasoning\" as const, text: reasoning.text }\n : { type: \"reasoning\" as const, text: reasoning.text, content: reasoning.content };\n return reasoning.id === undefined ? content : { ...content, id: reasoning.id };\n}\n\nfunction toolCallContent(toolCall: PartialToolCall): ToolCall {\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 if (toolCall.additionalParams !== undefined) {\n content.additionalParams = toolCall.additionalParams;\n }\n return content;\n}\n\nfunction mergeFinalToolCall(accumulated: ToolCall, finalToolCall: ToolCall): ToolCall {\n const argumentsValue = isEmptyToolArguments(finalToolCall.function.arguments)\n ? accumulated.function.arguments\n : finalToolCall.function.arguments;\n return {\n ...accumulated,\n ...finalToolCall,\n function: {\n ...accumulated.function,\n ...finalToolCall.function,\n arguments: argumentsValue,\n },\n };\n}\n\nfunction reasoningDeltaEvent(\n event: Extract<CompletionStreamEvent, { type: \"reasoning_delta\" }>,\n): AgentDeltaEvent {\n const mapped: AgentDeltaEvent = { type: \"reasoning_delta\", delta: event.delta };\n if (event.id !== undefined) mapped.id = event.id;\n if (event.contentType !== undefined) mapped.contentType = event.contentType;\n if (event.signature !== undefined) mapped.signature = event.signature;\n return mapped;\n}\n\nfunction isEmptyToolArguments(value: unknown): boolean {\n if (value === undefined || value === null) {\n return true;\n }\n if (typeof value === \"string\") {\n return value.trim().length === 0;\n }\n if (Array.isArray(value)) {\n return value.length === 0;\n }\n if (typeof value === \"object\") {\n return Object.values(value).every((item) => item === undefined);\n }\n return false;\n}\n\nfunction parseJsonValue(text: string): JsonValue {\n if (text.trim().length === 0) {\n return {};\n }\n try {\n return JSON.parse(text) as JsonValue;\n } catch {\n return text;\n }\n}\n","import type { AgentDeltaEvent, AgentStreamEvent } from \"../../request/types\";\n\nexport function addTurn(turn: number, event: AgentDeltaEvent): AgentStreamEvent {\n if (event.type === \"text_delta\") {\n return { type: \"text_delta\", turn, delta: event.delta };\n }\n if (event.type === \"reasoning_delta\") {\n const mapped: AgentStreamEvent = { type: \"reasoning_delta\", turn, delta: event.delta };\n if (event.id !== undefined) mapped.id = event.id;\n if (event.contentType !== undefined) mapped.contentType = event.contentType;\n if (event.signature !== undefined) mapped.signature = event.signature;\n return mapped;\n }\n return { type: \"tool_call\", turn, toolCall: event.toolCall };\n}\n\nexport function isGenerationDeltaEvent(type: string): boolean {\n return (\n type === \"text_delta\" ||\n type === \"reasoning_delta\" ||\n type === \"tool_call_delta\" ||\n type === \"tool_call\"\n );\n}\n","import type { Agent } from \"../../agent/agent\";\nimport type {\n JsonObject,\n ToolCall,\n ToolDefinition,\n ToolResult,\n ToolResultContent,\n} from \"../../completion\";\nimport { ToolContent } from \"../../completion\";\nimport type { PromptHook, ToolApprovalRequestOptions, ToolHookArgs } from \"../../hooks\";\nimport { runControl, toolCallControl } from \"../../hooks\";\nimport type { ActiveAgentRunObservers, ActiveToolObservers } from \"../../observability/group\";\nimport { ToolApprovalRequiredError } from \"../../request/errors\";\nimport type { AgentChildStreamEvent } from \"../../request/types\";\nimport type {\n AnyTool,\n NormalizedToolOutput,\n ToolApprovalContext,\n ToolApprovalDecision,\n ToolApprovalPolicy,\n ToolApprovalRequest,\n ToolApprovalsOptions,\n ToolCallStreamEvent,\n} from \"../../tool\";\nimport { parseToolArgs, toolResultContentToText } from \"../../tool\";\nimport type {\n AgentMiddleware,\n ToolOutputMiddlewareArgs,\n ToolOutputMiddlewareResult,\n} from \"../../tool/middleware\";\nimport { compact } from \"../compact\";\nimport { mapWithConcurrency } from \"../concurrency\";\n\nconst MCP_TOOL_METADATA_KEY = Symbol.for(\"anvia.mcp.tool.metadata\");\n\nexport type ToolResultEventPayload = {\n type: \"tool_result\";\n toolName: string;\n toolCallId?: string;\n internalCallId: string;\n args: string;\n result: string;\n structuredResult?: ToolResultContent[] | undefined;\n};\n\nexport type AgentToolEventPayload = {\n type: \"agent_tool_event\";\n toolName: string;\n toolCallId?: string;\n internalCallId: string;\n agentId: string;\n agentName?: string;\n event: AgentChildStreamEvent;\n};\n\nexport type ToolExecutionEventPayload = ToolResultEventPayload | AgentToolEventPayload;\n\nexport type ToolExecutionObservation = {\n turn: number;\n runObservers: ActiveAgentRunObservers;\n toolDefinitions?: ToolDefinition[];\n};\n\nexport type ToolExecutionRunContext = {\n runId: string;\n sessionId?: string | undefined;\n metadata?: JsonObject | undefined;\n};\n\nexport class ToolCallExecutor {\n constructor(\n private readonly agent: Agent,\n private readonly activeHook: PromptHook | undefined,\n private readonly approvals: ToolApprovalsOptions | undefined,\n private readonly runContext: ToolExecutionRunContext,\n private readonly concurrency: number,\n private readonly requestMiddlewares: AgentMiddleware[],\n private readonly cancel: (reason: string) => Error,\n ) {}\n\n async execute(\n toolCalls: ToolCall[],\n onResult?: (result: ToolResultEventPayload) => void,\n onStreamEvent?: (event: AgentToolEventPayload) => void,\n observation?: ToolExecutionObservation,\n ): Promise<ToolResult[]> {\n return mapWithConcurrency(toolCalls, this.concurrency, async (toolCall) => {\n const args = JSON.stringify(toolCall.function.arguments ?? {});\n const internalCallId = globalThis.crypto.randomUUID();\n const hookArgs: ToolHookArgs = {\n toolName: toolCall.function.name,\n internalCallId,\n args,\n };\n if (toolCall.callId !== undefined) {\n hookArgs.toolCallId = toolCall.callId;\n }\n const tool = this.agent.getTool(toolCall.function.name);\n const toolDefinition = observation?.toolDefinitions?.find(\n (definition) => definition.name === toolCall.function.name,\n );\n const toolMetadata = toolTraceMetadata(tool);\n\n const toolObservers = await observation?.runObservers.startTool(\n compact({\n turn: observation.turn,\n toolCall,\n toolName: toolCall.function.name,\n internalCallId,\n args,\n toolCallId: toolCall.callId,\n toolDefinition,\n toolMetadata,\n }),\n );\n\n let output: NormalizedToolOutput;\n let skipped = false;\n let effectiveArgs = args;\n\n const callAction = await this.activeHook?.onToolCall?.({\n ...hookArgs,\n tool: toolCallControl,\n });\n if (callAction?.type === \"terminate\") {\n await recordToolError(\n toolObservers,\n observation?.turn,\n toolCall,\n internalCallId,\n effectiveArgs,\n callAction.reason,\n );\n throw this.cancel(callAction.reason);\n }\n if (callAction?.type === \"skip\") {\n output = callAction.reason;\n skipped = true;\n } else {\n let approvalDecision: { approved: true } | { approved: false; result: string };\n try {\n effectiveArgs = await this.runToolInputMiddlewares({\n ...hookArgs,\n turn: observation?.turn ?? 0,\n originalArgs: args,\n });\n hookArgs.args = effectiveArgs;\n\n approvalDecision =\n callAction?.type === \"approval_request\"\n ? await this.requestApproval(tool, hookArgs, callAction)\n : ((await this.evaluateToolApproval(tool, hookArgs)) ?? { approved: true });\n if (!approvalDecision.approved) {\n output = approvalDecision.result;\n skipped = true;\n } else {\n output = await this.runApprovedToolCall(\n toolCall,\n hookArgs,\n effectiveArgs,\n args,\n toolObservers,\n observation,\n onStreamEvent,\n false,\n );\n effectiveArgs = hookArgs.args;\n }\n } catch (error) {\n await recordToolError(\n toolObservers,\n observation?.turn,\n toolCall,\n internalCallId,\n effectiveArgs,\n error,\n );\n throw error;\n }\n }\n\n let result = toolOutputToText(output);\n let structuredResult = toolOutputToStructuredResult(output);\n if (this.agent.shouldApplyToolMiddleware(toolCall.function.name)) {\n const middlewareReplacement = await this.runToolResultMiddlewares({\n ...hookArgs,\n args: effectiveArgs,\n result,\n originalResult: result,\n structuredResult,\n originalStructuredResult: structuredResult,\n turn: observation?.turn ?? 0,\n });\n if (middlewareReplacement !== undefined) {\n output = middlewareReplacement;\n result = toolOutputToText(middlewareReplacement);\n structuredResult = toolOutputToStructuredResult(middlewareReplacement);\n }\n }\n\n const resultAction = await this.activeHook?.onToolResult?.({\n ...hookArgs,\n args: effectiveArgs,\n result,\n structuredResult,\n run: runControl,\n });\n await toolObservers?.end({\n turn: observation?.turn ?? 0,\n toolCall,\n toolName: toolCall.function.name,\n internalCallId,\n args: effectiveArgs,\n result,\n structuredResult,\n skipped,\n toolCallId: toolCall.callId,\n });\n if (resultAction?.type === \"terminate\") {\n throw this.cancel(resultAction.reason);\n }\n\n const resultPayload: ToolResultEventPayload = {\n type: \"tool_result\",\n toolName: toolCall.function.name,\n internalCallId,\n args: effectiveArgs,\n result,\n structuredResult,\n };\n if (toolCall.callId !== undefined) {\n resultPayload.toolCallId = toolCall.callId;\n }\n onResult?.(resultPayload);\n return ToolContent.toolResult(toolCall.id, output, {\n callId: toolCall.callId,\n toolName: toolCall.function.name,\n });\n });\n }\n\n private async runApprovedToolCall(\n toolCall: ToolCall,\n hookArgs: ToolHookArgs,\n effectiveArgs: string,\n originalArgs: string,\n toolObservers: ActiveToolObservers | undefined,\n observation: ToolExecutionObservation | undefined,\n onStreamEvent?: (event: AgentToolEventPayload) => void,\n applyInputMiddleware = true,\n ): Promise<NormalizedToolOutput> {\n const middlewareArgs = applyInputMiddleware\n ? await this.runToolInputMiddlewares({\n ...hookArgs,\n args: effectiveArgs,\n turn: observation?.turn ?? 0,\n originalArgs,\n })\n : effectiveArgs;\n hookArgs.args = middlewareArgs;\n try {\n return await this.agent.callTool(toolCall.function.name, middlewareArgs, {\n emitStreamEvent: async (event) => {\n await toolObservers?.streamEvent(\n compact({\n turn: observation?.turn ?? 0,\n toolCall,\n toolName: toolCall.function.name,\n internalCallId: hookArgs.internalCallId,\n args: middlewareArgs,\n toolCallId: toolCall.callId,\n event,\n }),\n );\n const payload = agentToolEventPayload(toolCall, hookArgs.internalCallId, event);\n if (payload !== undefined) {\n onStreamEvent?.(payload);\n }\n },\n });\n } catch (error) {\n const errorAction = await this.activeHook?.onToolError?.({\n ...hookArgs,\n args: middlewareArgs,\n error,\n run: runControl,\n });\n await toolObservers?.error({\n turn: observation?.turn ?? 0,\n toolCall,\n toolName: toolCall.function.name,\n internalCallId: hookArgs.internalCallId,\n args: middlewareArgs,\n ...(toolCall.callId !== undefined && { toolCallId: toolCall.callId }),\n error,\n });\n if (errorAction?.type === \"terminate\") {\n throw this.cancel(errorAction.reason);\n }\n return error instanceof Error ? error.toString() : String(error);\n }\n }\n\n private async runToolResultMiddlewares(\n args: ToolOutputMiddlewareArgs,\n ): Promise<NormalizedToolOutput | undefined> {\n let result = args.result;\n let structuredResult = args.structuredResult;\n let replaced = false;\n for (const middleware of this.activeMiddlewares()) {\n const outputReplacement = await middleware.onToolOutput?.({\n ...args,\n result,\n structuredResult,\n });\n if (outputReplacement !== undefined) {\n const normalized = normalizeToolOutputMiddlewareResult(outputReplacement);\n if (normalized.result !== undefined) {\n result = normalized.result;\n structuredResult = undefined;\n }\n if (normalized.structuredResult !== undefined) {\n structuredResult = normalized.structuredResult;\n result = toolResultContentToText(normalized.structuredResult);\n }\n replaced = true;\n }\n const legacyReplacement = await middleware.onResult?.({\n ...args,\n result,\n structuredResult,\n });\n if (legacyReplacement !== undefined) {\n result = legacyReplacement;\n structuredResult = undefined;\n replaced = true;\n }\n }\n return replaced ? (structuredResult ?? result) : undefined;\n }\n\n private async runToolInputMiddlewares(\n args: ToolHookArgs & { turn: number; originalArgs: string },\n ): Promise<string> {\n let current = args.args;\n for (const middleware of this.activeMiddlewares()) {\n const replacement = await middleware.onToolInput?.({\n ...args,\n args: current,\n });\n if (replacement?.args !== undefined) {\n current =\n typeof replacement.args === \"string\"\n ? replacement.args\n : JSON.stringify(replacement.args);\n }\n }\n return current;\n }\n\n private activeMiddlewares(): AgentMiddleware[] {\n return [...this.agent.middlewares, ...this.requestMiddlewares];\n }\n\n private async evaluateToolApproval(\n tool: AnyTool | undefined,\n hookArgs: ToolHookArgs,\n ): Promise<{ approved: true } | { approved: false; result: string } | undefined> {\n if (tool?.approval === undefined) {\n return undefined;\n }\n const policy = tool.approval as ToolApprovalPolicy<unknown>;\n const context = approvalContext(tool, hookArgs, this.agent, this.runContext);\n const required = await policy.when(context);\n if (!required) {\n return { approved: true };\n }\n\n const reason = await resolveApprovalText(policy.reason, context);\n const rejectMessage = await resolveApprovalText(policy.rejectMessage, context);\n return this.requestApproval(tool, hookArgs, compact({ reason, rejectMessage }));\n }\n\n private async requestApproval(\n tool: AnyTool | undefined,\n hookArgs: ToolHookArgs,\n options: ToolApprovalRequestOptions,\n ): Promise<{ approved: true } | { approved: false; result: string }> {\n const request = compact({\n ...approvalContext(tool, hookArgs, this.agent, this.runContext),\n reason: options.reason,\n rejectMessage: options.rejectMessage,\n }) as ToolApprovalRequest;\n if (this.approvals === undefined) {\n throw new ToolApprovalRequiredError(request);\n }\n\n const decision = normalizeApprovalDecision(await this.approvals.handler(request));\n if (decision.approved) {\n return { approved: true };\n }\n return {\n approved: false,\n result:\n decision.rejectMessage ??\n decision.reason ??\n request.rejectMessage ??\n \"Tool approval was rejected.\",\n };\n }\n}\n\nfunction approvalContext(\n tool: AnyTool | undefined,\n hookArgs: ToolHookArgs,\n agent: Agent,\n run: ToolExecutionRunContext,\n): ToolApprovalContext {\n const rawParsedArgs = parseToolArgs(hookArgs.args);\n const parsedArgs = tool?.parseApprovalArgs?.(rawParsedArgs) ?? rawParsedArgs;\n return compact({\n toolName: hookArgs.toolName,\n args: parsedArgs,\n rawArgs: hookArgs.args,\n toolCallId: hookArgs.toolCallId,\n internalCallId: hookArgs.internalCallId,\n run: compact({\n agentId: agent.id,\n runId: run.runId,\n sessionId: run.sessionId,\n metadata: run.metadata,\n }),\n }) as ToolApprovalContext;\n}\n\nfunction normalizeApprovalDecision(decision: ToolApprovalDecision): {\n approved: boolean;\n reason?: string;\n rejectMessage?: string;\n} {\n if (typeof decision === \"boolean\") {\n return { approved: decision };\n }\n return decision;\n}\n\nasync function resolveApprovalText<Args>(\n value: string | ((ctx: ToolApprovalContext<Args>) => string | Promise<string>) | undefined,\n context: ToolApprovalContext<Args>,\n): Promise<string | undefined> {\n return typeof value === \"function\" ? value(context as ToolApprovalContext<Args>) : value;\n}\n\nfunction normalizeToolOutputMiddlewareResult(result: ToolOutputMiddlewareResult): {\n result?: string | undefined;\n structuredResult?: ToolResultContent[] | undefined;\n} {\n if (typeof result === \"string\") {\n return { result };\n }\n return result ?? {};\n}\n\nfunction toolTraceMetadata(tool: AnyTool | undefined): JsonObject | undefined {\n if (tool === undefined) {\n return undefined;\n }\n const metadata = (tool as { [MCP_TOOL_METADATA_KEY]?: unknown })[MCP_TOOL_METADATA_KEY];\n const mcpMetadata =\n typeof metadata === \"object\" && metadata !== null\n ? (metadata as { serverName?: unknown })\n : undefined;\n return {\n approvalRequired: tool.approval !== undefined,\n ...(typeof mcpMetadata?.serverName === \"string\" && mcpMetadata.serverName.length > 0\n ? { mcpServerName: mcpMetadata.serverName }\n : {}),\n };\n}\n\nasync function recordToolError(\n toolObservers: ActiveToolObservers | undefined,\n turn: number | undefined,\n toolCall: ToolCall,\n internalCallId: string,\n args: string,\n error: unknown,\n): Promise<void> {\n await toolObservers?.error({\n turn: turn ?? 0,\n toolCall,\n toolName: toolCall.function.name,\n internalCallId,\n args,\n error,\n toolCallId: toolCall.callId,\n });\n}\n\nfunction toolOutputToText(output: NormalizedToolOutput): string {\n return typeof output === \"string\" ? output : toolResultContentToText(output);\n}\n\nfunction toolOutputToStructuredResult(\n output: NormalizedToolOutput,\n): ToolResultContent[] | undefined {\n return typeof output === \"string\" ? undefined : output;\n}\n\nfunction agentToolEventPayload(\n toolCall: ToolCall,\n internalCallId: string,\n event: ToolCallStreamEvent,\n): AgentToolEventPayload | undefined {\n if (typeof event.agentId !== \"string\" || event.agentId.length === 0) {\n return undefined;\n }\n return compact({\n type: \"agent_tool_event\" as const,\n toolName: toolCall.function.name,\n toolCallId: toolCall.callId,\n internalCallId,\n agentId: event.agentId,\n agentName: event.agentName,\n event: event.event as AgentChildStreamEvent,\n });\n}\n","import type { Message as MessageType } from \"../completion/index\";\n\nexport function extractRagText(message: MessageType): string | undefined {\n if (message.role === \"user\") {\n return message.content.flatMap((item) => (item.type === \"text\" ? [item.text] : [])).join(\"\\n\");\n }\n\n if (message.role === \"tool\") {\n return message.content\n .flatMap((item) => item.content.flatMap((part) => (part.type === \"text\" ? [part.text] : [])))\n .join(\"\\n\");\n }\n\n return undefined;\n}\n","import type {\n AgentGenerationEndArgs,\n AgentGenerationErrorArgs,\n AgentGenerationObserver,\n AgentGenerationStartArgs,\n AgentGenerationUpdateArgs,\n AgentObserverRegistration,\n AgentRunEndArgs,\n AgentRunErrorArgs,\n AgentRunEventArgs,\n AgentRunObserver,\n AgentRunStartArgs,\n AgentToolEndArgs,\n AgentToolErrorArgs,\n AgentToolObserver,\n AgentToolStartArgs,\n AgentToolStreamEventArgs,\n AgentTraceInfo,\n} from \"./types\";\n\nexport async function startAgentRunObservers(\n registrations: AgentObserverRegistration[],\n args: AgentRunStartArgs,\n failOnObserverError: boolean,\n): Promise<ActiveAgentRunObservers> {\n const runObservers: AgentRunObserver[] = [];\n for (const registration of registrations) {\n try {\n const runObserver = await registration.observer.startRun(args);\n if (runObserver !== undefined) {\n runObservers.push(runObserver);\n }\n } catch (error) {\n if (failOnObserverError || registration.failOnObserverError === true) {\n throw error;\n }\n }\n }\n\n return new ActiveAgentRunObservers(runObservers, failOnObserverError);\n}\n\nexport class ActiveAgentRunObservers {\n readonly trace: AgentTraceInfo | undefined;\n\n constructor(\n private readonly runObservers: AgentRunObserver[],\n private readonly failOnObserverError: boolean,\n ) {\n this.trace = runObservers.find((observer) => observer.trace !== undefined)?.trace;\n }\n\n async startGeneration(args: AgentGenerationStartArgs): Promise<ActiveGenerationObservers> {\n const generationObservers: AgentGenerationObserver[] = [];\n for (const runObserver of this.runObservers) {\n if (runObserver.startGeneration === undefined) {\n continue;\n }\n try {\n const generationObserver = await runObserver.startGeneration(args);\n if (generationObserver !== undefined) {\n generationObservers.push(generationObserver);\n }\n } catch (error) {\n this.handleError(error);\n }\n }\n return new ActiveGenerationObservers(generationObservers, this.failOnObserverError);\n }\n\n async startTool(args: AgentToolStartArgs): Promise<ActiveToolObservers> {\n const toolObservers: AgentToolObserver[] = [];\n for (const runObserver of this.runObservers) {\n if (runObserver.startTool === undefined) {\n continue;\n }\n try {\n const toolObserver = await runObserver.startTool(args);\n if (toolObserver !== undefined) {\n toolObservers.push(toolObserver);\n }\n } catch (error) {\n this.handleError(error);\n }\n }\n return new ActiveToolObservers(toolObservers, this.failOnObserverError);\n }\n\n async end(args: AgentRunEndArgs): Promise<void> {\n for (const runObserver of this.runObservers) {\n try {\n await runObserver.end(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n async error(args: AgentRunErrorArgs): Promise<void> {\n for (const runObserver of this.runObservers) {\n if (runObserver.error === undefined) {\n continue;\n }\n try {\n await runObserver.error(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n async event(args: AgentRunEventArgs): Promise<void> {\n for (const runObserver of this.runObservers) {\n if (runObserver.event === undefined) {\n continue;\n }\n try {\n await runObserver.event(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n private handleError(error: unknown): void {\n if (this.failOnObserverError) {\n throw error;\n }\n }\n}\n\nexport class ActiveGenerationObservers {\n constructor(\n private readonly generationObservers: AgentGenerationObserver[],\n private readonly failOnObserverError: boolean,\n ) {}\n\n async end(args: AgentGenerationEndArgs): Promise<void> {\n for (const observer of this.generationObservers) {\n try {\n await observer.end(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n async error(args: AgentGenerationErrorArgs): Promise<void> {\n for (const observer of this.generationObservers) {\n if (observer.error === undefined) {\n continue;\n }\n try {\n await observer.error(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n async update(args: AgentGenerationUpdateArgs): Promise<void> {\n for (const observer of this.generationObservers) {\n if (observer.update === undefined) {\n continue;\n }\n try {\n await observer.update(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n private handleError(error: unknown): void {\n if (this.failOnObserverError) {\n throw error;\n }\n }\n}\n\nexport class ActiveToolObservers {\n constructor(\n private readonly toolObservers: AgentToolObserver[],\n private readonly failOnObserverError: boolean,\n ) {}\n\n async streamEvent(args: AgentToolStreamEventArgs): Promise<void> {\n for (const observer of this.toolObservers) {\n if (observer.streamEvent === undefined) {\n continue;\n }\n try {\n await observer.streamEvent(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n async end(args: AgentToolEndArgs): Promise<void> {\n for (const observer of this.toolObservers) {\n try {\n await observer.end(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n async error(args: AgentToolErrorArgs): Promise<void> {\n for (const observer of this.toolObservers) {\n if (observer.error === undefined) {\n continue;\n }\n try {\n await observer.error(args);\n } catch (error) {\n this.handleError(error);\n }\n }\n }\n\n private handleError(error: unknown): void {\n if (this.failOnObserverError) {\n throw error;\n }\n }\n}\n","import type { Agent } from \"../agent/agent\";\nimport { isStreamingCompletionModel } from \"../completion/create-completion\";\nimport {\n AssistantContent,\n assertCompletionRequestSupported,\n type CompletionModel,\n CompletionRequestBuilder,\n type CompletionResponse,\n type JsonObject,\n type JsonValue,\n Message,\n type Message as MessageType,\n type ToolCall,\n type ToolDefinition,\n type ToolResult,\n textFromAssistantContent,\n Usage,\n} from \"../completion/index\";\nimport {\n appendGuardrailPolicies,\n type GuardrailDecisionRecord,\n type GuardrailPolicy,\n type GuardrailPolicyInput,\n type GuardrailRunContext,\n hasEnforcedOutputGuardrails,\n runInputGuardrails,\n runOutputGuardrails,\n} from \"../guardrails\";\nimport type { PromptHook } from \"../hooks\";\nimport { runControl } from \"../hooks\";\nimport { createAsyncQueue } from \"../internal/async-queue\";\nimport { compact } from \"../internal/compact\";\nimport { PromptRequestMemory } from \"../internal/prompt-runtime/memory\";\nimport { fetchDynamicContext, fetchToolDefinitions } from \"../internal/prompt-runtime/retrieval\";\nimport { CompletionStreamAccumulator } from \"../internal/prompt-runtime/stream-accumulator\";\nimport { addTurn, isGenerationDeltaEvent } from \"../internal/prompt-runtime/stream-events\";\nimport {\n type AgentToolEventPayload,\n ToolCallExecutor,\n type ToolExecutionEventPayload,\n type ToolResultEventPayload,\n} from \"../internal/prompt-runtime/tool-execution\";\nimport { extractRagText } from \"../internal/rag-text\";\nimport type { MemoryContext } from \"../memory/types\";\nimport { type ActiveAgentRunObservers, startAgentRunObservers } from \"../observability/group\";\nimport type { AgentTraceOptions } from \"../observability/types\";\nimport { toReadableStream } from \"../streaming\";\nimport type { ToolApprovalsOptions } from \"../tool\";\nimport type { AgentMiddleware, ToolMiddleware } from \"../tool/middleware\";\nimport { MaxTurnsError, PromptCancelledError } from \"./errors\";\nimport type { AgentStreamEvent, PromptResponse } from \"./types\";\n\nexport class PromptRequest<M extends CompletionModel = CompletionModel> {\n private chatHistory: MessageType[];\n private maxTurnCount: number;\n private activeHook: PromptHook | undefined;\n private approvalOptions: ToolApprovalsOptions | undefined;\n private guardrailPolicies: GuardrailPolicy[];\n private guardrailDecisions: GuardrailDecisionRecord[] = [];\n private concurrency = 1;\n private traceOptions: AgentTraceOptions | undefined;\n private requestMiddlewares: AgentMiddleware[] = [];\n private readonly steeringMessages: MessageType[] = [];\n private runState: \"idle\" | \"running\" | \"completed\" | \"errored\" | \"cancelled\" = \"idle\";\n private readonly memoryRecorder: PromptRequestMemory;\n\n private constructor(\n private readonly agent: Agent<M>,\n private promptMessage: MessageType,\n initialHistory: MessageType[] = [],\n private readonly memoryContext: MemoryContext | undefined = undefined,\n ) {\n this.chatHistory = initialHistory;\n this.maxTurnCount = agent.defaultMaxTurns ?? 0;\n this.activeHook = agent.hook;\n this.approvalOptions = agent.approvals;\n this.guardrailPolicies = [...agent.guardrails];\n this.memoryRecorder = new PromptRequestMemory(agent, memoryContext, initialHistory);\n }\n\n static fromAgent<M extends CompletionModel>(\n agent: Agent<M>,\n prompt: string | MessageType | MessageType[],\n options: { memoryContext?: MemoryContext | undefined } = {},\n ): PromptRequest<M> {\n const normalized = normalizePromptInput(prompt);\n return new PromptRequest(agent, normalized.prompt, normalized.history, options.memoryContext);\n }\n\n maxTurns(maxTurns: number): this {\n this.maxTurnCount = maxTurns;\n return this;\n }\n\n withHook(hook: PromptHook): this {\n this.activeHook = hook;\n return this;\n }\n\n approvals(options: ToolApprovalsOptions): this {\n this.approvalOptions = options;\n return this;\n }\n\n guardrails(policies: GuardrailPolicyInput): this {\n this.guardrailPolicies = appendGuardrailPolicies(this.guardrailPolicies, policies);\n return this;\n }\n\n /**\n * @deprecated Use `withHook` instead.\n */\n requestHook(hook: PromptHook): this {\n return this.withHook(hook);\n }\n\n withToolConcurrency(concurrency: number): this {\n this.concurrency = Math.max(1, concurrency);\n return this;\n }\n\n withMiddleware(middleware: AgentMiddleware): this {\n this.requestMiddlewares.push(middleware);\n return this;\n }\n\n withMiddlewares(middlewares: AgentMiddleware[]): this {\n this.requestMiddlewares.push(...middlewares);\n return this;\n }\n\n /**\n * @deprecated Use `withMiddleware` instead.\n */\n withToolMiddleware(middleware: ToolMiddleware): this {\n return this.withMiddleware(middleware);\n }\n\n /**\n * @deprecated Use `withMiddlewares` instead.\n */\n withToolMiddlewares(middlewares: ToolMiddleware[]): this {\n return this.withMiddlewares(middlewares);\n }\n\n withTrace(trace: AgentTraceOptions): this {\n this.traceOptions = trace;\n return this;\n }\n\n steer(input: string | MessageType | MessageType[]): boolean {\n if (this.isTerminal()) {\n return false;\n }\n\n this.steeringMessages.push(...normalizeSteeringInput(input));\n return true;\n }\n\n async send(): Promise<PromptResponse> {\n this.startRun();\n const runId = globalThis.crypto.randomUUID();\n let usage = Usage.empty();\n let currentTurns = 0;\n let lastPrompt = this.promptMessage;\n let newMessages: MessageType[] = [this.promptMessage];\n const runObservers = await this.startRunObservers();\n\n try {\n const inputResult = await runInputGuardrails(this.guardrailPolicies, {\n prompt: this.promptMessage,\n history: this.chatHistory,\n inputText: textFromMessage(this.promptMessage),\n run: this.guardrailRunContext(runId),\n });\n for (const decision of inputResult.decisions) {\n await this.recordGuardrailDecision(decision, runObservers);\n }\n this.promptMessage = inputResult.prompt;\n if (inputResult.blocked) {\n const output = inputResult.message ?? \"The request was blocked by a guardrail.\";\n const result: PromptResponse = {\n output,\n usage: Usage.empty(),\n messages: [this.promptMessage, Message.assistant(output)],\n guardrails: [...this.guardrailDecisions],\n };\n await runObservers.end(result);\n this.runState = \"completed\";\n return result;\n }\n\n newMessages = [this.promptMessage];\n this.chatHistory = await this.memoryRecorder.prepareRun(runId, newMessages);\n const pendingTurnMessages = this.memoryRecorder.pendingTurnMessages(newMessages);\n await this.runRunStartHook(newMessages);\n while (currentTurns <= this.maxTurnCount + 1) {\n const prompt = newMessages.at(-1);\n if (prompt === undefined) {\n throw new Error(\"PromptRequest requires at least one message\");\n }\n\n lastPrompt = prompt;\n currentTurns += 1;\n\n const historyForRequest = [...this.chatHistory, ...newMessages.slice(0, -1)];\n await this.runTurnStartHook(currentTurns, prompt, historyForRequest, newMessages);\n await this.runCompletionCallHook(prompt, historyForRequest, newMessages);\n\n const ragText = extractRagText(prompt);\n const dynamicContext = await fetchDynamicContext(this.agent, ragText);\n const toolDefs = await fetchToolDefinitions(this.agent, ragText);\n let request = new CompletionRequestBuilder(this.agent.model, prompt)\n .instructions(this.agent.instructions)\n .messages(historyForRequest)\n .documents([...this.agent.staticContext, ...dynamicContext])\n .tools(toolDefs)\n .temperature(this.agent.temperature)\n .maxTokens(this.agent.maxTokens)\n .additionalParams(this.agent.additionalParams)\n .toolChoice(this.agent.toolChoice)\n .outputSchema(this.agent.outputSchema)\n .build();\n request = (await this.runCompletionRequestMiddlewares(\n request,\n currentTurns,\n )) as typeof request;\n\n let response: CompletionResponse;\n try {\n response = await this.runCompletion(request, currentTurns, runObservers);\n } catch (error) {\n await this.runCompletionErrorHook(prompt, error, newMessages);\n throw error;\n }\n response = await this.runCompletionResponseMiddlewares(request, response, currentTurns);\n usage = Usage.add(usage, response.usage);\n await this.runCompletionResponseHook(prompt, response, newMessages);\n await this.runTurnEndHook(currentTurns, response, newMessages);\n\n const toolCalls = response.choice.filter(\n (item): item is ToolCall => item.type === \"tool_call\",\n );\n const assistantMessage = Message.assistant(response.choice, response.messageId);\n newMessages.push(assistantMessage);\n if (toolCalls.length === 0) {\n if (this.steeringMessages.length > 0) {\n await this.memoryRecorder.commitMessages(\n runId,\n currentTurns,\n [assistantMessage],\n pendingTurnMessages,\n );\n }\n if (\n await this.drainSteeringMessages(runId, currentTurns, newMessages, pendingTurnMessages)\n ) {\n await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);\n continue;\n }\n\n const guardedOutput = await this.runOutputGuardrailsForResponse(\n runId,\n usage,\n response,\n newMessages,\n runObservers,\n );\n response = guardedOutput.response;\n const finalAssistantMessage = Message.assistant(response.choice, response.messageId);\n newMessages[newMessages.length - 1] = finalAssistantMessage;\n await this.memoryRecorder.commitMessages(\n runId,\n currentTurns,\n [finalAssistantMessage],\n pendingTurnMessages,\n );\n const result: PromptResponse = {\n output: guardedOutput.output,\n usage,\n messages: [...newMessages],\n trace: runObservers.trace,\n guardrails: [...this.guardrailDecisions],\n };\n await this.runRunEndHook(result, newMessages);\n await runObservers.end(result);\n await this.memoryRecorder.commitCompletedRun(\n runId,\n currentTurns,\n newMessages,\n pendingTurnMessages,\n );\n this.runState = \"completed\";\n return result;\n }\n\n await this.memoryRecorder.commitMessages(\n runId,\n currentTurns,\n [assistantMessage],\n pendingTurnMessages,\n );\n const toolResults = await this.executeToolCalls(\n runId,\n toolCalls,\n newMessages,\n undefined,\n undefined,\n {\n turn: currentTurns,\n runObservers,\n toolDefinitions: request.tools,\n },\n );\n const toolMessage = Message.tool(toolResults);\n newMessages.push(toolMessage);\n await this.memoryRecorder.commitMessages(\n runId,\n currentTurns,\n [toolMessage],\n pendingTurnMessages,\n );\n await this.drainSteeringMessages(runId, currentTurns, newMessages, pendingTurnMessages);\n await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);\n }\n\n throw new MaxTurnsError(this.maxTurnCount, [...this.chatHistory, ...newMessages], lastPrompt);\n } catch (error) {\n const finalError = await this.runRunErrorHook(error, usage, newMessages);\n this.runState = finalError instanceof PromptCancelledError ? \"cancelled\" : \"errored\";\n await runObservers.error({ error: finalError, usage, messages: [...newMessages] });\n await this.memoryRecorder.recordError(runId, finalError, newMessages);\n throw finalError;\n }\n }\n\n async *stream(): AsyncIterable<AgentStreamEvent> {\n if (!this.agent.model.capabilities.streaming || !isStreamingCompletionModel(this.agent.model)) {\n throw new Error(\"This completion model does not support streaming\");\n }\n\n this.startRun();\n const runId = globalThis.crypto.randomUUID();\n const emit = async (event: AgentStreamEvent): Promise<AgentStreamEvent> => {\n await this.recordAgentEvent(runId, event);\n return event;\n };\n let usage = Usage.empty();\n let currentTurns = 0;\n let lastPrompt = this.promptMessage;\n let newMessages: MessageType[] = [this.promptMessage];\n const runObservers = await this.startRunObservers();\n const bufferOutputDeltas = hasEnforcedOutputGuardrails(this.guardrailPolicies);\n\n try {\n const inputResult = await runInputGuardrails(this.guardrailPolicies, {\n prompt: this.promptMessage,\n history: this.chatHistory,\n inputText: textFromMessage(this.promptMessage),\n run: this.guardrailRunContext(runId),\n });\n for (const decision of inputResult.decisions) {\n await this.recordGuardrailDecision(decision, runObservers);\n yield await emit({ type: \"guardrail_decision\", decision });\n }\n this.promptMessage = inputResult.prompt;\n if (inputResult.blocked) {\n const output = inputResult.message ?? \"The request was blocked by a guardrail.\";\n const result: PromptResponse = {\n output,\n usage: Usage.empty(),\n messages: [this.promptMessage, Message.assistant(output)],\n guardrails: [...this.guardrailDecisions],\n };\n await runObservers.end(result);\n this.runState = \"completed\";\n yield await emit({\n type: \"final\",\n runId,\n output: result.output,\n usage: result.usage,\n messages: result.messages,\n guardrails: result.guardrails,\n });\n return;\n }\n\n newMessages = [this.promptMessage];\n this.chatHistory = await this.memoryRecorder.prepareRun(runId, newMessages);\n const pendingTurnMessages = this.memoryRecorder.pendingTurnMessages(newMessages);\n await this.runRunStartHook(newMessages);\n while (currentTurns <= this.maxTurnCount + 1) {\n const prompt = newMessages.at(-1);\n if (prompt === undefined) {\n throw new Error(\"PromptRequest requires at least one message\");\n }\n\n lastPrompt = prompt;\n currentTurns += 1;\n\n const historyForRequest = [...this.chatHistory, ...newMessages.slice(0, -1)];\n yield await emit({\n type: \"turn_start\",\n turn: currentTurns,\n prompt,\n history: historyForRequest,\n });\n await this.runTurnStartHook(currentTurns, prompt, historyForRequest, newMessages);\n await this.runCompletionCallHook(prompt, historyForRequest, newMessages);\n\n const ragText = extractRagText(prompt);\n const dynamicContext = await fetchDynamicContext(this.agent, ragText);\n const toolDefs = await fetchToolDefinitions(this.agent, ragText);\n let request = new CompletionRequestBuilder(this.agent.model, prompt)\n .instructions(this.agent.instructions)\n .messages(historyForRequest)\n .documents([...this.agent.staticContext, ...dynamicContext])\n .tools(toolDefs)\n .temperature(this.agent.temperature)\n .maxTokens(this.agent.maxTokens)\n .additionalParams(this.agent.additionalParams)\n .toolChoice(this.agent.toolChoice)\n .outputSchema(this.agent.outputSchema)\n .build();\n request = (await this.runCompletionRequestMiddlewares(\n request,\n currentTurns,\n )) as typeof request;\n\n assertCompletionRequestSupported(this.agent.model, request, { streaming: true });\n const providerRequest = this.providerTraceRequest(request, { stream: true });\n const generationObservers = await runObservers.startGeneration(\n compact({\n turn: currentTurns,\n request,\n providerRequest,\n modelInfo: {\n provider: this.agent.model.provider,\n defaultModel: this.agent.model.defaultModel,\n capabilities: this.agent.model.capabilities,\n },\n }),\n );\n const accumulator = new CompletionStreamAccumulator();\n const generationStartedAt = Date.now();\n let firstDeltaMs: number | undefined;\n const bufferResponseEvents = this.shouldBufferStreamResponseEvents();\n const emittedToolCallIds = new Set<string>();\n try {\n for await (const event of this.agent.model.streamCompletion(request)) {\n if (firstDeltaMs === undefined && isGenerationDeltaEvent(event.type)) {\n firstDeltaMs = Date.now() - generationStartedAt;\n }\n const mapped = accumulator.accept(event);\n if (event.type === \"error\") {\n throw event.error;\n }\n if (mapped !== undefined) {\n await generationObservers.update?.({ turn: currentTurns, delta: mapped });\n if (mapped.type === \"tool_call\") {\n emittedToolCallIds.add(mapped.toolCall.id);\n }\n const shouldBuffer =\n bufferResponseEvents ||\n (bufferOutputDeltas &&\n (mapped.type === \"text_delta\" || mapped.type === \"reasoning_delta\"));\n if (!shouldBuffer) {\n yield await emit(addTurn(currentTurns, mapped));\n }\n }\n }\n } catch (error) {\n await generationObservers.error({ turn: currentTurns, error });\n await this.runCompletionErrorHook(prompt, error, newMessages);\n throw error;\n }\n\n let response = accumulator.response();\n await generationObservers.end(\n compact({\n turn: currentTurns,\n response,\n firstDeltaMs,\n }),\n );\n response = await this.runCompletionResponseMiddlewares(request, response, currentTurns);\n usage = Usage.add(usage, response.usage);\n await this.runCompletionResponseHook(prompt, response, newMessages);\n await this.runTurnEndHook(currentTurns, response, newMessages);\n\n const toolCalls = response.choice.filter(\n (item): item is ToolCall => item.type === \"tool_call\",\n );\n let assistantMessage = Message.assistant(response.choice, response.messageId);\n newMessages.push(assistantMessage);\n\n if (toolCalls.length === 0) {\n let emittedTurnEnd = false;\n if (!bufferOutputDeltas) {\n if (bufferResponseEvents) {\n for (const event of responseStreamEvents(currentTurns, response)) {\n yield await emit(event);\n }\n }\n yield await emit({ type: \"turn_end\", turn: currentTurns, response });\n emittedTurnEnd = true;\n }\n if (this.steeringMessages.length > 0) {\n await this.memoryRecorder.commitMessages(\n runId,\n currentTurns,\n [assistantMessage],\n pendingTurnMessages,\n );\n }\n if (\n await this.drainSteeringMessages(runId, currentTurns, newMessages, pendingTurnMessages)\n ) {\n await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);\n continue;\n }\n\n const guardedOutput = await this.runOutputGuardrailsForResponse(\n runId,\n usage,\n response,\n newMessages,\n runObservers,\n );\n for (const decision of guardedOutput.decisions) {\n yield await emit({ type: \"guardrail_decision\", decision });\n }\n response = guardedOutput.response;\n assistantMessage = Message.assistant(response.choice, response.messageId);\n newMessages[newMessages.length - 1] = assistantMessage;\n await this.memoryRecorder.commitMessages(\n runId,\n currentTurns,\n [assistantMessage],\n pendingTurnMessages,\n );\n if (!emittedTurnEnd && (bufferResponseEvents || bufferOutputDeltas)) {\n for (const event of responseStreamEvents(currentTurns, response)) {\n yield await emit(event);\n }\n }\n if (!emittedTurnEnd) {\n yield await emit({ type: \"turn_end\", turn: currentTurns, response });\n }\n\n const result: PromptResponse = {\n output: guardedOutput.output,\n usage,\n messages: [...newMessages],\n trace: runObservers.trace,\n guardrails: [...this.guardrailDecisions],\n };\n await this.runRunEndHook(result, newMessages);\n await runObservers.end(result);\n await this.memoryRecorder.commitCompletedRun(\n runId,\n currentTurns,\n newMessages,\n pendingTurnMessages,\n );\n this.runState = \"completed\";\n yield await emit({\n type: \"final\",\n runId,\n output: result.output,\n usage: result.usage,\n messages: result.messages,\n trace: result.trace,\n guardrails: result.guardrails,\n });\n return;\n }\n\n if (bufferResponseEvents) {\n for (const event of responseStreamEvents(currentTurns, response)) {\n yield await emit(event);\n }\n } else {\n for (const toolCall of toolCalls) {\n if (!emittedToolCallIds.has(toolCall.id)) {\n yield await emit({ type: \"tool_call\", turn: currentTurns, toolCall });\n }\n }\n }\n await this.memoryRecorder.commitMessages(\n runId,\n currentTurns,\n [assistantMessage],\n pendingTurnMessages,\n );\n yield await emit({ type: \"turn_end\", turn: currentTurns, response });\n\n const toolResultEvents = createAsyncQueue<ToolExecutionEventPayload>();\n const toolResultsPromise = this.executeToolCalls(\n runId,\n toolCalls,\n newMessages,\n (result) => {\n toolResultEvents.enqueue(result);\n },\n (event) => {\n toolResultEvents.enqueue(event);\n },\n {\n turn: currentTurns,\n runObservers,\n toolDefinitions: request.tools,\n },\n );\n toolResultsPromise.then(\n () => toolResultEvents.close(),\n (error: unknown) => toolResultEvents.throw(error),\n );\n for await (const result of toolResultEvents) {\n yield await emit({ turn: currentTurns, ...result });\n }\n const toolResults = await toolResultsPromise;\n const toolMessage = Message.tool(toolResults);\n newMessages.push(toolMessage);\n await this.memoryRecorder.commitMessages(\n runId,\n currentTurns,\n [toolMessage],\n pendingTurnMessages,\n );\n await this.drainSteeringMessages(runId, currentTurns, newMessages, pendingTurnMessages);\n await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);\n }\n\n throw new MaxTurnsError(this.maxTurnCount, [...this.chatHistory, ...newMessages], lastPrompt);\n } catch (error) {\n const finalError = await this.runRunErrorHook(error, usage, newMessages);\n this.runState = finalError instanceof PromptCancelledError ? \"cancelled\" : \"errored\";\n await runObservers.error({ error: finalError, usage, messages: [...newMessages] });\n await this.memoryRecorder.recordError(runId, finalError, newMessages);\n yield await emit({ type: \"error\", error: finalError });\n throw finalError;\n }\n }\n\n readableStream(): ReadableStream<Uint8Array> {\n return toReadableStream(this.stream());\n }\n\n private async runCompletion(\n request: ReturnType<CompletionRequestBuilder[\"build\"]>,\n turn: number,\n runObservers: ActiveAgentRunObservers,\n ): Promise<CompletionResponse> {\n assertCompletionRequestSupported(this.agent.model, request);\n const providerRequest = this.providerTraceRequest(request);\n const generationObservers = await runObservers.startGeneration(\n compact({\n turn,\n request,\n providerRequest,\n modelInfo: {\n provider: this.agent.model.provider,\n defaultModel: this.agent.model.defaultModel,\n capabilities: this.agent.model.capabilities,\n },\n }),\n );\n try {\n const response = await this.agent.model.completion(request);\n await generationObservers.end({ turn, response });\n return response;\n } catch (error) {\n await generationObservers.error({ turn, error });\n throw error;\n }\n }\n\n private providerTraceRequest(\n request: ReturnType<CompletionRequestBuilder[\"build\"]>,\n options: { stream?: boolean | undefined } = {},\n ): JsonObject | undefined {\n try {\n return this.agent.model.traceRequest?.(request, options);\n } catch (error) {\n return {\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n private async executeToolCalls(\n runId: string,\n toolCalls: ToolCall[],\n newMessages: MessageType[],\n onResult?: (result: ToolResultEventPayload) => void,\n onStreamEvent?: (event: AgentToolEventPayload) => void,\n observation?: {\n turn: number;\n runObservers: ActiveAgentRunObservers;\n toolDefinitions?: ToolDefinition[];\n },\n ): Promise<ToolResult[]> {\n const executor = new ToolCallExecutor(\n this.agent,\n this.activeHook,\n this.approvalOptions,\n {\n runId,\n sessionId: this.memoryContext?.sessionId,\n metadata: this.memoryContext?.metadata,\n },\n this.concurrency,\n this.requestMiddlewares,\n (reason) => this.cancelled(newMessages, reason),\n );\n return executor.execute(toolCalls, onResult, onStreamEvent, observation);\n }\n\n private async runOutputGuardrailsForResponse(\n runId: string,\n usage: Usage,\n response: CompletionResponse,\n messages: MessageType[],\n runObservers: ActiveAgentRunObservers,\n ): Promise<{\n output: string;\n response: CompletionResponse;\n decisions: GuardrailDecisionRecord[];\n }> {\n const originalOutput = textFromAssistantContent(response.choice);\n const result = await runOutputGuardrails(this.guardrailPolicies, {\n outputText: originalOutput,\n messages: [...this.chatHistory, ...messages],\n usage,\n run: this.guardrailRunContext(runId),\n });\n for (const decision of result.decisions) {\n await this.recordGuardrailDecision(decision, runObservers);\n }\n const output = result.blocked\n ? (result.message ?? \"The response was blocked by a guardrail.\")\n : result.outputText;\n if (output === originalOutput) {\n return { output, response, decisions: result.decisions };\n }\n return {\n output,\n response: {\n ...response,\n choice: [AssistantContent.text(output)],\n },\n decisions: result.decisions,\n };\n }\n\n private async recordGuardrailDecision(\n decision: GuardrailDecisionRecord,\n runObservers: ActiveAgentRunObservers,\n ): Promise<void> {\n this.guardrailDecisions.push(decision);\n await runObservers.event({\n name: \"guardrail.decision\",\n level: decision.action === \"block\" ? \"WARNING\" : \"DEFAULT\",\n attributes: guardrailDecisionAttributes(decision),\n });\n }\n\n private guardrailRunContext(runId: string): GuardrailRunContext {\n return compact({\n agentId: this.agent.id,\n runId,\n sessionId: this.memoryContext?.sessionId,\n metadata: this.memoryContext?.metadata,\n }) as GuardrailRunContext;\n }\n\n private async startRunObservers(): Promise<ActiveAgentRunObservers> {\n const failOnObserverError =\n this.traceOptions?.failOnObserverError === true ||\n this.agent.observers.some((registration) => registration.failOnObserverError === true);\n return startAgentRunObservers(\n this.agent.observers,\n {\n agentName: this.agent.name,\n agentDescription: this.agent.description,\n instructions: this.agent.instructions,\n trace: this.traceOptions,\n prompt: this.promptMessage,\n history: this.chatHistory,\n maxTurns: this.maxTurnCount,\n },\n failOnObserverError,\n );\n }\n\n private async recordAgentEvent(runId: string, event: AgentStreamEvent): Promise<void> {\n const registration = this.agent.eventStore;\n if (registration === undefined) {\n return;\n }\n if (registration.options.include === \"agent_tool_events\" && event.type !== \"agent_tool_event\") {\n return;\n }\n\n const turn = \"turn\" in event ? event.turn : undefined;\n const agentId = event.type === \"agent_tool_event\" ? event.agentId : this.agent.id;\n const agentName = event.type === \"agent_tool_event\" ? event.agentName : this.agent.name;\n await registration.store.append({\n runId,\n agentId,\n ...compact({ agentName, turn }),\n ...(event.type === \"agent_tool_event\"\n ? compact({\n toolName: event.toolName,\n toolCallId: event.toolCallId,\n internalCallId: event.internalCallId,\n })\n : {}),\n event,\n });\n }\n\n private async runCompletionCallHook(\n prompt: MessageType,\n history: MessageType[],\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onCompletionCall?.({\n prompt,\n history,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runRunStartHook(newMessages: MessageType[]): Promise<void> {\n const action = await this.activeHook?.onRunStart?.({\n prompt: this.promptMessage,\n history: this.chatHistory,\n maxTurns: this.maxTurnCount,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runRunEndHook(result: PromptResponse, newMessages: MessageType[]): Promise<void> {\n const action = await this.activeHook?.onRunEnd?.({\n output: result.output,\n usage: result.usage,\n messages: result.messages,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runRunErrorHook(\n error: unknown,\n usage: Usage,\n newMessages: MessageType[],\n ): Promise<unknown> {\n const action = await this.activeHook?.onRunError?.({\n error,\n usage,\n messages: [...this.chatHistory, ...newMessages],\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n return this.cancelled(newMessages, action.reason);\n }\n return error;\n }\n\n private async runTurnStartHook(\n turn: number,\n prompt: MessageType,\n history: MessageType[],\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onTurnStart?.({\n turn,\n prompt,\n history,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runTurnEndHook(\n turn: number,\n response: CompletionResponse,\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onTurnEnd?.({\n turn,\n response,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runCompletionRequestMiddlewares(\n request: ReturnType<CompletionRequestBuilder[\"build\"]>,\n turn: number,\n ): Promise<ReturnType<CompletionRequestBuilder[\"build\"]>> {\n let current = request;\n for (const middleware of this.activeMiddlewares()) {\n const replacement = await middleware.onCompletionRequest?.({\n turn,\n request: current,\n originalRequest: request,\n });\n if (replacement?.request !== undefined) {\n current = replacement.request;\n }\n }\n return current;\n }\n\n private async runCompletionResponseMiddlewares(\n request: ReturnType<CompletionRequestBuilder[\"build\"]>,\n response: CompletionResponse,\n turn: number,\n ): Promise<CompletionResponse> {\n let current = response;\n for (const middleware of this.activeMiddlewares()) {\n const replacement = await middleware.onCompletionResponse?.({\n turn,\n request,\n response: current,\n originalResponse: response,\n });\n if (replacement?.response !== undefined) {\n current = replacement.response;\n }\n }\n return current;\n }\n\n private async runCompletionResponseHook(\n prompt: MessageType,\n response:\n | Awaited<ReturnType<M[\"completion\"]>>\n | Awaited<ReturnType<CompletionModel[\"completion\"]>>,\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onCompletionResponse?.({\n prompt,\n response,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private async runCompletionErrorHook(\n prompt: MessageType,\n error: unknown,\n newMessages: MessageType[],\n ): Promise<void> {\n const action = await this.activeHook?.onCompletionError?.({\n prompt,\n error,\n run: runControl,\n });\n if (action?.type === \"terminate\") {\n throw this.cancelled(newMessages, action.reason);\n }\n }\n\n private activeMiddlewares(): AgentMiddleware[] {\n return [...this.agent.middlewares, ...this.requestMiddlewares];\n }\n\n private shouldBufferStreamResponseEvents(): boolean {\n return (\n this.activeHook?.onCompletionResponse !== undefined ||\n this.activeMiddlewares().some((middleware) => middleware.onCompletionResponse !== undefined)\n );\n }\n\n private async drainSteeringMessages(\n runId: string,\n turn: number,\n newMessages: MessageType[],\n pendingTurnMessages: MessageType[],\n ): Promise<boolean> {\n const messages = this.steeringMessages.splice(0);\n if (messages.length === 0) {\n return false;\n }\n\n newMessages.push(...messages);\n await this.memoryRecorder.commitMessages(runId, turn, messages, pendingTurnMessages);\n return true;\n }\n\n private startRun(): void {\n if (this.runState === \"idle\") {\n this.runState = \"running\";\n return;\n }\n if (this.runState === \"running\") {\n throw new Error(\"PromptRequest is already running.\");\n }\n throw new Error(\"PromptRequest has already been used.\");\n }\n\n private isTerminal(): boolean {\n return (\n this.runState === \"completed\" || this.runState === \"errored\" || this.runState === \"cancelled\"\n );\n }\n\n private cancelled(newMessages: MessageType[], reason: string): PromptCancelledError {\n return new PromptCancelledError([...this.chatHistory, ...newMessages], reason);\n }\n}\n\nfunction normalizePromptInput(prompt: string | MessageType | MessageType[]): {\n prompt: MessageType;\n history: MessageType[];\n} {\n if (typeof prompt === \"string\") {\n return { prompt: Message.user(prompt), history: [] };\n }\n if (!Array.isArray(prompt)) {\n return { prompt, history: [] };\n }\n if (prompt.length === 0) {\n throw new TypeError(\"Prompt transcript must contain at least one message.\");\n }\n const activePrompt = prompt.at(-1);\n if (activePrompt === undefined) {\n throw new TypeError(\"Prompt transcript must contain at least one message.\");\n }\n return {\n prompt: activePrompt,\n history: prompt.slice(0, -1),\n };\n}\n\nfunction normalizeSteeringInput(input: string | MessageType | MessageType[]): MessageType[] {\n if (typeof input === \"string\") {\n return [Message.user(input)];\n }\n return Array.isArray(input) ? [...input] : [input];\n}\n\nfunction responseStreamEvents(turn: number, response: CompletionResponse): AgentStreamEvent[] {\n const events: AgentStreamEvent[] = [];\n for (const item of response.choice) {\n if (item.type === \"text\") {\n if (item.text.length > 0) {\n events.push({ type: \"text_delta\", turn, delta: item.text });\n }\n continue;\n }\n\n if (item.type === \"reasoning\") {\n if (item.content === undefined) {\n if (item.text.length > 0) {\n events.push(\n compact({ type: \"reasoning_delta\" as const, turn, delta: item.text, id: item.id }),\n );\n }\n continue;\n }\n\n for (const content of item.content) {\n const delta =\n content.type === \"encrypted\" || content.type === \"redacted\" ? content.data : content.text;\n events.push(\n compact({\n type: \"reasoning_delta\" as const,\n turn,\n delta,\n id: item.id,\n contentType: content.type,\n signature: content.type === \"text\" ? content.signature : undefined,\n }),\n );\n }\n continue;\n }\n\n if (item.type === \"tool_call\") {\n events.push({ type: \"tool_call\", turn, toolCall: item });\n }\n }\n return events;\n}\n\nfunction textFromMessage(message: MessageType): string {\n if (message.role === \"system\") {\n return message.content;\n }\n return message.content\n .flatMap((content) => {\n if (content.type === \"text\") {\n return [content.text];\n }\n if (content.type === \"document\" && content.source.type === \"text\") {\n return [content.source.text];\n }\n return [];\n })\n .join(\"\\n\");\n}\n\nfunction guardrailDecisionAttributes(\n decision: GuardrailDecisionRecord,\n): Record<string, JsonValue | undefined> {\n return compact({\n policyId: decision.policyId,\n guardrailId: decision.guardrailId,\n boundary: decision.boundary,\n mode: decision.mode,\n action: decision.action,\n applied: decision.applied,\n reason: decision.reason,\n message: decision.message,\n latencyMs: decision.latencyMs,\n }) as Record<string, JsonValue | undefined>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGO,IAAM,gBAAN,cAA4B,MAAM;AAAA,EACvC,YACW,UACA,aACA,QACT;AACA,UAAM,2BAA2B,QAAQ,EAAE;AAJlC;AACA;AACA;AAGT,SAAK,OAAO;AAAA,EACd;AAAA,EANW;AAAA,EACA;AAAA,EACA;AAKb;AAEO,IAAM,uBAAN,cAAmC,MAAM;AAAA,EAC9C,YACW,aACA,QACT;AACA,UAAM,qBAAqB,MAAM,EAAE;AAH1B;AACA;AAGT,SAAK,OAAO;AAAA,EACd;AAAA,EALW;AAAA,EACA;AAKb;AAEO,IAAM,4BAAN,cAAwC,MAAM;AAAA,EACnD,YAAqB,SAA8B;AACjD,UAAM,8BAA8B,QAAQ,QAAQ,0CAA0C;AAD3E;AAEnB,SAAK,OAAO;AAAA,EACd;AAAA,EAHqB;AAIvB;;;AClBO,SAAS,mBAAqC;AACnD,QAAM,SAAc,CAAC;AACrB,QAAM,UAAiC,CAAC;AACxC,MAAI,SAAS;AACb,MAAI;AAEJ,WAAS,QAAc;AACrB,WAAO,QAAQ,SAAS,KAAK,OAAO,SAAS,GAAG;AAC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QAAI,KAAK,SAAS,aAAa;AAC7B,aAAO,KAAK,EAAE,MAAM,aAAa,MAAM,UAAU,KAAK,CAAC;AAAA,IACzD;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,gBAAgB,SAA8B;AACrD,MAAI,QAAQ,SAAS,UAAU;AAC7B,WAAO,QAAQ;AAAA,EACjB;AACA,SAAO,QAAQ,QACZ,QAAQ,CAAC,YAAY;AACpB,QAAI,QAAQ,SAAS,QAAQ;AAC3B,aAAO,CAAC,QAAQ,IAAI;AAAA,IACtB;AACA,QAAI,QAAQ,SAAS,cAAc,QAAQ,OAAO,SAAS,QAAQ;AACjE,aAAO,CAAC,QAAQ,OAAO,IAAI;AAAA,IAC7B;AACA,WAAO,CAAC;AAAA,EACV,CAAC,EACA,KAAK,IAAI;AACd;AAEA,SAAS,4BACP,UACuC;AACvC,SAAO,QAAQ;AAAA,IACb,UAAU,SAAS;AAAA,IACnB,aAAa,SAAS;AAAA,IACtB,UAAU,SAAS;AAAA,IACnB,MAAM,SAAS;AAAA,IACf,QAAQ,SAAS;AAAA,IACjB,SAAS,SAAS;AAAA,IAClB,QAAQ,SAAS;AAAA,IACjB,SAAS,SAAS;AAAA,IAClB,WAAW,SAAS;AAAA,EACtB,CAAC;AACH;","names":["key","reasoning"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/vector-store/index.ts","../src/tool/create-tool.ts","../src/vector-store/filter.ts","../src/vector-store/lsh.ts"],"sourcesContent":["import { z } from \"zod\";\nimport {\n cosineSimilarity,\n type EmbeddedDocument,\n type Embedding,\n type EmbeddingModel,\n embedText,\n type VectorMetadata,\n} from \"../embeddings\";\nimport { createTool } from \"../tool/create-tool\";\nimport type { Tool } from \"../tool/tool\";\nimport { matchesVectorFilter } from \"./filter\";\nimport { LshIndex } from \"./lsh\";\nimport type {\n IndexStrategy,\n VectorInspectPage,\n VectorInspectRequest,\n VectorSearchIndex,\n VectorSearchRequest,\n VectorSearchResult,\n VectorSearchToolOptions,\n} from \"./types\";\n\nexport { vectorFilter } from \"./filter\";\nexport type * from \"./types\";\n\ntype StoredDocument<T, Metadata extends VectorMetadata> = EmbeddedDocument<T, Metadata>;\n\nexport class InMemoryVectorStore<T, Metadata extends VectorMetadata = VectorMetadata> {\n private readonly documents = new Map<string, StoredDocument<T, Metadata>>();\n private indexStrategy: IndexStrategy;\n private lshIndex: LshIndex | undefined;\n private embeddingDimension: number | undefined;\n\n constructor(options: { index?: IndexStrategy } = {}) {\n this.indexStrategy = options.index ?? { type: \"bruteForce\" };\n }\n\n static fromDocuments<T, Metadata extends VectorMetadata = VectorMetadata>(\n documents: Array<EmbeddedDocument<T, Metadata>>,\n options: { index?: IndexStrategy } = {},\n ): InMemoryVectorStore<T, Metadata> {\n const store = new InMemoryVectorStore<T, Metadata>(options);\n store.addDocuments(documents);\n return store;\n }\n\n addDocuments(documents: Array<EmbeddedDocument<T, Metadata>>): this {\n this.validateDocumentDimensions(documents);\n for (const document of documents) {\n this.documents.set(document.id, document);\n }\n this.rebuildLshIndex();\n return this;\n }\n\n get(id: string): StoredDocument<T, Metadata> | undefined {\n return this.documents.get(id);\n }\n\n values(): Array<StoredDocument<T, Metadata>> {\n return [...this.documents.values()];\n }\n\n len(): number {\n return this.documents.size;\n }\n\n isEmpty(): boolean {\n return this.documents.size === 0;\n }\n\n index(model: EmbeddingModel): InMemoryVectorIndex<T, Metadata> {\n return new InMemoryVectorIndex(model, this);\n }\n\n candidates(queryEmbedding: Embedding): Array<StoredDocument<T, Metadata>> {\n this.validateQueryDimension(queryEmbedding);\n if (this.indexStrategy.type !== \"lsh\" || this.lshIndex === undefined) {\n return this.values();\n }\n\n const candidateIds = this.lshIndex.query(queryEmbedding.vector);\n if (candidateIds.size === 0) {\n return this.values();\n }\n\n return [...candidateIds].flatMap((id) => {\n const document = this.documents.get(id);\n return document === undefined ? [] : [document];\n });\n }\n\n private rebuildLshIndex(): void {\n if (this.indexStrategy.type !== \"lsh\") {\n this.lshIndex = undefined;\n return;\n }\n\n const firstEmbedding = this.values().flatMap((document) => document.embeddings)[0];\n if (firstEmbedding === undefined) {\n this.lshIndex = undefined;\n return;\n }\n\n const index = new LshIndex(firstEmbedding.vector.length, this.indexStrategy);\n for (const document of this.documents.values()) {\n for (const embedding of document.embeddings) {\n index.insert(document.id, embedding.vector);\n }\n }\n this.lshIndex = index;\n }\n\n private validateDocumentDimensions(documents: Array<EmbeddedDocument<T, Metadata>>): void {\n let dimension = this.embeddingDimension;\n for (const document of documents) {\n for (const embedding of document.embeddings) {\n dimension = validateEmbeddingDimension(dimension, embedding, document.id);\n }\n }\n this.embeddingDimension = dimension;\n }\n\n private validateQueryDimension(queryEmbedding: Embedding): void {\n if (this.embeddingDimension === undefined) {\n return;\n }\n validateEmbeddingDimension(this.embeddingDimension, queryEmbedding, \"query\");\n }\n}\n\nexport class InMemoryVectorIndex<T, Metadata extends VectorMetadata = VectorMetadata>\n implements VectorSearchIndex<T, Metadata>\n{\n constructor(\n private readonly model: EmbeddingModel,\n private readonly store: InMemoryVectorStore<T, Metadata>,\n ) {}\n\n async search(request: VectorSearchRequest): Promise<Array<VectorSearchResult<T, Metadata>>> {\n const queryEmbedding = await embedText(this.model, request.query);\n return this.store\n .candidates(queryEmbedding)\n .filter((document) => matchesVectorFilter(document.metadata, request.filter))\n .flatMap((document) => {\n const score = bestScore(queryEmbedding, document.embeddings);\n if (score === undefined) {\n return [];\n }\n if (request.threshold !== undefined && score < request.threshold) {\n return [];\n }\n return [\n {\n score,\n id: document.id,\n document: document.document,\n ...(document.metadata !== undefined && { metadata: document.metadata }),\n },\n ];\n })\n .sort((left, right) => right.score - left.score)\n .slice(0, Math.max(0, Math.trunc(request.topK)));\n }\n\n async searchIds(request: VectorSearchRequest): Promise<Array<{ score: number; id: string }>> {\n return (await this.search(request)).map(({ score, id }) => ({ score, id }));\n }\n\n async inspect(request: VectorInspectRequest): Promise<VectorInspectPage<T, Metadata>> {\n const limit = Math.max(0, Math.trunc(request.limit));\n const start = Math.max(0, Math.trunc(Number(request.cursor ?? \"0\")));\n const documents = this.store\n .values()\n .filter((document) => matchesVectorFilter(document.metadata, request.filter));\n const page = documents.slice(start, start + limit);\n const nextOffset = start + page.length;\n return {\n items: page.map((document) => ({\n id: document.id,\n document: document.document,\n ...(document.metadata !== undefined && { metadata: document.metadata }),\n })),\n ...(nextOffset < documents.length ? { nextCursor: String(nextOffset) } : {}),\n totalCount: documents.length,\n };\n }\n\n asTool(options: VectorSearchToolOptions): Tool<{ query: string; topK?: number }, unknown> {\n return createVectorSearchTool(this, options);\n }\n}\n\nexport function createVectorSearchTool<T, Metadata extends VectorMetadata>(\n index: VectorSearchIndex<T, Metadata>,\n options: VectorSearchToolOptions,\n): Tool<{ query: string; topK?: number }, Array<VectorSearchResult<T, Metadata>>> {\n return createTool({\n name: options.name,\n description:\n options.description ?? \"Search a vector store for documents relevant to the provided query.\",\n input: z.object({\n query: z.string().describe(\"The query string to search for relevant documents.\"),\n topK: z.number().int().positive().optional().describe(\"The maximum number of results.\"),\n }),\n output: z.array(\n z.object({\n score: z.number(),\n id: z.string(),\n document: z.any(),\n metadata: z\n .record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.null()]))\n .optional(),\n }),\n ),\n execute: ({ query, topK }) =>\n index.search({\n query,\n topK: topK ?? options.topK ?? 5,\n threshold: options.threshold,\n filter: options.filter,\n }),\n }) as Tool<{ query: string; topK?: number }, Array<VectorSearchResult<T, Metadata>>>;\n}\n\nfunction bestScore(queryEmbedding: Embedding, embeddings: Embedding[]): number | undefined {\n let best: number | undefined;\n for (const embedding of embeddings) {\n const score = cosineSimilarity(queryEmbedding.vector, embedding.vector);\n best = best === undefined ? score : Math.max(best, score);\n }\n return best;\n}\n\nfunction validateEmbeddingDimension(\n expectedDimension: number | undefined,\n embedding: Embedding,\n id: string,\n): number {\n if (expectedDimension === undefined) {\n return embedding.vector.length;\n }\n if (embedding.vector.length !== expectedDimension) {\n throw new Error(\n `Vector dimension mismatch: expected ${expectedDimension} dimensions but received ${embedding.vector.length} for ${id}`,\n );\n }\n return expectedDimension;\n}\n","import type { z } from \"zod\";\nimport { compact } from \"../internal/compact\";\nimport { toProviderJsonSchema, type ZodSchema } from \"../schema/zod-schema\";\nimport type { Tool, ToolApprovalPolicy, ToolCallContext } from \"./tool\";\n\nexport type CreateToolOptions<\n InputSchema extends ZodSchema,\n OutputSchema extends ZodSchema | undefined = undefined,\n Output = unknown,\n> = {\n name: string;\n description: string;\n input: InputSchema;\n output?: OutputSchema;\n approval?: ToolApprovalPolicy<z.output<InputSchema>>;\n execute(\n args: z.output<InputSchema>,\n context: ToolCallContext,\n ): OutputSchema extends ZodSchema\n ? z.input<OutputSchema> | Promise<z.input<OutputSchema>>\n : Output | Promise<Output>;\n};\n\ntype CreateToolOutput<\n OutputSchema extends ZodSchema | undefined,\n Output,\n> = OutputSchema extends ZodSchema ? z.output<OutputSchema> : Output;\n\nexport function createTool<InputSchema extends ZodSchema, Output = unknown>(\n options: CreateToolOptions<InputSchema, undefined, Output> & { output?: undefined },\n): Tool<z.output<InputSchema>, Output>;\n\nexport function createTool<InputSchema extends ZodSchema, OutputSchema extends ZodSchema>(\n options: CreateToolOptions<InputSchema, OutputSchema>,\n): Tool<z.output<InputSchema>, z.output<OutputSchema>>;\n\nexport function createTool<\n InputSchema extends ZodSchema,\n OutputSchema extends ZodSchema | undefined = undefined,\n Output = unknown,\n>(\n options: CreateToolOptions<InputSchema, OutputSchema, Output>,\n): Tool<z.output<InputSchema>, CreateToolOutput<OutputSchema, Output>> {\n const parameters = toProviderJsonSchema(options.input);\n\n return {\n ...compact({\n name: options.name,\n approval: options.approval,\n }),\n definition() {\n return {\n name: options.name,\n description: options.description,\n parameters,\n };\n },\n async call(args, context = {}): Promise<CreateToolOutput<OutputSchema, Output>> {\n const parsedArgs = options.input.parse(args);\n const result = await options.execute(parsedArgs, context);\n return (\n options.output === undefined ? result : options.output.parse(result)\n ) as CreateToolOutput<OutputSchema, Output>;\n },\n parseApprovalArgs(args): z.output<InputSchema> {\n return options.input.parse(args);\n },\n };\n}\n","import type { VectorMetadata, VectorMetadataValue } from \"../embeddings\";\nimport type { VectorFilter } from \"./types\";\n\nexport type { VectorFilter } from \"./types\";\n\nexport const vectorFilter = {\n eq(key: string, value: VectorMetadataValue): VectorFilter {\n return { type: \"eq\", key, value };\n },\n gt(key: string, value: VectorMetadataValue): VectorFilter {\n return { type: \"gt\", key, value };\n },\n lt(key: string, value: VectorMetadataValue): VectorFilter {\n return { type: \"lt\", key, value };\n },\n and(left: VectorFilter, right: VectorFilter): VectorFilter {\n return { type: \"and\", filters: [left, right] };\n },\n or(left: VectorFilter, right: VectorFilter): VectorFilter {\n return { type: \"or\", filters: [left, right] };\n },\n};\n\nexport function matchesVectorFilter(\n metadata: VectorMetadata | undefined,\n filter: VectorFilter | undefined,\n): boolean {\n if (filter === undefined) {\n return true;\n }\n if (metadata === undefined) {\n return false;\n }\n\n switch (filter.type) {\n case \"eq\":\n return metadata[filter.key] === filter.value;\n case \"gt\":\n return compare(metadata[filter.key], filter.value) > 0;\n case \"lt\":\n return compare(metadata[filter.key], filter.value) < 0;\n case \"and\":\n return (\n matchesVectorFilter(metadata, filter.filters[0]) &&\n matchesVectorFilter(metadata, filter.filters[1])\n );\n case \"or\":\n return (\n matchesVectorFilter(metadata, filter.filters[0]) ||\n matchesVectorFilter(metadata, filter.filters[1])\n );\n }\n}\n\nfunction compare(left: VectorMetadataValue | undefined, right: VectorMetadataValue): number {\n if (typeof left === \"number\" && typeof right === \"number\") {\n return left - right;\n }\n if (typeof left === \"string\" && typeof right === \"string\") {\n return left.localeCompare(right);\n }\n if (typeof left === \"boolean\" && typeof right === \"boolean\") {\n return Number(left) - Number(right);\n }\n return 0;\n}\n","import type { LshOptions } from \"./types\";\n\nexport type { LshOptions } from \"./types\";\n\nexport class LshIndex {\n private readonly hyperplanes: number[][];\n private readonly tables: Array<Map<string, Set<string>>>;\n\n constructor(\n dimensions: number,\n private readonly options: LshOptions,\n ) {\n const rng = seededRandom(options.seed ?? 42);\n this.hyperplanes = [];\n for (let index = 0; index < options.numTables * options.numHyperplanes; index += 1) {\n const plane = Array.from({ length: dimensions }, () => rng() * 2 - 1);\n const norm = Math.sqrt(plane.reduce((sum, value) => sum + value ** 2, 0));\n this.hyperplanes.push(norm === 0 ? plane : plane.map((value) => value / norm));\n }\n this.tables = Array.from({ length: options.numTables }, () => new Map());\n }\n\n insert(id: string, vector: number[]): void {\n for (let table = 0; table < this.options.numTables; table += 1) {\n const hash = this.hash(vector, table);\n const bucket = this.tables[table]?.get(hash) ?? new Set<string>();\n bucket.add(id);\n this.tables[table]?.set(hash, bucket);\n }\n }\n\n query(vector: number[]): Set<string> {\n const candidates = new Set<string>();\n for (let table = 0; table < this.options.numTables; table += 1) {\n const hash = this.hash(vector, table);\n for (const id of this.tables[table]?.get(hash) ?? []) {\n candidates.add(id);\n }\n }\n return candidates;\n }\n\n private hash(vector: number[], table: number): string {\n let hash = \"\";\n const start = table * this.options.numHyperplanes;\n for (let offset = 0; offset < this.options.numHyperplanes; offset += 1) {\n const plane = this.hyperplanes[start + offset] as number[];\n const dot = vector.reduce((sum, value, index) => sum + value * (plane[index] ?? 0), 0);\n hash += dot >= 0 ? \"1\" : \"0\";\n }\n return hash;\n }\n}\n\nfunction seededRandom(seed: number): () => number {\n let state = seed >>> 0;\n return () => {\n state = (state * 1664525 + 1013904223) >>> 0;\n return state / 0x100000000;\n };\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,SAAS;;;ACoCX,SAAS,WAKd,SACqE;AACrE,QAAM,aAAa,qBAAqB,QAAQ,KAAK;AAErD,SAAO;AAAA,IACL,GAAG,QAAQ;AAAA,MACT,MAAM,QAAQ;AAAA,MACd,UAAU,QAAQ;AAAA,IACpB,CAAC;AAAA,IACD,aAAa;AACX,aAAO;AAAA,QACL,MAAM,QAAQ;AAAA,QACd,aAAa,QAAQ;AAAA,QACrB;AAAA,MACF;AAAA,IACF;AAAA,IACA,MAAM,KAAK,MAAM,UA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};
4
- for (const [key, value] of Object.entries(obj)) {
5
- if (value !== void 0) {
6
- result[key] = value;
7
- }
8
- }
9
- return result;
10
- }
11
- function isRecord(value) {
12
- return typeof value === "object" && value !== null && !Array.isArray(value);
13
- }
14
-
15
- export {
16
- compact,
17
- isRecord
18
- };
19
- //# sourceMappingURL=chunk-MMHG7WAM.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/internal/compact.ts"],"sourcesContent":["/**\n * Strips keys whose resolved type includes `undefined`.\n *\n * Replaces the verbose `...(x === undefined ? {} : { key: x })` pattern.\n *\n * @example\n * compact({ id: \"1\", title: session.title, metadata: session.metadata })\n * // returns { id: \"1\" } when title and metadata are undefined\n */\nexport type Compact<T> = {\n [K in keyof T as undefined extends T[K] ? never : K]: Exclude<T[K], undefined>;\n};\n\nexport function compact<T extends Record<string, unknown>>(obj: T): Compact<T> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (value !== undefined) {\n result[key] = value;\n }\n }\n return result as Compact<T>;\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"],"mappings":";AAaO,SAAS,QAA2C,KAAoB;AAC7E,QAAM,SAAkC,CAAC;AACzC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,GAAG,GAAG;AAC9C,QAAI,UAAU,QAAW;AACvB,aAAO,GAAG,IAAI;AAAA,IAChB;AAAA,EACF;AACA,SAAO;AACT;AAEO,SAAS,SAAS,OAAkD;AACzE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/ui/messages.ts"],"sourcesContent":["import { isJsonValue } from \"../completion/json\";\nimport {\n AssistantContent,\n type AssistantContent as AssistantContentType,\n type Message as CoreMessage,\n type DocumentContent,\n type ImageContent,\n type ImageDetail,\n type JsonValue,\n Message,\n reasoningDisplayText,\n serializeToolResultOutput,\n ToolContent,\n type ToolContent as ToolContentType,\n type ToolResultContent,\n UserContent,\n type UserContent as UserContentType,\n} from \"../completion/types\";\nimport type { UIAttachment, UIMessage, UIMessagePart } from \"./types\";\n\ntype UIToolPartLocation = {\n messageIndex: number;\n partIndex: number;\n};\n\ntype UIToolPartLocations = {\n byToolCallId: Map<string, UIToolPartLocation>;\n byCallId: Map<string, UIToolPartLocation>;\n};\n\ntype UIToolMessagePart = Extract<UIMessagePart, { type: \"tool\" }>;\n\nexport function uiMessagesToCoreMessages(messages: UIMessage[]): CoreMessage[] {\n const coreMessages: CoreMessage[] = [];\n\n for (const message of messages) {\n const text = textFromUIParts(message.parts);\n\n if (message.role === \"system\") {\n if (text.length > 0) {\n coreMessages.push(Message.system(text, metadataOptions(message.metadata)));\n }\n continue;\n }\n\n if (message.role === \"user\") {\n const content: UserContentType[] = [];\n for (const part of message.parts) {\n if (part.type === \"text\") {\n content.push(UserContent.text(part.text));\n continue;\n }\n if (part.type === \"attachment\") {\n content.push(attachmentToUserContent(part.attachment));\n continue;\n }\n if (part.type === \"data\" && isUserContent(part.data)) {\n content.push(part.data);\n continue;\n }\n throw new TypeError(\n \"User UI messages can only be converted from text, attachment, or image/document data parts.\",\n );\n }\n if (content.length > 0) {\n coreMessages.push(Message.user(content, metadataOptions(message.metadata)));\n }\n continue;\n }\n\n if (message.role === \"assistant\") {\n const content: AssistantContentType[] = [];\n const toolResults: ToolContentType[] = [];\n for (const part of message.parts) {\n if (part.type === \"text\" && part.text.length > 0) {\n content.push(AssistantContent.text(part.text));\n continue;\n }\n if (part.type === \"reasoning\" && part.text.length > 0) {\n content.push(AssistantContent.reasoning(part.text, part.reasoningId));\n continue;\n }\n if (\n part.type === \"tool\" &&\n (part.state === \"input-streaming\" ||\n part.state === \"input-available\" ||\n part.state === \"output-available\")\n ) {\n content.push(\n AssistantContent.toolCall(\n part.toolCallId,\n part.toolName,\n part.input ?? {},\n part.callId,\n ),\n );\n if (part.state === \"output-available\") {\n toolResults.push(\n ToolContent.toolResult(part.toolCallId, outputToToolResultContent(part.output), {\n callId: part.callId,\n toolName: part.toolName,\n }),\n );\n }\n }\n }\n if (content.length > 0) {\n coreMessages.push(\n Message.assistant(content, {\n id: message.id,\n ...metadataOptions(message.metadata),\n }),\n );\n }\n if (toolResults.length > 0) {\n coreMessages.push(Message.tool(toolResults));\n }\n continue;\n }\n\n const toolResults: ToolContentType[] = [];\n for (const part of message.parts) {\n if (part.type !== \"tool\" || part.state !== \"output-available\") {\n continue;\n }\n toolResults.push(\n ToolContent.toolResult(part.toolCallId, outputToToolResultContent(part.output), {\n callId: part.callId,\n toolName: part.toolName,\n }),\n );\n }\n if (toolResults.length > 0) {\n coreMessages.push(Message.tool(toolResults, metadataOptions(message.metadata)));\n }\n }\n\n return coreMessages;\n}\n\nexport function coreMessagesToUIMessages(messages: CoreMessage[]): UIMessage[] {\n const uiMessages: UIMessage[] = [];\n const toolPartLocations: UIToolPartLocations = {\n byToolCallId: new Map(),\n byCallId: new Map(),\n };\n\n for (const message of messages) {\n if (message.role === \"system\") {\n uiMessages.push({\n id: createId(\"msg\"),\n role: \"system\",\n parts: [{ id: createId(\"part\"), type: \"text\", text: message.content }],\n ...uiMetadata(message.metadata),\n });\n continue;\n }\n\n if (message.role === \"user\") {\n const parts: UIMessagePart[] = [];\n for (const content of message.content) {\n if (content.type === \"text\") {\n parts.push({ id: createId(\"part\"), type: \"text\", text: content.text });\n } else {\n parts.push({\n id: createId(\"part\"),\n type: \"attachment\",\n attachment: userContentToAttachment(content),\n });\n }\n }\n uiMessages.push({\n id: createId(\"msg\"),\n role: \"user\",\n parts,\n ...uiMetadata(message.metadata),\n });\n continue;\n }\n\n if (message.role === \"assistant\") {\n const parts: UIMessagePart[] = [];\n for (const content of message.content) {\n if (content.type === \"text\") {\n parts.push({ id: createId(\"part\"), type: \"text\", text: content.text });\n continue;\n }\n if (content.type === \"reasoning\") {\n const part: UIMessagePart = {\n id: createId(\"part\"),\n type: \"reasoning\",\n text: reasoningDisplayText(content),\n };\n if (content.id !== undefined) {\n part.reasoningId = content.id;\n }\n parts.push(part);\n continue;\n }\n if (content.type === \"tool_call\") {\n const part: UIMessagePart = {\n id: toolPartId(content.id),\n type: \"tool\",\n toolName: content.function.name,\n toolCallId: content.id,\n state: \"input-available\",\n input: content.function.arguments,\n };\n if (content.callId !== undefined) {\n part.callId = content.callId;\n }\n parts.push(part);\n continue;\n }\n parts.push({\n id: createId(\"part\"),\n type: \"data\",\n name: content.type,\n data: content as JsonValue,\n });\n }\n const messageIndex = uiMessages.length;\n uiMessages.push({\n id: message.id ?? createId(\"msg\"),\n role: \"assistant\",\n parts,\n ...uiMetadata(message.metadata),\n });\n registerToolPartLocations(parts, messageIndex, toolPartLocations);\n continue;\n }\n\n const parts: UIMessagePart[] = [];\n for (const content of message.content) {\n const part: UIToolMessagePart = {\n id: toolPartId(content.id),\n type: \"tool\",\n toolName: toolNameForResult(content, uiMessages, toolPartLocations),\n toolCallId: content.id,\n state: \"output-available\",\n output: toolResultContentToJson(content.content),\n };\n if (content.callId !== undefined) {\n part.callId = content.callId;\n }\n if (\n message.metadata === undefined &&\n mergeToolResultPart(uiMessages, toolPartLocations, part)\n ) {\n continue;\n }\n parts.push(part);\n }\n if (parts.length > 0) {\n uiMessages.push({\n id: createId(\"msg\"),\n role: \"tool\",\n parts,\n ...uiMetadata(message.metadata),\n });\n }\n }\n\n return uiMessages;\n}\n\nfunction metadataOptions(metadata: UIMessage[\"metadata\"]): { metadata?: JsonValue } {\n if (metadata === undefined) {\n return {};\n }\n if (!isJsonValue(metadata)) {\n throw new TypeError(\"UI message metadata must be a strict JSON value.\");\n }\n return { metadata };\n}\n\nfunction uiMetadata(metadata: JsonValue | undefined): { metadata?: JsonValue } {\n if (metadata === undefined) {\n return {};\n }\n if (!isJsonValue(metadata)) {\n throw new TypeError(\"Core message metadata must be a strict JSON value.\");\n }\n return { metadata };\n}\n\nfunction registerToolPartLocations(\n parts: UIMessagePart[],\n messageIndex: number,\n toolPartLocations: UIToolPartLocations,\n): void {\n for (const [partIndex, part] of parts.entries()) {\n if (part.type !== \"tool\") {\n continue;\n }\n const location = { messageIndex, partIndex };\n toolPartLocations.byToolCallId.set(part.toolCallId, location);\n if (part.callId !== undefined) {\n toolPartLocations.byCallId.set(part.callId, location);\n }\n }\n}\n\nfunction mergeToolResultPart(\n uiMessages: UIMessage[],\n toolPartLocations: UIToolPartLocations,\n resultPart: UIMessagePart,\n): boolean {\n if (resultPart.type !== \"tool\") {\n return false;\n }\n\n const location = findToolPartLocation(\n resultPart.toolCallId,\n resultPart.callId,\n toolPartLocations,\n );\n if (location === undefined) {\n return false;\n }\n\n const message = uiMessages[location.messageIndex];\n const currentPart = message?.parts[location.partIndex];\n if (message === undefined || currentPart?.type !== \"tool\") {\n return false;\n }\n\n const mergedPart: UIToolMessagePart = {\n ...currentPart,\n toolName: resultPart.toolName === \"tool\" ? currentPart.toolName : resultPart.toolName,\n state: \"output-available\",\n ...(resultPart.output === undefined ? {} : { output: resultPart.output }),\n };\n if (currentPart.callId === undefined && resultPart.callId !== undefined) {\n mergedPart.callId = resultPart.callId;\n toolPartLocations.byCallId.set(resultPart.callId, location);\n }\n\n const nextParts = [...message.parts];\n nextParts[location.partIndex] = mergedPart;\n uiMessages[location.messageIndex] = { ...message, parts: nextParts };\n return true;\n}\n\nfunction findToolPartLocation(\n toolCallId: string,\n callId: string | undefined,\n toolPartLocations: UIToolPartLocations,\n): UIToolPartLocation | undefined {\n return (\n (callId === undefined ? undefined : toolPartLocations.byCallId.get(callId)) ??\n toolPartLocations.byToolCallId.get(toolCallId)\n );\n}\n\nfunction toolNameForResult(\n content: ToolContentType,\n uiMessages: UIMessage[],\n toolPartLocations: UIToolPartLocations,\n): string {\n if (content.toolName !== undefined) {\n return content.toolName;\n }\n\n const location = findToolPartLocation(content.id, content.callId, toolPartLocations);\n const part =\n location === undefined\n ? undefined\n : uiMessages[location.messageIndex]?.parts[location.partIndex];\n return part?.type === \"tool\" ? part.toolName : \"tool\";\n}\n\nexport function isUIMessage(value: unknown): value is UIMessage {\n return (\n isRecord(value) &&\n typeof value.id === \"string\" &&\n isUIMessageRole(value.role) &&\n Array.isArray(value.parts)\n );\n}\n\nexport function isUIMessageArray(value: unknown): value is UIMessage[] {\n return Array.isArray(value) && value.every(isUIMessage);\n}\n\nfunction textFromUIParts(parts: UIMessagePart[]): string {\n return parts.flatMap((part) => (part.type === \"text\" ? [part.text] : [])).join(\"\");\n}\n\nfunction outputToToolResultContent(output: JsonValue | undefined): ToolResultContent[] {\n return [{ type: \"text\", text: serializeToolResultOutput(output ?? null) }];\n}\n\nfunction attachmentToUserContent(attachment: UIAttachment): UserContentType {\n if (attachment.type === \"image\" || isImageFileAttachment(attachment)) {\n if (attachment.url !== undefined) {\n return UserContent.imageUrl(attachment.url, imageOptions(attachment));\n }\n if (attachment.data !== undefined && attachment.mediaType !== undefined) {\n return UserContent.imageBase64(\n attachment.data,\n attachment.mediaType,\n imageOptions(attachment),\n );\n }\n throw new TypeError(\"Image attachments require a url or base64 data with mediaType.\");\n }\n\n if (attachment.text !== undefined) {\n return {\n type: \"document\",\n source: {\n type: \"text\",\n text: attachment.text,\n ...(attachment.mediaType === undefined ? {} : { mediaType: attachment.mediaType }),\n ...(attachment.name === undefined ? {} : { filename: attachment.name }),\n },\n };\n }\n\n const mediaType = attachment.mediaType ?? \"application/octet-stream\";\n if (attachment.url !== undefined) {\n return UserContent.documentUrl(attachment.url, mediaType, documentOptions(attachment));\n }\n if (attachment.data !== undefined) {\n return UserContent.documentBase64(attachment.data, mediaType, documentOptions(attachment));\n }\n\n throw new TypeError(\"Document attachments require a url, base64 data, or text.\");\n}\n\nfunction userContentToAttachment(content: ImageContent | DocumentContent): UIAttachment {\n if (content.type === \"image\") {\n const attachment: UIAttachment = {\n id: createId(\"attachment\"),\n type: \"image\",\n ...(content.detail === undefined ? {} : { detail: content.detail }),\n };\n if (content.source.type === \"url\") {\n attachment.url = content.source.url;\n } else {\n attachment.data = content.source.data;\n attachment.mediaType = content.source.mediaType;\n }\n return attachment;\n }\n\n const attachment: UIAttachment = {\n id: createId(\"attachment\"),\n type: \"document\",\n };\n if (content.source.type === \"url\") {\n attachment.url = content.source.url;\n attachment.mediaType = content.source.mediaType;\n if (content.source.filename !== undefined) {\n attachment.name = content.source.filename;\n }\n } else if (content.source.type === \"base64\") {\n attachment.data = content.source.data;\n attachment.mediaType = content.source.mediaType;\n if (content.source.filename !== undefined) {\n attachment.name = content.source.filename;\n }\n } else {\n attachment.text = content.source.text;\n if (content.source.mediaType !== undefined) {\n attachment.mediaType = content.source.mediaType;\n }\n if (content.source.filename !== undefined) {\n attachment.name = content.source.filename;\n }\n }\n return attachment;\n}\n\nfunction isImageFileAttachment(attachment: UIAttachment): boolean {\n return attachment.type === \"file\" && attachment.mediaType?.startsWith(\"image/\") === true;\n}\n\nfunction imageOptions(attachment: UIAttachment): { detail?: ImageDetail } {\n return attachment.detail === undefined ? {} : { detail: attachment.detail };\n}\n\nfunction documentOptions(attachment: UIAttachment): { filename?: string } {\n return attachment.name === undefined ? {} : { filename: attachment.name };\n}\n\nfunction toolResultContentToJson(content: ToolResultContent[]): JsonValue {\n if (content.length === 1 && content[0]?.type === \"text\") {\n return content[0].text;\n }\n return content as JsonValue;\n}\n\nfunction isUserContent(value: unknown): value is UserContentType {\n if (!isRecord(value)) {\n return false;\n }\n\n if (value.type === \"text\") {\n return typeof value.text === \"string\";\n }\n\n if (value.type === \"image\") {\n return isImageContent(value);\n }\n\n if (value.type === \"document\") {\n return isDocumentContent(value);\n }\n\n return false;\n}\n\nfunction isImageContent(value: Record<string, unknown>): boolean {\n if (!isRecord(value.source)) {\n return false;\n }\n\n if (value.source.type === \"url\") {\n return typeof value.source.url === \"string\";\n }\n\n if (value.source.type === \"base64\") {\n return typeof value.source.data === \"string\" && typeof value.source.mediaType === \"string\";\n }\n\n return false;\n}\n\nfunction isDocumentContent(value: Record<string, unknown>): boolean {\n if (!isRecord(value.source)) {\n return false;\n }\n\n if (value.source.type === \"url\") {\n return typeof value.source.url === \"string\" && typeof value.source.mediaType === \"string\";\n }\n\n if (value.source.type === \"base64\") {\n return typeof value.source.data === \"string\" && typeof value.source.mediaType === \"string\";\n }\n\n if (value.source.type === \"text\") {\n return (\n typeof value.source.text === \"string\" &&\n (value.source.mediaType === undefined || typeof value.source.mediaType === \"string\")\n );\n }\n\n return false;\n}\n\nfunction toolPartId(toolCallId: string): string {\n return `tool_${toolCallId}`;\n}\n\nlet nextId = 0;\n\nfunction createId(prefix: string): string {\n const random = globalThis.crypto?.randomUUID?.();\n if (random !== undefined) {\n return `${prefix}_${random}`;\n }\n nextId += 1;\n return `${prefix}_${nextId.toString(36)}`;\n}\n\nfunction isUIMessageRole(value: unknown): value is UIMessage[\"role\"] {\n return value === \"system\" || value === \"user\" || value === \"assistant\" || value === \"tool\";\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n"],"mappings":";;;;;;;;;;;AAgCO,SAAS,yBAAyB,UAAsC;AAC7E,QAAM,eAA8B,CAAC;AAErC,aAAW,WAAW,UAAU;AAC9B,UAAM,OAAO,gBAAgB,QAAQ,KAAK;AAE1C,QAAI,QAAQ,SAAS,UAAU;AAC7B,UAAI,KAAK,SAAS,GAAG;AACnB,qBAAa,KAAK,QAAQ,OAAO,MAAM,gBAAgB,QAAQ,QAAQ,CAAC,CAAC;AAAA,MAC3E;AACA;AAAA,IACF;AAEA,QAAI,QAAQ,SAAS,QAAQ;AAC3B,YAAM,UAA6B,CAAC;AACpC,iBAAW,QAAQ,QAAQ,OAAO;AAChC,YAAI,KAAK,SAAS,QAAQ;AACxB,kBAAQ,KAAK,YAAY,KAAK,KAAK,IAAI,CAAC;AACxC;AAAA,QACF;AACA,YAAI,KAAK,SAAS,cAAc;AAC9B,kBAAQ,KAAK,wBAAwB,KAAK,UAAU,CAAC;AACrD;AAAA,QACF;AACA,YAAI,KAAK,SAAS,UAA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WAAO,OAAO,MAAM,OAAO,SAAS,YAAY,OAAO,MAAM,OAAO,cAAc;AAAA,EACpF;AAEA,SAAO;AACT;AAEA,SAAS,kBAAkB,OAAyC;AAClE,MAAI,CAAC,SAAS,MAAM,MAAM,GAAG;AAC3B,WAAO;AAAA,EACT;AAEA,MAAI,MAAM,OAAO,SAAS,OAAO;AAC/B,WAAO,OAAO,MAAM,OAAO,QAAQ,YAAY,OAAO,MAAM,OAAO,cAAc;AAAA,EACnF;AAEA,MAAI,MAAM,OAAO,SAAS,UAAU;AAClC,WAAO,OAAO,MAAM,OAAO,SAAS,YAAY,OAAO,MAAM,OAAO,cAAc;AAAA,EACpF;AAEA,MAAI,MAAM,OAAO,SAAS,QAAQ;AAChC,WACE,OAAO,MAAM,OAAO,SAAS,aAC5B,MAAM,OAAO,cAAc,UAAa,OAAO,MAAM,OAAO,cAAc;AAAA,EAE/E;AAEA,SAAO;AACT;AAEA,SAAS,WAAW,YAA4B;AAC9C,SAAO,QAAQ,UAAU;AAC3B;AAEA,IAAI,SAAS;AAEb,SAAS,SAAS,QAAwB;AACxC,QAAM,SAAS,WAAW,QAAQ,aAAa;AAC/C,MAAI,WAAW,QAAW;AACxB,WAAO,GAAG,MAAM,IAAI,MAAM;AAAA,EAC5B;AACA,YAAU;AACV,SAAO,GAAG,MAAM,IAAI,OAAO,SAAS,EAAE,CAAC;AACzC;AAMA,SAAS,SAAS,OAAkD;AAClE,SAAO,OAAO,UAAU,YAAY,UAAU;AAChD;","names":["toolResults","parts","attachment"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/hooks/control.ts"],"sourcesContent":["import { compact } from \"../internal/compact\";\nimport type {\n HookAction,\n PromptHook,\n RunControl,\n ToolApprovalRequestOptions,\n ToolCallControl,\n ToolCallHookAction,\n} from \"./types\";\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 compact({\n type: \"approval_request\" as const,\n reason: options.reason,\n rejectMessage: options.rejectMessage,\n }) as ToolCallHookAction;\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"],"mappings":";;;;;AAUO,SAAS,WACd,MACyB;AACzB,SAAO;AACT;AAEO,SAAS,aAAa,QAA4B;AACvD,SAAO,EAAE,MAAM,aAAa,OAAO;AACrC;AAEO,SAAS,SAAS,QAAoC;AAC3D,SAAO,EAAE,MAAM,QAAQ,OAAO;AAChC;AAEO,SAAS,oBAAoB,UAAsC,CAAC,GAAuB;AAChG,SAAO,QAAQ;AAAA,IACb,MAAM;AAAA,IACN,QAAQ,QAAQ;AAAA,IAChB,eAAe,QAAQ;AAAA,EACzB,CAAC;AACH;AAEO,IAAM,aAAyB;AAAA,EACpC,WAAW;AACT,WAAO,EAAE,MAAM,WAAW;AAAA,EAC5B;AAAA,EACA,OAAO,QAAgB;AACrB,WAAO,aAAa,MAAM;AAAA,EAC5B;AACF;AAEO,IAAM,kBAAmC;AAAA,EAC9C,MAAM;AACJ,WAAO,EAAE,MAAM,WAAW;AAAA,EAC5B;AAAA,EACA,KAAK,QAAgB;AACnB,WAAO,SAAS,MAAM;AAAA,EACxB;AAAA,EACA,OAAO,QAAgB;AACrB,WAAO,EAAE,MAAM,aAAa,OAAO;AAAA,EACrC;AAAA,EACA,gBAAgB,SAAS;AACvB,WAAO,oBAAoB,OAAO;AAAA,EACpC;AACF;","names":[]}