@tanstack/ai 0.37.0 → 0.39.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/activities/chat/index.js +28 -0
- package/dist/esm/activities/chat/index.js.map +1 -1
- package/dist/esm/activities/chat/mcp/manager.js +10 -1
- package/dist/esm/activities/chat/mcp/manager.js.map +1 -1
- package/dist/esm/activities/chat/mcp/types.d.ts +22 -0
- package/dist/esm/activities/chat/messages.js.map +1 -1
- package/dist/esm/activities/chat/middleware/compose.d.ts +7 -1
- package/dist/esm/activities/chat/middleware/compose.js +27 -0
- package/dist/esm/activities/chat/middleware/compose.js.map +1 -1
- package/dist/esm/activities/chat/middleware/index.d.ts +1 -1
- package/dist/esm/activities/chat/middleware/sandbox-runtime.d.ts +8 -0
- package/dist/esm/activities/chat/middleware/sandbox-runtime.js +9 -0
- package/dist/esm/activities/chat/middleware/sandbox-runtime.js.map +1 -0
- package/dist/esm/activities/chat/middleware/types.d.ts +22 -0
- package/dist/esm/activities/chat/stream/processor.js +23 -0
- package/dist/esm/activities/chat/stream/processor.js.map +1 -1
- package/dist/esm/activities/chat/tools/tool-calls.d.ts +6 -1
- package/dist/esm/activities/chat/tools/tool-calls.js +36 -0
- package/dist/esm/activities/chat/tools/tool-calls.js.map +1 -1
- package/dist/esm/adapter-internals.d.ts +2 -0
- package/dist/esm/adapter-internals.js +4 -0
- package/dist/esm/adapter-internals.js.map +1 -1
- package/dist/esm/client.d.ts +1 -1
- package/dist/esm/client.js.map +1 -1
- package/dist/esm/index.d.ts +2 -2
- package/dist/esm/logger/internal-logger.d.ts +2 -0
- package/dist/esm/logger/internal-logger.js +6 -1
- package/dist/esm/logger/internal-logger.js.map +1 -1
- package/dist/esm/logger/resolve.js +6 -3
- package/dist/esm/logger/resolve.js.map +1 -1
- package/dist/esm/logger/types.d.ts +5 -0
- package/dist/esm/types.d.ts +52 -1
- package/package.json +1 -1
- package/skills/ai-core/adapter-configuration/SKILL.md +25 -12
- package/skills/ai-core/chat-experience/SKILL.md +30 -2
- package/skills/ai-core/media-generation/SKILL.md +13 -0
- package/skills/ai-core/tool-calling/SKILL.md +10 -3
- package/src/activities/chat/index.ts +39 -0
- package/src/activities/chat/mcp/manager.ts +31 -1
- package/src/activities/chat/mcp/types.ts +23 -0
- package/src/activities/chat/messages.ts +5 -0
- package/src/activities/chat/middleware/compose.ts +34 -0
- package/src/activities/chat/middleware/index.ts +2 -0
- package/src/activities/chat/middleware/sandbox-runtime.ts +21 -0
- package/src/activities/chat/middleware/types.ts +37 -0
- package/src/activities/chat/stream/processor.ts +42 -0
- package/src/activities/chat/tools/tool-calls.ts +96 -2
- package/src/adapter-internals.ts +6 -0
- package/src/client.ts +1 -0
- package/src/index.ts +4 -0
- package/src/logger/internal-logger.ts +6 -0
- package/src/logger/resolve.ts +3 -0
- package/src/logger/types.ts +5 -0
- package/src/types.ts +51 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-calls.js","sources":["../../../../../src/activities/chat/tools/tool-calls.ts"],"sourcesContent":["import { normalizeToolResult } from '../../../utilities/tool-result'\nimport { isStandardSchema, parseWithStandardSchema } from './schema-converter'\nimport type {\n AnyTool,\n ContentPart,\n CustomEvent,\n ModelMessage,\n RunFinishedEvent,\n Tool,\n ToolCall,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n ToolCallStartEvent,\n ToolExecutionContext,\n ToolOutputState,\n} from '../../../types'\nimport type {\n AfterToolCallInfo,\n BeforeToolCallDecision,\n} from '../middleware/types'\nimport type {\n ContextFromTool,\n DefinedContext,\n MergeContext,\n UnionToIntersection,\n} from '../runtime-context-types'\n\nfunction safeJsonParse(value: string): unknown {\n try {\n return JSON.parse(value)\n } catch {\n return value\n }\n}\n\n/**\n * Optional middleware hooks for tool execution.\n * When provided, these callbacks are invoked before/after each tool execution.\n */\nexport interface ToolExecutionMiddlewareHooks {\n onBeforeToolCall?: (\n toolCall: ToolCall,\n tool: Tool | undefined,\n args: unknown,\n ) => Promise<BeforeToolCallDecision>\n onAfterToolCall?: (info: AfterToolCallInfo) => Promise<void>\n}\n\n/**\n * Error thrown when middleware decides to abort the chat run during tool execution.\n */\nexport class MiddlewareAbortError extends Error {\n constructor(reason: string) {\n super(reason)\n this.name = 'MiddlewareAbortError'\n }\n}\n\n// The leaf context-inference primitives (ContextFromTool, MergeContext,\n// UnionToIntersection, DefinedContext) are shared with the chat activity\n// options layer — see ../runtime-context-types.\ntype RequiredContextFromToolUnion<T> = T extends unknown\n ? undefined extends ContextFromTool<T>\n ? never\n : ContextFromTool<T>\n : never\n\ntype ContextFromToolUnion<T> = [\n UnionToIntersection<DefinedContext<ContextFromTool<T>>>,\n] extends [never]\n ? unknown\n : [RequiredContextFromToolUnion<T>] extends [never]\n ? UnionToIntersection<DefinedContext<ContextFromTool<T>>> | undefined\n : UnionToIntersection<DefinedContext<ContextFromTool<T>>>\n\ntype ContextFromTools<TTools> = TTools extends readonly [\n infer THead,\n ...infer TTail,\n]\n ? MergeContext<ContextFromTool<THead>, ContextFromTools<TTail>>\n : TTools extends ReadonlyArray<infer TTool>\n ? ContextFromToolUnion<TTool>\n : unknown\n\ntype ExecuteToolsContextArgs<TContext> = undefined extends TContext\n ? [userContext?: TContext]\n : [userContext: TContext]\n\n/**\n * Manages tool call accumulation and execution for the chat() method's automatic tool execution loop.\n *\n * Responsibilities:\n * - Accumulates streaming tool call events (ID, name, arguments)\n * - Validates tool calls (filters out incomplete ones)\n * - Executes tool `execute` functions with parsed arguments\n * - Emits `TOOL_CALL_END` events for client visibility\n * - Returns tool result messages for conversation history\n *\n * This class is used internally by the AI.chat() method to handle the automatic\n * tool execution loop. It can also be used independently for custom tool execution logic.\n *\n * @example\n * ```typescript\n * const manager = new ToolCallManager(tools);\n *\n * // During streaming, accumulate tool calls\n * for await (const chunk of stream) {\n * if (chunk.type === 'TOOL_CALL_START') {\n * manager.addToolCallStartEvent(chunk);\n * } else if (chunk.type === 'TOOL_CALL_ARGS') {\n * manager.addToolCallArgsEvent(chunk);\n * }\n * }\n *\n * // After stream completes, execute tools\n * if (manager.hasToolCalls()) {\n * const toolResults = yield* manager.executeTools(finishEvent);\n * messages = [...messages, ...toolResults];\n * manager.clear();\n * }\n * ```\n */\nexport class ToolCallManager<\n TToolsOrContext = ReadonlyArray<AnyTool>,\n TContext = TToolsOrContext extends ReadonlyArray<AnyTool>\n ? ContextFromTools<TToolsOrContext>\n : TToolsOrContext,\n> {\n private readonly toolCallsMap = new Map<number, ToolCall>()\n private readonly tools: TToolsOrContext extends ReadonlyArray<AnyTool>\n ? TToolsOrContext\n : ReadonlyArray<AnyTool>\n\n constructor(\n tools: TToolsOrContext extends ReadonlyArray<AnyTool>\n ? TToolsOrContext\n : ReadonlyArray<AnyTool>,\n ) {\n this.tools = tools\n }\n\n /**\n * Add a TOOL_CALL_START event to begin tracking a tool call (AG-UI)\n */\n addToolCallStartEvent(event: ToolCallStartEvent): void {\n const index = event.index ?? this.toolCallsMap.size\n const runtimeEvent = event as Partial<ToolCallStartEvent> &\n Pick<ToolCallStartEvent, 'toolName'>\n const name = runtimeEvent.toolCallName ?? runtimeEvent.toolName\n this.toolCallsMap.set(index, {\n id: event.toolCallId,\n type: 'function',\n function: {\n name,\n arguments: '',\n },\n ...(event.metadata !== undefined && { metadata: event.metadata }),\n })\n }\n\n /**\n * Add a TOOL_CALL_ARGS event to accumulate arguments (AG-UI)\n */\n addToolCallArgsEvent(event: ToolCallArgsEvent): void {\n // Find the tool call by ID\n for (const [, toolCall] of this.toolCallsMap.entries()) {\n if (toolCall.id === event.toolCallId) {\n toolCall.function.arguments += event.delta\n break\n }\n }\n }\n\n /**\n * Complete a tool call with its final input\n * Called when TOOL_CALL_END is received\n */\n completeToolCall(event: ToolCallEndEvent): void {\n for (const [, toolCall] of this.toolCallsMap.entries()) {\n if (toolCall.id === event.toolCallId) {\n if (event.input !== undefined) {\n // Normalize null/non-object to {} (e.g. Anthropic empty tool_use blocks)\n const normalized =\n event.input && typeof event.input === 'object' ? event.input : {}\n toolCall.function.arguments = JSON.stringify(normalized)\n }\n break\n }\n }\n }\n\n /**\n * Check if there are any complete tool calls to execute\n */\n hasToolCalls(): boolean {\n return this.getToolCalls().length > 0\n }\n\n /**\n * Get all complete tool calls (filtered for valid ID and name)\n */\n getToolCalls(): Array<ToolCall> {\n return Array.from(this.toolCallsMap.values()).filter(\n (tc) => tc.id && tc.function.name && tc.function.name.trim().length > 0,\n )\n }\n\n /**\n * Execute all tool calls and return tool result messages\n * Yields TOOL_CALL_END events for streaming\n * @param finishEvent - RUN_FINISHED event from the stream\n */\n async *executeTools(\n finishEvent: RunFinishedEvent,\n ...contextArgs: ExecuteToolsContextArgs<TContext>\n ): AsyncGenerator<ToolCallEndEvent, Array<ModelMessage>, void> {\n const toolCallsArray = this.getToolCalls()\n const toolResults: Array<ModelMessage> = []\n const hasRuntimeContext = contextArgs.length > 0\n const userContext = contextArgs[0]\n\n for (const toolCall of toolCallsArray) {\n const tool = this.tools.find((t) => t.name === toolCall.function.name)\n\n let toolResultContent: string | Array<ContentPart>\n let toolResultState: ToolOutputState | undefined\n if (tool?.execute) {\n try {\n // Parse arguments (normalize null/non-object to {} for empty tool_use blocks)\n let args: unknown\n try {\n const argsString = toolCall.function.arguments.trim() || '{}'\n const parsed = JSON.parse(argsString)\n args = parsed && typeof parsed === 'object' ? parsed : {}\n } catch (parseError) {\n throw new Error(\n `Failed to parse tool arguments as JSON: ${toolCall.function.arguments}`,\n )\n }\n\n // Validate input against inputSchema (for Standard Schema compliant schemas)\n if (tool.inputSchema && isStandardSchema(tool.inputSchema)) {\n try {\n args = parseWithStandardSchema(tool.inputSchema, args)\n } catch (validationError: unknown) {\n const message =\n validationError instanceof Error\n ? validationError.message\n : 'Validation failed'\n throw new Error(\n `Input validation failed for tool ${tool.name}: ${message}`,\n )\n }\n }\n\n // Execute the tool\n const executionContext = {\n toolCallId: toolCall.id,\n context: userContext,\n emitCustomEvent: () => {},\n } as ToolExecutionContext<TContext>\n let result = hasRuntimeContext\n ? await tool.execute(args, executionContext)\n : await tool.execute(args)\n\n // Validate output against outputSchema if provided (for Standard\n // Schema compliant schemas). Unlike the previous implementation we\n // intentionally validate `undefined`/`null` results too, so a tool\n // whose schema forbids them surfaces a validation error instead of\n // silently passing — the schema itself decides whether they're valid.\n if (tool.outputSchema && isStandardSchema(tool.outputSchema)) {\n try {\n result = parseWithStandardSchema(tool.outputSchema, result)\n } catch (validationError: unknown) {\n const message =\n validationError instanceof Error\n ? validationError.message\n : 'Validation failed'\n throw new Error(\n `Output validation failed for tool ${tool.name}: ${message}`,\n )\n }\n }\n\n toolResultContent = normalizeToolResult(result)\n } catch (error: unknown) {\n // If tool execution fails, add error message\n const message =\n error instanceof Error ? error.message : 'Unknown error'\n toolResultContent = `Error executing tool: ${message}`\n toolResultState = 'output-error'\n }\n } else {\n // Tool doesn't have execute function, add placeholder\n toolResultContent = `Tool ${toolCall.function.name} does not have an execute function`\n }\n\n // Emit TOOL_CALL_END event\n yield {\n type: 'TOOL_CALL_END',\n toolCallId: toolCall.id,\n toolCallName: toolCall.function.name,\n toolName: toolCall.function.name,\n model: finishEvent.model,\n timestamp: Date.now(),\n result: toolResultContent,\n ...(toolResultState !== undefined && { state: toolResultState }),\n } as ToolCallEndEvent\n\n // Add tool result message\n toolResults.push({\n role: 'tool',\n content: toolResultContent,\n toolCallId: toolCall.id,\n })\n }\n\n return toolResults\n }\n\n /**\n * Clear the tool calls map for the next iteration\n */\n clear(): void {\n this.toolCallsMap.clear()\n }\n}\n\nexport interface ToolResult {\n toolCallId: string\n toolName: string\n result: any\n state?: 'output-available' | 'output-error'\n /** Duration of tool execution in milliseconds (only for server-executed tools) */\n duration?: number\n}\n\nexport interface ApprovalRequest {\n toolCallId: string\n toolName: string\n input: any\n approvalId: string\n}\n\nexport interface ClientToolRequest {\n toolCallId: string\n toolName: string\n input: any\n}\n\ninterface ExecuteToolCallsResult {\n /** Tool results ready to send to LLM */\n results: Array<ToolResult>\n /** Tools that need user approval before execution */\n needsApproval: Array<ApprovalRequest>\n /** Tools that need client-side execution */\n needsClientExecution: Array<ClientToolRequest>\n}\n\n/**\n * Helper that runs a tool execution promise while polling for pending custom events.\n * Yields any custom events that are emitted during execution, then returns the\n * execution result.\n */\nasync function* executeWithEventPolling<T>(\n executionPromise: Promise<T>,\n pendingEvents: Array<CustomEvent>,\n): AsyncGenerator<CustomEvent, T, void> {\n // Use an object to track mutable state across the async boundary\n const state = { done: false, result: undefined as T }\n const executionWithFlag = executionPromise.then((r) => {\n state.done = true\n state.result = r\n return r\n })\n\n while (!state.done) {\n // Wait for either the execution to complete or a short timeout\n await Promise.race([\n executionWithFlag,\n new Promise((resolve) => setTimeout(resolve, 10)),\n ])\n\n // Flush any pending events\n let event: CustomEvent | undefined\n while ((event = pendingEvents.shift()) !== undefined) {\n yield event\n }\n }\n\n // Final flush in case events were emitted right at completion\n let event: CustomEvent | undefined\n while ((event = pendingEvents.shift()) !== undefined) {\n yield event\n }\n\n return state.result\n}\n\n/**\n * Apply a middleware onBeforeToolCall decision.\n * Returns the (possibly transformed) input if execution should proceed,\n * or undefined if the tool call was skipped (result already pushed).\n * Throws MiddlewareAbortError if the decision is 'abort'.\n */\nasync function applyBeforeToolCallDecision(\n toolCall: ToolCall,\n tool: Tool,\n input: unknown,\n toolName: string,\n middlewareHooks: ToolExecutionMiddlewareHooks,\n results: Array<ToolResult>,\n): Promise<{ proceed: true; input: unknown } | { proceed: false }> {\n if (!middlewareHooks.onBeforeToolCall) {\n return { proceed: true, input }\n }\n\n const decision = await middlewareHooks.onBeforeToolCall(toolCall, tool, input)\n if (!decision) {\n return { proceed: true, input }\n }\n\n if (decision.type === 'abort') {\n throw new MiddlewareAbortError(decision.reason || 'Aborted by middleware')\n }\n\n if (decision.type === 'skip') {\n const skipResult = decision.result\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result:\n typeof skipResult === 'string'\n ? safeJsonParse(skipResult)\n : (skipResult ?? null),\n duration: 0,\n })\n if (middlewareHooks.onAfterToolCall) {\n await middlewareHooks.onAfterToolCall({\n toolCall,\n tool,\n toolName,\n toolCallId: toolCall.id,\n ok: true,\n duration: 0,\n result: skipResult,\n })\n }\n return { proceed: false }\n }\n\n return { proceed: true, input: decision.args }\n}\n\n/**\n * Execute a server-side tool with event polling, output validation, and middleware hooks.\n * Yields CustomEvent chunks during execution and pushes the result to the results array.\n */\nasync function* executeServerTool<TContext = unknown>(\n toolCall: ToolCall,\n tool: AnyTool,\n toolName: string,\n input: unknown,\n context: ToolExecutionContext<TContext>,\n pendingEvents: Array<CustomEvent>,\n results: Array<ToolResult>,\n middlewareHooks?: ToolExecutionMiddlewareHooks,\n): AsyncGenerator<CustomEvent, void, void> {\n const startTime = Date.now()\n try {\n if (!tool.execute) {\n throw new Error(`Tool ${toolName} has no execute() implementation`)\n }\n const executionPromise = Promise.resolve(tool.execute(input, context))\n let result = yield* executeWithEventPolling(executionPromise, pendingEvents)\n const duration = Date.now() - startTime\n\n // Flush remaining events\n let pendingEvent: CustomEvent | undefined\n while ((pendingEvent = pendingEvents.shift()) !== undefined) {\n yield pendingEvent\n }\n\n // Validate output against outputSchema if provided. Validates\n // `undefined`/`null` too — the schema decides whether they're valid.\n if (tool.outputSchema && isStandardSchema(tool.outputSchema)) {\n result = parseWithStandardSchema(tool.outputSchema, result)\n }\n\n const finalResult =\n typeof result === 'string' ? safeJsonParse(result) : (result ?? null)\n\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result: finalResult,\n duration,\n })\n\n if (middlewareHooks?.onAfterToolCall) {\n await middlewareHooks.onAfterToolCall({\n toolCall,\n tool,\n toolName,\n toolCallId: toolCall.id,\n ok: true,\n duration,\n result: finalResult,\n })\n }\n } catch (error: unknown) {\n const duration = Date.now() - startTime\n\n // Flush remaining events\n let pendingEvent: CustomEvent | undefined\n while ((pendingEvent = pendingEvents.shift()) !== undefined) {\n yield pendingEvent\n }\n\n if (error instanceof MiddlewareAbortError) {\n throw error\n }\n\n const message = error instanceof Error ? error.message : 'Unknown error'\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result: { error: message },\n state: 'output-error',\n duration,\n })\n\n if (middlewareHooks?.onAfterToolCall) {\n await middlewareHooks.onAfterToolCall({\n toolCall,\n tool,\n toolName,\n toolCallId: toolCall.id,\n ok: false,\n duration,\n error,\n })\n }\n }\n}\n\nfunction buildClientToolResult(\n toolCallId: string,\n toolName: string,\n tool: AnyTool,\n rawResult: unknown,\n): ToolResult {\n try {\n let result = rawResult\n if (tool.outputSchema && isStandardSchema(tool.outputSchema)) {\n result = parseWithStandardSchema(tool.outputSchema, result)\n }\n\n return {\n toolCallId,\n toolName,\n result:\n typeof result === 'string' ? safeJsonParse(result) : (result ?? null),\n }\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : 'Validation failed'\n return {\n toolCallId,\n toolName,\n result: { error: message },\n state: 'output-error',\n }\n }\n}\n\n/**\n * Execute tool calls based on their configuration.\n * Yields CustomEvent chunks during tool execution for real-time progress updates.\n *\n * Handles three cases:\n * 1. Client tools (no execute) - request client to execute\n * 2. Server tools with approval - check approval before executing\n * 3. Normal server tools - execute immediately\n *\n * @param toolCalls - Tool calls from the LLM\n * @param tools - Available tools with their configurations\n * @param approvals - Map of approval decisions (approval.id -> approved boolean)\n * @param clientResults - Map of client-side execution results (toolCallId -> result)\n * @param createCustomEventChunk - Factory to create CustomEvent chunks (optional)\n */\nexport async function* executeToolCalls<TContext = unknown>(\n toolCalls: Array<ToolCall>,\n tools: ReadonlyArray<AnyTool>,\n approvals: Map<string, boolean> = new Map(),\n clientResults: Map<string, any> = new Map(),\n createCustomEventChunk?: (\n eventName: string,\n value: Record<string, any>,\n ) => CustomEvent,\n middlewareHooks?: ToolExecutionMiddlewareHooks,\n userContext?: TContext,\n abortSignal?: AbortSignal,\n): AsyncGenerator<CustomEvent, ExecuteToolCallsResult, void> {\n const results: Array<ToolResult> = []\n const needsApproval: Array<ApprovalRequest> = []\n const needsClientExecution: Array<ClientToolRequest> = []\n\n // Create tool lookup map\n const toolMap = new Map<string, AnyTool>()\n for (const tool of tools) {\n toolMap.set(tool.name, tool)\n }\n\n // Batch gating: when any tool in the batch still needs an approval decision,\n // defer all execution so side effects don't happen before the user decides.\n const hasPendingApprovals = toolCalls.some((tc) => {\n const t = toolMap.get(tc.function.name)\n return t?.needsApproval && !approvals.has(`approval_${tc.id}`)\n })\n\n for (const toolCall of toolCalls) {\n const tool = toolMap.get(toolCall.function.name)\n const toolName = toolCall.function.name\n\n if (!tool) {\n // Unknown tool - return error\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result: { error: `Unknown tool: ${toolName}` },\n state: 'output-error',\n })\n continue\n }\n\n // Skip non-pending tools while approvals are outstanding\n if (hasPendingApprovals) {\n if (!tool.needsApproval || approvals.has(`approval_${toolCall.id}`)) {\n continue\n }\n }\n\n // Parse arguments, throwing error if invalid JSON\n let input: unknown = {}\n const argsStr = toolCall.function.arguments.trim() || '{}'\n if (argsStr) {\n try {\n const parsed = JSON.parse(argsStr)\n // Normalize null/non-object to {} (e.g. Anthropic empty tool_use blocks)\n input = parsed && typeof parsed === 'object' ? parsed : {}\n } catch (parseError) {\n // If parsing fails, throw error to fail fast\n throw new Error(`Failed to parse tool arguments as JSON: ${argsStr}`)\n }\n }\n\n // Validate input against inputSchema (for Standard Schema compliant schemas)\n if (tool.inputSchema && isStandardSchema(tool.inputSchema)) {\n try {\n input = parseWithStandardSchema(tool.inputSchema, input)\n } catch (validationError: unknown) {\n const message =\n validationError instanceof Error\n ? validationError.message\n : 'Validation failed'\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result: {\n error: `Input validation failed for tool ${tool.name}: ${message}`,\n },\n state: 'output-error',\n })\n continue\n }\n }\n\n // Create a ToolExecutionContext for this tool call with event emission\n const pendingEvents: Array<CustomEvent> = []\n const context = {\n toolCallId: toolCall.id,\n context: userContext,\n abortSignal,\n emitCustomEvent: (eventName: string, value: Record<string, any>) => {\n if (createCustomEventChunk) {\n pendingEvents.push(\n createCustomEventChunk(eventName, {\n ...value,\n toolCallId: toolCall.id,\n }),\n )\n }\n },\n } as ToolExecutionContext<TContext>\n\n // CASE 1: Client-side tool (no execute function)\n if (!tool.execute) {\n // Check if tool needs approval\n if (tool.needsApproval) {\n const approvalId = `approval_${toolCall.id}`\n\n // Check if approval decision exists\n if (approvals.has(approvalId)) {\n const approved = approvals.get(approvalId)\n\n if (approved) {\n // Approved - check if client has executed\n if (clientResults.has(toolCall.id)) {\n results.push(\n buildClientToolResult(\n toolCall.id,\n toolName,\n tool,\n clientResults.get(toolCall.id),\n ),\n )\n } else {\n // Approved but not executed yet - request client execution\n needsClientExecution.push({\n toolCallId: toolCall.id,\n toolName,\n input,\n })\n }\n } else {\n // User declined\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result: { error: 'User declined tool execution' },\n state: 'output-error',\n })\n }\n } else {\n // Need approval first\n needsApproval.push({\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n input,\n approvalId,\n })\n }\n } else {\n // No approval needed - check if client has executed\n if (clientResults.has(toolCall.id)) {\n results.push(\n buildClientToolResult(\n toolCall.id,\n toolName,\n tool,\n clientResults.get(toolCall.id),\n ),\n )\n } else {\n // Request client execution\n needsClientExecution.push({\n toolCallId: toolCall.id,\n toolName,\n input,\n })\n }\n }\n continue\n }\n\n // CASE 2: Server tool with approval required\n if (tool.needsApproval) {\n const approvalId = `approval_${toolCall.id}`\n\n // Check if approval decision exists\n if (approvals.has(approvalId)) {\n const approved = approvals.get(approvalId)\n\n if (approved) {\n // Apply middleware before-hook for approved tools\n if (middlewareHooks) {\n const decision = await applyBeforeToolCallDecision(\n toolCall,\n tool,\n input,\n toolName,\n middlewareHooks,\n results,\n )\n if (!decision.proceed) continue\n input = decision.input\n }\n\n yield* executeServerTool(\n toolCall,\n tool,\n toolName,\n input,\n context,\n pendingEvents,\n results,\n middlewareHooks,\n )\n } else {\n // User declined\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result: { error: 'User declined tool execution' },\n state: 'output-error',\n })\n }\n } else {\n // Need approval\n needsApproval.push({\n toolCallId: toolCall.id,\n toolName,\n input,\n approvalId,\n })\n }\n continue\n }\n\n // CASE 3: Normal server tool - execute immediately\n if (middlewareHooks) {\n const decision = await applyBeforeToolCallDecision(\n toolCall,\n tool,\n input,\n toolName,\n middlewareHooks,\n results,\n )\n if (!decision.proceed) continue\n input = decision.input\n }\n\n yield* executeServerTool(\n toolCall,\n tool,\n toolName,\n input,\n context,\n pendingEvents,\n results,\n middlewareHooks,\n )\n }\n\n return { results, needsApproval, needsClientExecution }\n}\n"],"names":["event"],"mappings":";;AA2BA,SAAS,cAAc,OAAwB;AAC7C,MAAI;AACF,WAAO,KAAK,MAAM,KAAK;AAAA,EACzB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAkBO,MAAM,6BAA6B,MAAM;AAAA,EAC9C,YAAY,QAAgB;AAC1B,UAAM,MAAM;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAkEO,MAAM,gBAKX;AAAA,EACiB,mCAAmB,IAAA;AAAA,EACnB;AAAA,EAIjB,YACE,OAGA;AACA,SAAK,QAAQ;AAAA,EACf;AAAA;AAAA;AAAA;AAAA,EAKA,sBAAsB,OAAiC;AACrD,UAAM,QAAQ,MAAM,SAAS,KAAK,aAAa;AAC/C,UAAM,eAAe;AAErB,UAAM,OAAO,aAAa,gBAAgB,aAAa;AACvD,SAAK,aAAa,IAAI,OAAO;AAAA,MAC3B,IAAI,MAAM;AAAA,MACV,MAAM;AAAA,MACN,UAAU;AAAA,QACR;AAAA,QACA,WAAW;AAAA,MAAA;AAAA,MAEb,GAAI,MAAM,aAAa,UAAa,EAAE,UAAU,MAAM,SAAA;AAAA,IAAS,CAChE;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKA,qBAAqB,OAAgC;AAEnD,eAAW,CAAA,EAAG,QAAQ,KAAK,KAAK,aAAa,WAAW;AACtD,UAAI,SAAS,OAAO,MAAM,YAAY;AACpC,iBAAS,SAAS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C,SAAS,QAAS;AACvB,cAAQ,SAAS;AAAA,IACnB;AAEA,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,EAEJ;AAEA,SAAO,EAAE,SAAS,eAAe,qBAAA;AACnC;"}
|
|
1
|
+
{"version":3,"file":"tool-calls.js","sources":["../../../../../src/activities/chat/tools/tool-calls.ts"],"sourcesContent":["import { normalizeToolResult } from '../../../utilities/tool-result'\nimport { isStandardSchema, parseWithStandardSchema } from './schema-converter'\nimport type {\n AnyTool,\n ContentPart,\n CustomEvent,\n ModelMessage,\n RunFinishedEvent,\n Tool,\n ToolCall,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n ToolCallStartEvent,\n ToolExecutionContext,\n ToolOutputState,\n} from '../../../types'\nimport type {\n AfterToolCallInfo,\n BeforeToolCallDecision,\n} from '../middleware/types'\nimport type { McpResourceReadResult } from '../mcp/types'\nimport type {\n ContextFromTool,\n DefinedContext,\n MergeContext,\n UnionToIntersection,\n} from '../runtime-context-types'\n\nfunction safeJsonParse(value: string): unknown {\n try {\n return JSON.parse(value)\n } catch {\n return value\n }\n}\n\n/**\n * MCP Apps metadata attached to a server tool at discovery (see\n * `@tanstack/ai-mcp` discovery + `MCPManager.discover()`).\n *\n * - `uiResourceUri` / `serverId` are stamped by ai-mcp at tool discovery.\n * - `readResource` is bound by `MCPManager.discover()` (the one site that has\n * both the tool and its originating source) so the resource can be eagerly\n * read at the emit site. Under `chat()`-managed MCP lifecycle\n * (`connection:'close'`), the MCP source is not disposed until the run\n * drains, so `readResource` is still live at this emit point. Note: a caller\n * who closes the MCP source early (outside `chat()`'s managed lifecycle)\n * degrades fail-soft — `readResource` may reject, the widget is absent, but\n * the tool result still flows to the model.\n * `@tanstack/ai` never imports `@tanstack/ai-mcp`; this travels structurally\n * on the tool.\n */\ninterface McpToolAppMeta {\n uiResourceUri?: string\n serverId?: string\n /** Server-native (unprefixed) MCP tool name — used as the renderer's toolName. */\n serverToolName?: string\n readResource?: (uri: string) => Promise<McpResourceReadResult>\n}\n\nfunction readMcpAppMeta(tool: AnyTool): McpToolAppMeta | undefined {\n const meta = (tool.metadata as { mcp?: McpToolAppMeta } | undefined)?.mcp\n return meta\n}\n\n/**\n * Eagerly read a tool's linked `ui://` resource (MCP Apps) and emit a\n * `ui-resource` CUSTOM event so the client can render the widget. The model\n * still receives the normal text tool-result; the widget rides alongside and\n * never enters model input.\n *\n * Fail-soft: any read error logs a warning and emits nothing — it never throws,\n * so the normal tool-result still flows and a broken widget cannot break the run.\n */\nasync function emitUiResourceIfLinked<TContext>(\n tool: AnyTool,\n context: ToolExecutionContext<TContext>,\n): Promise<void> {\n const mcp = readMcpAppMeta(tool)\n const uiUri = mcp?.uiResourceUri\n if (!uiUri || !mcp.readResource) return\n\n // The try covers ONLY the fallible read — keep `emitCustomEvent` out of it so\n // an exception from the emit path can't be mislabeled as a read failure.\n let matched: McpResourceReadResult['contents'][number] | undefined\n try {\n const res = await mcp.readResource(uiUri)\n // Emit ONLY the content whose uri matches the requested `uiUri`. A source\n // can return unrelated contents; falling back to `contents[0]` would risk\n // rendering a widget that doesn't correspond to the linked resource. This\n // is a display widget — a mismatched resource is worse than none, so if no\n // content matches we fail-soft (warn + return) rather than emit.\n matched = res.contents.find((c) => c.uri === uiUri)\n } catch (err) {\n // fail-soft — the text tool-result already flows; a broken widget must\n // not break the run.\n console.warn(`[mcp-apps] failed to read ui resource ${uiUri}:`, err)\n return\n }\n if (!matched) {\n console.warn(\n `[mcp-apps] ui resource ${uiUri} returned no content matching that uri; not emitting`,\n )\n return\n }\n // NOTE: `toolCallId` is intentionally NOT set here — it is stamped onto\n // every emitted event by the `executeToolCalls` context wrapper, so the\n // UIResourceEvent.value.toolCallId / UIResourcePart.toolCallId contract is\n // still satisfied downstream.\n context.emitCustomEvent('ui-resource', {\n resource: {\n uri: matched.uri,\n mimeType: matched.mimeType ?? 'text/html',\n text: matched.text,\n blob: matched.blob,\n },\n serverId: mcp.serverId,\n toolName: mcp.serverToolName ?? tool.name,\n meta: undefined,\n })\n}\n\n/**\n * Optional middleware hooks for tool execution.\n * When provided, these callbacks are invoked before/after each tool execution.\n */\nexport interface ToolExecutionMiddlewareHooks {\n onBeforeToolCall?: (\n toolCall: ToolCall,\n tool: Tool | undefined,\n args: unknown,\n ) => Promise<BeforeToolCallDecision>\n onAfterToolCall?: (info: AfterToolCallInfo) => Promise<void>\n}\n\n/**\n * Error thrown when middleware decides to abort the chat run during tool execution.\n */\nexport class MiddlewareAbortError extends Error {\n constructor(reason: string) {\n super(reason)\n this.name = 'MiddlewareAbortError'\n }\n}\n\n// The leaf context-inference primitives (ContextFromTool, MergeContext,\n// UnionToIntersection, DefinedContext) are shared with the chat activity\n// options layer — see ../runtime-context-types.\ntype RequiredContextFromToolUnion<T> = T extends unknown\n ? undefined extends ContextFromTool<T>\n ? never\n : ContextFromTool<T>\n : never\n\ntype ContextFromToolUnion<T> = [\n UnionToIntersection<DefinedContext<ContextFromTool<T>>>,\n] extends [never]\n ? unknown\n : [RequiredContextFromToolUnion<T>] extends [never]\n ? UnionToIntersection<DefinedContext<ContextFromTool<T>>> | undefined\n : UnionToIntersection<DefinedContext<ContextFromTool<T>>>\n\ntype ContextFromTools<TTools> = TTools extends readonly [\n infer THead,\n ...infer TTail,\n]\n ? MergeContext<ContextFromTool<THead>, ContextFromTools<TTail>>\n : TTools extends ReadonlyArray<infer TTool>\n ? ContextFromToolUnion<TTool>\n : unknown\n\ntype ExecuteToolsContextArgs<TContext> = undefined extends TContext\n ? [userContext?: TContext]\n : [userContext: TContext]\n\n/**\n * Manages tool call accumulation and execution for the chat() method's automatic tool execution loop.\n *\n * Responsibilities:\n * - Accumulates streaming tool call events (ID, name, arguments)\n * - Validates tool calls (filters out incomplete ones)\n * - Executes tool `execute` functions with parsed arguments\n * - Emits `TOOL_CALL_END` events for client visibility\n * - Returns tool result messages for conversation history\n *\n * This class is used internally by the AI.chat() method to handle the automatic\n * tool execution loop. It can also be used independently for custom tool execution logic.\n *\n * @example\n * ```typescript\n * const manager = new ToolCallManager(tools);\n *\n * // During streaming, accumulate tool calls\n * for await (const chunk of stream) {\n * if (chunk.type === 'TOOL_CALL_START') {\n * manager.addToolCallStartEvent(chunk);\n * } else if (chunk.type === 'TOOL_CALL_ARGS') {\n * manager.addToolCallArgsEvent(chunk);\n * }\n * }\n *\n * // After stream completes, execute tools\n * if (manager.hasToolCalls()) {\n * const toolResults = yield* manager.executeTools(finishEvent);\n * messages = [...messages, ...toolResults];\n * manager.clear();\n * }\n * ```\n */\nexport class ToolCallManager<\n TToolsOrContext = ReadonlyArray<AnyTool>,\n TContext = TToolsOrContext extends ReadonlyArray<AnyTool>\n ? ContextFromTools<TToolsOrContext>\n : TToolsOrContext,\n> {\n private readonly toolCallsMap = new Map<number, ToolCall>()\n private readonly tools: TToolsOrContext extends ReadonlyArray<AnyTool>\n ? TToolsOrContext\n : ReadonlyArray<AnyTool>\n\n constructor(\n tools: TToolsOrContext extends ReadonlyArray<AnyTool>\n ? TToolsOrContext\n : ReadonlyArray<AnyTool>,\n ) {\n this.tools = tools\n }\n\n /**\n * Add a TOOL_CALL_START event to begin tracking a tool call (AG-UI)\n */\n addToolCallStartEvent(event: ToolCallStartEvent): void {\n const index = event.index ?? this.toolCallsMap.size\n const runtimeEvent = event as Partial<ToolCallStartEvent> &\n Pick<ToolCallStartEvent, 'toolName'>\n const name = runtimeEvent.toolCallName ?? runtimeEvent.toolName\n this.toolCallsMap.set(index, {\n id: event.toolCallId,\n type: 'function',\n function: {\n name,\n arguments: '',\n },\n ...(event.metadata !== undefined && { metadata: event.metadata }),\n })\n }\n\n /**\n * Add a TOOL_CALL_ARGS event to accumulate arguments (AG-UI)\n */\n addToolCallArgsEvent(event: ToolCallArgsEvent): void {\n // Find the tool call by ID\n for (const [, toolCall] of this.toolCallsMap.entries()) {\n if (toolCall.id === event.toolCallId) {\n toolCall.function.arguments += event.delta\n break\n }\n }\n }\n\n /**\n * Complete a tool call with its final input\n * Called when TOOL_CALL_END is received\n */\n completeToolCall(event: ToolCallEndEvent): void {\n for (const [, toolCall] of this.toolCallsMap.entries()) {\n if (toolCall.id === event.toolCallId) {\n if (event.input !== undefined) {\n // Normalize null/non-object to {} (e.g. Anthropic empty tool_use blocks)\n const normalized =\n event.input && typeof event.input === 'object' ? event.input : {}\n toolCall.function.arguments = JSON.stringify(normalized)\n }\n break\n }\n }\n }\n\n /**\n * Check if there are any complete tool calls to execute\n */\n hasToolCalls(): boolean {\n return this.getToolCalls().length > 0\n }\n\n /**\n * Get all complete tool calls (filtered for valid ID and name)\n */\n getToolCalls(): Array<ToolCall> {\n return Array.from(this.toolCallsMap.values()).filter(\n (tc) => tc.id && tc.function.name && tc.function.name.trim().length > 0,\n )\n }\n\n /**\n * Execute all tool calls and return tool result messages\n * Yields TOOL_CALL_END events for streaming\n * @param finishEvent - RUN_FINISHED event from the stream\n */\n async *executeTools(\n finishEvent: RunFinishedEvent,\n ...contextArgs: ExecuteToolsContextArgs<TContext>\n ): AsyncGenerator<ToolCallEndEvent, Array<ModelMessage>, void> {\n const toolCallsArray = this.getToolCalls()\n const toolResults: Array<ModelMessage> = []\n const hasRuntimeContext = contextArgs.length > 0\n const userContext = contextArgs[0]\n\n for (const toolCall of toolCallsArray) {\n const tool = this.tools.find((t) => t.name === toolCall.function.name)\n\n let toolResultContent: string | Array<ContentPart>\n let toolResultState: ToolOutputState | undefined\n if (tool?.execute) {\n try {\n // Parse arguments (normalize null/non-object to {} for empty tool_use blocks)\n let args: unknown\n try {\n const argsString = toolCall.function.arguments.trim() || '{}'\n const parsed = JSON.parse(argsString)\n args = parsed && typeof parsed === 'object' ? parsed : {}\n } catch (parseError) {\n throw new Error(\n `Failed to parse tool arguments as JSON: ${toolCall.function.arguments}`,\n )\n }\n\n // Validate input against inputSchema (for Standard Schema compliant schemas)\n if (tool.inputSchema && isStandardSchema(tool.inputSchema)) {\n try {\n args = parseWithStandardSchema(tool.inputSchema, args)\n } catch (validationError: unknown) {\n const message =\n validationError instanceof Error\n ? validationError.message\n : 'Validation failed'\n throw new Error(\n `Input validation failed for tool ${tool.name}: ${message}`,\n )\n }\n }\n\n // Execute the tool\n const executionContext = {\n toolCallId: toolCall.id,\n context: userContext,\n emitCustomEvent: () => {},\n } as ToolExecutionContext<TContext>\n let result = hasRuntimeContext\n ? await tool.execute(args, executionContext)\n : await tool.execute(args)\n\n // Validate output against outputSchema if provided (for Standard\n // Schema compliant schemas). Unlike the previous implementation we\n // intentionally validate `undefined`/`null` results too, so a tool\n // whose schema forbids them surfaces a validation error instead of\n // silently passing — the schema itself decides whether they're valid.\n if (tool.outputSchema && isStandardSchema(tool.outputSchema)) {\n try {\n result = parseWithStandardSchema(tool.outputSchema, result)\n } catch (validationError: unknown) {\n const message =\n validationError instanceof Error\n ? validationError.message\n : 'Validation failed'\n throw new Error(\n `Output validation failed for tool ${tool.name}: ${message}`,\n )\n }\n }\n\n toolResultContent = normalizeToolResult(result)\n } catch (error: unknown) {\n // If tool execution fails, add error message\n const message =\n error instanceof Error ? error.message : 'Unknown error'\n toolResultContent = `Error executing tool: ${message}`\n toolResultState = 'output-error'\n }\n } else {\n // Tool doesn't have execute function, add placeholder\n toolResultContent = `Tool ${toolCall.function.name} does not have an execute function`\n }\n\n // Emit TOOL_CALL_END event\n yield {\n type: 'TOOL_CALL_END',\n toolCallId: toolCall.id,\n toolCallName: toolCall.function.name,\n toolName: toolCall.function.name,\n model: finishEvent.model,\n timestamp: Date.now(),\n result: toolResultContent,\n ...(toolResultState !== undefined && { state: toolResultState }),\n } as ToolCallEndEvent\n\n // Add tool result message\n toolResults.push({\n role: 'tool',\n content: toolResultContent,\n toolCallId: toolCall.id,\n })\n }\n\n return toolResults\n }\n\n /**\n * Clear the tool calls map for the next iteration\n */\n clear(): void {\n this.toolCallsMap.clear()\n }\n}\n\nexport interface ToolResult {\n toolCallId: string\n toolName: string\n result: any\n state?: 'output-available' | 'output-error'\n /** Duration of tool execution in milliseconds (only for server-executed tools) */\n duration?: number\n}\n\nexport interface ApprovalRequest {\n toolCallId: string\n toolName: string\n input: any\n approvalId: string\n}\n\nexport interface ClientToolRequest {\n toolCallId: string\n toolName: string\n input: any\n}\n\ninterface ExecuteToolCallsResult {\n /** Tool results ready to send to LLM */\n results: Array<ToolResult>\n /** Tools that need user approval before execution */\n needsApproval: Array<ApprovalRequest>\n /** Tools that need client-side execution */\n needsClientExecution: Array<ClientToolRequest>\n}\n\n/**\n * Helper that runs a tool execution promise while polling for pending custom events.\n * Yields any custom events that are emitted during execution, then returns the\n * execution result.\n */\nasync function* executeWithEventPolling<T>(\n executionPromise: Promise<T>,\n pendingEvents: Array<CustomEvent>,\n): AsyncGenerator<CustomEvent, T, void> {\n // Use an object to track mutable state across the async boundary\n const state = { done: false, result: undefined as T }\n const executionWithFlag = executionPromise.then((r) => {\n state.done = true\n state.result = r\n return r\n })\n\n while (!state.done) {\n // Wait for either the execution to complete or a short timeout\n await Promise.race([\n executionWithFlag,\n new Promise((resolve) => setTimeout(resolve, 10)),\n ])\n\n // Flush any pending events\n let event: CustomEvent | undefined\n while ((event = pendingEvents.shift()) !== undefined) {\n yield event\n }\n }\n\n // Final flush in case events were emitted right at completion\n let event: CustomEvent | undefined\n while ((event = pendingEvents.shift()) !== undefined) {\n yield event\n }\n\n return state.result\n}\n\n/**\n * Apply a middleware onBeforeToolCall decision.\n * Returns the (possibly transformed) input if execution should proceed,\n * or undefined if the tool call was skipped (result already pushed).\n * Throws MiddlewareAbortError if the decision is 'abort'.\n */\nasync function applyBeforeToolCallDecision(\n toolCall: ToolCall,\n tool: Tool,\n input: unknown,\n toolName: string,\n middlewareHooks: ToolExecutionMiddlewareHooks,\n results: Array<ToolResult>,\n): Promise<{ proceed: true; input: unknown } | { proceed: false }> {\n if (!middlewareHooks.onBeforeToolCall) {\n return { proceed: true, input }\n }\n\n const decision = await middlewareHooks.onBeforeToolCall(toolCall, tool, input)\n if (!decision) {\n return { proceed: true, input }\n }\n\n if (decision.type === 'abort') {\n throw new MiddlewareAbortError(decision.reason || 'Aborted by middleware')\n }\n\n if (decision.type === 'skip') {\n const skipResult = decision.result\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result:\n typeof skipResult === 'string'\n ? safeJsonParse(skipResult)\n : (skipResult ?? null),\n duration: 0,\n })\n if (middlewareHooks.onAfterToolCall) {\n await middlewareHooks.onAfterToolCall({\n toolCall,\n tool,\n toolName,\n toolCallId: toolCall.id,\n ok: true,\n duration: 0,\n result: skipResult,\n })\n }\n return { proceed: false }\n }\n\n return { proceed: true, input: decision.args }\n}\n\n/**\n * Execute a server-side tool with event polling, output validation, and middleware hooks.\n * Yields CustomEvent chunks during execution and pushes the result to the results array.\n */\nexport async function* executeServerTool<TContext = unknown>(\n toolCall: ToolCall,\n tool: AnyTool,\n toolName: string,\n input: unknown,\n context: ToolExecutionContext<TContext>,\n pendingEvents: Array<CustomEvent>,\n results: Array<ToolResult>,\n middlewareHooks?: ToolExecutionMiddlewareHooks,\n): AsyncGenerator<CustomEvent, void, void> {\n const startTime = Date.now()\n try {\n if (!tool.execute) {\n throw new Error(`Tool ${toolName} has no execute() implementation`)\n }\n const executionPromise = Promise.resolve(tool.execute(input, context))\n let result = yield* executeWithEventPolling(executionPromise, pendingEvents)\n const duration = Date.now() - startTime\n\n // MCP Apps: if this tool links a ui:// resource, eagerly read it and queue\n // a `ui-resource` CUSTOM event. The MCP source stays live until the run\n // drains (MCPManager's `connection:'close'` policy disposes on completion),\n // so `readResource` is callable here. Fail-soft: a read error warns and\n // emits nothing — the text result still flows.\n await emitUiResourceIfLinked(tool, context)\n\n // Flush remaining events (including any queued ui-resource event)\n let pendingEvent: CustomEvent | undefined\n while ((pendingEvent = pendingEvents.shift()) !== undefined) {\n yield pendingEvent\n }\n\n // Validate output against outputSchema if provided. Validates\n // `undefined`/`null` too — the schema decides whether they're valid.\n if (tool.outputSchema && isStandardSchema(tool.outputSchema)) {\n result = parseWithStandardSchema(tool.outputSchema, result)\n }\n\n const finalResult =\n typeof result === 'string' ? safeJsonParse(result) : (result ?? null)\n\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result: finalResult,\n duration,\n })\n\n if (middlewareHooks?.onAfterToolCall) {\n await middlewareHooks.onAfterToolCall({\n toolCall,\n tool,\n toolName,\n toolCallId: toolCall.id,\n ok: true,\n duration,\n result: finalResult,\n })\n }\n } catch (error: unknown) {\n const duration = Date.now() - startTime\n\n // Flush remaining events\n let pendingEvent: CustomEvent | undefined\n while ((pendingEvent = pendingEvents.shift()) !== undefined) {\n yield pendingEvent\n }\n\n if (error instanceof MiddlewareAbortError) {\n throw error\n }\n\n const message = error instanceof Error ? error.message : 'Unknown error'\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result: { error: message },\n state: 'output-error',\n duration,\n })\n\n if (middlewareHooks?.onAfterToolCall) {\n await middlewareHooks.onAfterToolCall({\n toolCall,\n tool,\n toolName,\n toolCallId: toolCall.id,\n ok: false,\n duration,\n error,\n })\n }\n }\n}\n\nfunction buildClientToolResult(\n toolCallId: string,\n toolName: string,\n tool: AnyTool,\n rawResult: unknown,\n): ToolResult {\n try {\n let result = rawResult\n if (tool.outputSchema && isStandardSchema(tool.outputSchema)) {\n result = parseWithStandardSchema(tool.outputSchema, result)\n }\n\n return {\n toolCallId,\n toolName,\n result:\n typeof result === 'string' ? safeJsonParse(result) : (result ?? null),\n }\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : 'Validation failed'\n return {\n toolCallId,\n toolName,\n result: { error: message },\n state: 'output-error',\n }\n }\n}\n\n/**\n * Execute tool calls based on their configuration.\n * Yields CustomEvent chunks during tool execution for real-time progress updates.\n *\n * Handles three cases:\n * 1. Client tools (no execute) - request client to execute\n * 2. Server tools with approval - check approval before executing\n * 3. Normal server tools - execute immediately\n *\n * @param toolCalls - Tool calls from the LLM\n * @param tools - Available tools with their configurations\n * @param approvals - Map of approval decisions (approval.id -> approved boolean)\n * @param clientResults - Map of client-side execution results (toolCallId -> result)\n * @param createCustomEventChunk - Factory to create CustomEvent chunks (optional)\n */\nexport async function* executeToolCalls<TContext = unknown>(\n toolCalls: Array<ToolCall>,\n tools: ReadonlyArray<AnyTool>,\n approvals: Map<string, boolean> = new Map(),\n clientResults: Map<string, any> = new Map(),\n createCustomEventChunk?: (\n eventName: string,\n value: Record<string, any>,\n ) => CustomEvent,\n middlewareHooks?: ToolExecutionMiddlewareHooks,\n userContext?: TContext,\n abortSignal?: AbortSignal,\n): AsyncGenerator<CustomEvent, ExecuteToolCallsResult, void> {\n const results: Array<ToolResult> = []\n const needsApproval: Array<ApprovalRequest> = []\n const needsClientExecution: Array<ClientToolRequest> = []\n\n // Create tool lookup map\n const toolMap = new Map<string, AnyTool>()\n for (const tool of tools) {\n toolMap.set(tool.name, tool)\n }\n\n // Batch gating: when any tool in the batch still needs an approval decision,\n // defer all execution so side effects don't happen before the user decides.\n const hasPendingApprovals = toolCalls.some((tc) => {\n const t = toolMap.get(tc.function.name)\n return t?.needsApproval && !approvals.has(`approval_${tc.id}`)\n })\n\n for (const toolCall of toolCalls) {\n const tool = toolMap.get(toolCall.function.name)\n const toolName = toolCall.function.name\n\n if (!tool) {\n // Unknown tool - return error\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result: { error: `Unknown tool: ${toolName}` },\n state: 'output-error',\n })\n continue\n }\n\n // Skip non-pending tools while approvals are outstanding\n if (hasPendingApprovals) {\n if (!tool.needsApproval || approvals.has(`approval_${toolCall.id}`)) {\n continue\n }\n }\n\n // Parse arguments, throwing error if invalid JSON\n let input: unknown = {}\n const argsStr = toolCall.function.arguments.trim() || '{}'\n if (argsStr) {\n try {\n const parsed = JSON.parse(argsStr)\n // Normalize null/non-object to {} (e.g. Anthropic empty tool_use blocks)\n input = parsed && typeof parsed === 'object' ? parsed : {}\n } catch (parseError) {\n // If parsing fails, throw error to fail fast\n throw new Error(`Failed to parse tool arguments as JSON: ${argsStr}`)\n }\n }\n\n // Validate input against inputSchema (for Standard Schema compliant schemas)\n if (tool.inputSchema && isStandardSchema(tool.inputSchema)) {\n try {\n input = parseWithStandardSchema(tool.inputSchema, input)\n } catch (validationError: unknown) {\n const message =\n validationError instanceof Error\n ? validationError.message\n : 'Validation failed'\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result: {\n error: `Input validation failed for tool ${tool.name}: ${message}`,\n },\n state: 'output-error',\n })\n continue\n }\n }\n\n // Create a ToolExecutionContext for this tool call with event emission\n const pendingEvents: Array<CustomEvent> = []\n const context = {\n toolCallId: toolCall.id,\n context: userContext,\n abortSignal,\n emitCustomEvent: (eventName: string, value: Record<string, any>) => {\n if (createCustomEventChunk) {\n pendingEvents.push(\n createCustomEventChunk(eventName, {\n ...value,\n toolCallId: toolCall.id,\n }),\n )\n }\n },\n } as ToolExecutionContext<TContext>\n\n // CASE 1: Client-side tool (no execute function)\n if (!tool.execute) {\n // Check if tool needs approval\n if (tool.needsApproval) {\n const approvalId = `approval_${toolCall.id}`\n\n // Check if approval decision exists\n if (approvals.has(approvalId)) {\n const approved = approvals.get(approvalId)\n\n if (approved) {\n // Approved - check if client has executed\n if (clientResults.has(toolCall.id)) {\n results.push(\n buildClientToolResult(\n toolCall.id,\n toolName,\n tool,\n clientResults.get(toolCall.id),\n ),\n )\n } else {\n // Approved but not executed yet - request client execution\n needsClientExecution.push({\n toolCallId: toolCall.id,\n toolName,\n input,\n })\n }\n } else {\n // User declined\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result: { error: 'User declined tool execution' },\n state: 'output-error',\n })\n }\n } else {\n // Need approval first\n needsApproval.push({\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n input,\n approvalId,\n })\n }\n } else {\n // No approval needed - check if client has executed\n if (clientResults.has(toolCall.id)) {\n results.push(\n buildClientToolResult(\n toolCall.id,\n toolName,\n tool,\n clientResults.get(toolCall.id),\n ),\n )\n } else {\n // Request client execution\n needsClientExecution.push({\n toolCallId: toolCall.id,\n toolName,\n input,\n })\n }\n }\n continue\n }\n\n // CASE 2: Server tool with approval required\n if (tool.needsApproval) {\n const approvalId = `approval_${toolCall.id}`\n\n // Check if approval decision exists\n if (approvals.has(approvalId)) {\n const approved = approvals.get(approvalId)\n\n if (approved) {\n // Apply middleware before-hook for approved tools\n if (middlewareHooks) {\n const decision = await applyBeforeToolCallDecision(\n toolCall,\n tool,\n input,\n toolName,\n middlewareHooks,\n results,\n )\n if (!decision.proceed) continue\n input = decision.input\n }\n\n yield* executeServerTool(\n toolCall,\n tool,\n toolName,\n input,\n context,\n pendingEvents,\n results,\n middlewareHooks,\n )\n } else {\n // User declined\n results.push({\n toolCallId: toolCall.id,\n toolName,\n result: { error: 'User declined tool execution' },\n state: 'output-error',\n })\n }\n } else {\n // Need approval\n needsApproval.push({\n toolCallId: toolCall.id,\n toolName,\n input,\n approvalId,\n })\n }\n continue\n }\n\n // CASE 3: Normal server tool - execute immediately\n if (middlewareHooks) {\n const decision = await applyBeforeToolCallDecision(\n toolCall,\n tool,\n input,\n toolName,\n middlewareHooks,\n results,\n )\n if (!decision.proceed) continue\n input = decision.input\n }\n\n yield* executeServerTool(\n toolCall,\n tool,\n toolName,\n input,\n context,\n pendingEvents,\n results,\n middlewareHooks,\n )\n }\n\n return { results, needsApproval, needsClientExecution }\n}\n"],"names":["event"],"mappings":";;AA4BA,SAAS,cAAc,OAAwB;AAC7C,MAAI;AACF,WAAO,KAAK,MAAM,KAAK;AAAA,EACzB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AA0BA,SAAS,eAAe,MAA2C;AACjE,QAAM,OAAQ,KAAK,UAAmD;AACtE,SAAO;AACT;AAWA,eAAe,uBACb,MACA,SACe;AACf,QAAM,MAAM,eAAe,IAAI;AAC/B,QAAM,QAAQ,KAAK;AACnB,MAAI,CAAC,SAAS,CAAC,IAAI,aAAc;AAIjC,MAAI;AACJ,MAAI;AACF,UAAM,MAAM,MAAM,IAAI,aAAa,KAAK;AAMxC,cAAU,IAAI,SAAS,KAAK,CAAC,MAA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AAI,CAAC,SAAS,QAAS;AACvB,cAAQ,SAAS;AAAA,IACnB;AAEA,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,EAEJ;AAEA,SAAO,EAAE,SAAS,eAAe,qBAAA;AACnC;"}
|
|
@@ -3,3 +3,5 @@ export { InternalLogger } from './logger/internal-logger.js';
|
|
|
3
3
|
export type { Logger } from './logger/types.js';
|
|
4
4
|
export { resolveDebugOption } from './logger/resolve.js';
|
|
5
5
|
export { toRunErrorPayload, toRunErrorRawEvent, } from './activities/error-payload.js';
|
|
6
|
+
export { getSandboxRuntime, provideSandboxRuntime, SandboxRuntimeCapability, } from './activities/chat/middleware/sandbox-runtime.js';
|
|
7
|
+
export type { SandboxRuntime } from './activities/chat/middleware/sandbox-runtime.js';
|
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
import { InternalLogger } from "./logger/internal-logger.js";
|
|
2
2
|
import { resolveDebugOption } from "./logger/resolve.js";
|
|
3
3
|
import { toRunErrorPayload, toRunErrorRawEvent } from "./activities/error-payload.js";
|
|
4
|
+
import { SandboxRuntimeCapability, getSandboxRuntime, provideSandboxRuntime } from "./activities/chat/middleware/sandbox-runtime.js";
|
|
4
5
|
export {
|
|
5
6
|
InternalLogger,
|
|
7
|
+
SandboxRuntimeCapability,
|
|
8
|
+
getSandboxRuntime,
|
|
9
|
+
provideSandboxRuntime,
|
|
6
10
|
resolveDebugOption,
|
|
7
11
|
toRunErrorPayload,
|
|
8
12
|
toRunErrorRawEvent
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter-internals.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"adapter-internals.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;"}
|
package/dist/esm/client.d.ts
CHANGED
|
@@ -40,5 +40,5 @@ export { BatchStrategy, CompositeStrategy, defaultJSONParser, ImmediateStrategy,
|
|
|
40
40
|
export type { ChunkRecording, ChunkStrategy, InternalToolCallState, JSONParser, ProcessorResult, ProcessorState, StreamProcessorEvents, StreamProcessorOptions, ToolCallState, ToolResultState, } from './activities/chat/stream/index.js';
|
|
41
41
|
export { uiMessagesToWire } from './utilities/ag-ui-wire.js';
|
|
42
42
|
export type { WireMessage } from './utilities/ag-ui-wire.js';
|
|
43
|
-
export type { AudioPart, ContentPart, ContentPartDataSource, ContentPartSource, ContentPartUrlSource, CustomEvent, DocumentPart, ImagePart, MediaInputMetadata, MediaInputRole, MediaPrompt, MediaPromptPart, MessagePart, ModelMessage, RunErrorEvent, RunFinishedEvent, SchemaInput, StreamChunk, StructuredOutputPart, TextPart, ThinkingPart, ToolCall, ToolCallPart, ToolResultPart, UIMessage, VideoPart, InferSchemaType, } from './types.js';
|
|
43
|
+
export type { AudioPart, ContentPart, ContentPartDataSource, ContentPartSource, ContentPartUrlSource, CustomEvent, DocumentPart, ImagePart, MediaInputMetadata, MediaInputRole, MediaPrompt, MediaPromptPart, MessagePart, ModelMessage, RunErrorEvent, RunFinishedEvent, SchemaInput, StreamChunk, StructuredOutputPart, TextPart, ThinkingPart, ToolCall, ToolCallPart, ToolResultPart, UIMessage, UIResourcePart, VideoPart, InferSchemaType, } from './types.js';
|
|
44
44
|
export type { AudioVisualization, RealtimeAdapter, RealtimeConnection, RealtimeError, RealtimeErrorCode, RealtimeEvent, RealtimeEventHandler, RealtimeEventPayloads, RealtimeMessage, RealtimeMessagePart, RealtimeMode, RealtimeSessionConfig, RealtimeStatus, RealtimeToken, RealtimeAudioPart, RealtimeImagePart, RealtimeTextPart, RealtimeToolCallPart, RealtimeToolResultPart, VADConfig, } from './realtime/types.js';
|
package/dist/esm/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sources":["../../src/client.ts"],"sourcesContent":["export enum EventType {\n TEXT_MESSAGE_START = 'TEXT_MESSAGE_START',\n TEXT_MESSAGE_CONTENT = 'TEXT_MESSAGE_CONTENT',\n TEXT_MESSAGE_END = 'TEXT_MESSAGE_END',\n TEXT_MESSAGE_CHUNK = 'TEXT_MESSAGE_CHUNK',\n TOOL_CALL_START = 'TOOL_CALL_START',\n TOOL_CALL_ARGS = 'TOOL_CALL_ARGS',\n TOOL_CALL_END = 'TOOL_CALL_END',\n TOOL_CALL_CHUNK = 'TOOL_CALL_CHUNK',\n TOOL_CALL_RESULT = 'TOOL_CALL_RESULT',\n THINKING_START = 'THINKING_START',\n THINKING_END = 'THINKING_END',\n THINKING_TEXT_MESSAGE_START = 'THINKING_TEXT_MESSAGE_START',\n THINKING_TEXT_MESSAGE_CONTENT = 'THINKING_TEXT_MESSAGE_CONTENT',\n THINKING_TEXT_MESSAGE_END = 'THINKING_TEXT_MESSAGE_END',\n STATE_SNAPSHOT = 'STATE_SNAPSHOT',\n STATE_DELTA = 'STATE_DELTA',\n MESSAGES_SNAPSHOT = 'MESSAGES_SNAPSHOT',\n ACTIVITY_SNAPSHOT = 'ACTIVITY_SNAPSHOT',\n ACTIVITY_DELTA = 'ACTIVITY_DELTA',\n RAW = 'RAW',\n CUSTOM = 'CUSTOM',\n RUN_STARTED = 'RUN_STARTED',\n RUN_FINISHED = 'RUN_FINISHED',\n RUN_ERROR = 'RUN_ERROR',\n STEP_STARTED = 'STEP_STARTED',\n STEP_FINISHED = 'STEP_FINISHED',\n REASONING_START = 'REASONING_START',\n REASONING_MESSAGE_START = 'REASONING_MESSAGE_START',\n REASONING_MESSAGE_CONTENT = 'REASONING_MESSAGE_CONTENT',\n REASONING_MESSAGE_END = 'REASONING_MESSAGE_END',\n REASONING_MESSAGE_CHUNK = 'REASONING_MESSAGE_CHUNK',\n REASONING_END = 'REASONING_END',\n REASONING_ENCRYPTED_VALUE = 'REASONING_ENCRYPTED_VALUE',\n}\n\nexport {\n toolDefinition,\n type AnyClientTool,\n type ClientTool,\n type InferToolInput,\n type InferToolName,\n type InferToolOutput,\n type ToolDefinition,\n type ToolDefinitionConfig,\n type ToolDefinitionInstance,\n} from './activities/chat/tools/tool-definition'\n\nexport {\n convertSchemaToJsonSchema,\n isStandardSchema,\n parseWithStandardSchema,\n} from './activities/chat/tools/schema-converter'\n\nexport {\n convertMessagesToModelMessages,\n generateMessageId,\n modelMessageToUIMessage,\n modelMessagesToUIMessages,\n normalizeToUIMessage,\n uiMessageToModelMessages,\n} from './activities/chat/messages'\n\nexport {\n BatchStrategy,\n CompositeStrategy,\n defaultJSONParser,\n ImmediateStrategy,\n parsePartialJSON,\n PartialJSONParser,\n PunctuationStrategy,\n StreamProcessor,\n WordBoundaryStrategy,\n} from './activities/chat/stream/index'\nexport type {\n ChunkRecording,\n ChunkStrategy,\n InternalToolCallState,\n JSONParser,\n ProcessorResult,\n ProcessorState,\n StreamProcessorEvents,\n StreamProcessorOptions,\n ToolCallState,\n ToolResultState,\n} from './activities/chat/stream/index'\n\nexport { uiMessagesToWire } from './utilities/ag-ui-wire'\nexport type { WireMessage } from './utilities/ag-ui-wire'\n\nexport type {\n AudioPart,\n ContentPart,\n ContentPartDataSource,\n ContentPartSource,\n ContentPartUrlSource,\n CustomEvent,\n DocumentPart,\n ImagePart,\n MediaInputMetadata,\n MediaInputRole,\n MediaPrompt,\n MediaPromptPart,\n MessagePart,\n ModelMessage,\n RunErrorEvent,\n RunFinishedEvent,\n SchemaInput,\n StreamChunk,\n StructuredOutputPart,\n TextPart,\n ThinkingPart,\n ToolCall,\n ToolCallPart,\n ToolResultPart,\n UIMessage,\n VideoPart,\n InferSchemaType,\n} from './types'\n\nexport type {\n AudioVisualization,\n RealtimeAdapter,\n RealtimeConnection,\n RealtimeError,\n RealtimeErrorCode,\n RealtimeEvent,\n RealtimeEventHandler,\n RealtimeEventPayloads,\n RealtimeMessage,\n RealtimeMessagePart,\n RealtimeMode,\n RealtimeSessionConfig,\n RealtimeStatus,\n RealtimeToken,\n RealtimeAudioPart,\n RealtimeImagePart,\n RealtimeTextPart,\n RealtimeToolCallPart,\n RealtimeToolResultPart,\n VADConfig,\n} from './realtime/types'\n"],"names":["EventType"],"mappings":";;;;;;;AAAO,IAAK,8BAAAA,eAAL;AACLA,aAAA,oBAAA,IAAqB;AACrBA,aAAA,sBAAA,IAAuB;AACvBA,aAAA,kBAAA,IAAmB;AACnBA,aAAA,oBAAA,IAAqB;AACrBA,aAAA,iBAAA,IAAkB;AAClBA,aAAA,gBAAA,IAAiB;AACjBA,aAAA,eAAA,IAAgB;AAChBA,aAAA,iBAAA,IAAkB;AAClBA,aAAA,kBAAA,IAAmB;AACnBA,aAAA,gBAAA,IAAiB;AACjBA,aAAA,cAAA,IAAe;AACfA,aAAA,6BAAA,IAA8B;AAC9BA,aAAA,+BAAA,IAAgC;AAChCA,aAAA,2BAAA,IAA4B;AAC5BA,aAAA,gBAAA,IAAiB;AACjBA,aAAA,aAAA,IAAc;AACdA,aAAA,mBAAA,IAAoB;AACpBA,aAAA,mBAAA,IAAoB;AACpBA,aAAA,gBAAA,IAAiB;AACjBA,aAAA,KAAA,IAAM;AACNA,aAAA,QAAA,IAAS;AACTA,aAAA,aAAA,IAAc;AACdA,aAAA,cAAA,IAAe;AACfA,aAAA,WAAA,IAAY;AACZA,aAAA,cAAA,IAAe;AACfA,aAAA,eAAA,IAAgB;AAChBA,aAAA,iBAAA,IAAkB;AAClBA,aAAA,yBAAA,IAA0B;AAC1BA,aAAA,2BAAA,IAA4B;AAC5BA,aAAA,uBAAA,IAAwB;AACxBA,aAAA,yBAAA,IAA0B;AAC1BA,aAAA,eAAA,IAAgB;AAChBA,aAAA,2BAAA,IAA4B;AAjClB,SAAAA;AAAA,GAAA,aAAA,CAAA,CAAA;"}
|
|
1
|
+
{"version":3,"file":"client.js","sources":["../../src/client.ts"],"sourcesContent":["export enum EventType {\n TEXT_MESSAGE_START = 'TEXT_MESSAGE_START',\n TEXT_MESSAGE_CONTENT = 'TEXT_MESSAGE_CONTENT',\n TEXT_MESSAGE_END = 'TEXT_MESSAGE_END',\n TEXT_MESSAGE_CHUNK = 'TEXT_MESSAGE_CHUNK',\n TOOL_CALL_START = 'TOOL_CALL_START',\n TOOL_CALL_ARGS = 'TOOL_CALL_ARGS',\n TOOL_CALL_END = 'TOOL_CALL_END',\n TOOL_CALL_CHUNK = 'TOOL_CALL_CHUNK',\n TOOL_CALL_RESULT = 'TOOL_CALL_RESULT',\n THINKING_START = 'THINKING_START',\n THINKING_END = 'THINKING_END',\n THINKING_TEXT_MESSAGE_START = 'THINKING_TEXT_MESSAGE_START',\n THINKING_TEXT_MESSAGE_CONTENT = 'THINKING_TEXT_MESSAGE_CONTENT',\n THINKING_TEXT_MESSAGE_END = 'THINKING_TEXT_MESSAGE_END',\n STATE_SNAPSHOT = 'STATE_SNAPSHOT',\n STATE_DELTA = 'STATE_DELTA',\n MESSAGES_SNAPSHOT = 'MESSAGES_SNAPSHOT',\n ACTIVITY_SNAPSHOT = 'ACTIVITY_SNAPSHOT',\n ACTIVITY_DELTA = 'ACTIVITY_DELTA',\n RAW = 'RAW',\n CUSTOM = 'CUSTOM',\n RUN_STARTED = 'RUN_STARTED',\n RUN_FINISHED = 'RUN_FINISHED',\n RUN_ERROR = 'RUN_ERROR',\n STEP_STARTED = 'STEP_STARTED',\n STEP_FINISHED = 'STEP_FINISHED',\n REASONING_START = 'REASONING_START',\n REASONING_MESSAGE_START = 'REASONING_MESSAGE_START',\n REASONING_MESSAGE_CONTENT = 'REASONING_MESSAGE_CONTENT',\n REASONING_MESSAGE_END = 'REASONING_MESSAGE_END',\n REASONING_MESSAGE_CHUNK = 'REASONING_MESSAGE_CHUNK',\n REASONING_END = 'REASONING_END',\n REASONING_ENCRYPTED_VALUE = 'REASONING_ENCRYPTED_VALUE',\n}\n\nexport {\n toolDefinition,\n type AnyClientTool,\n type ClientTool,\n type InferToolInput,\n type InferToolName,\n type InferToolOutput,\n type ToolDefinition,\n type ToolDefinitionConfig,\n type ToolDefinitionInstance,\n} from './activities/chat/tools/tool-definition'\n\nexport {\n convertSchemaToJsonSchema,\n isStandardSchema,\n parseWithStandardSchema,\n} from './activities/chat/tools/schema-converter'\n\nexport {\n convertMessagesToModelMessages,\n generateMessageId,\n modelMessageToUIMessage,\n modelMessagesToUIMessages,\n normalizeToUIMessage,\n uiMessageToModelMessages,\n} from './activities/chat/messages'\n\nexport {\n BatchStrategy,\n CompositeStrategy,\n defaultJSONParser,\n ImmediateStrategy,\n parsePartialJSON,\n PartialJSONParser,\n PunctuationStrategy,\n StreamProcessor,\n WordBoundaryStrategy,\n} from './activities/chat/stream/index'\nexport type {\n ChunkRecording,\n ChunkStrategy,\n InternalToolCallState,\n JSONParser,\n ProcessorResult,\n ProcessorState,\n StreamProcessorEvents,\n StreamProcessorOptions,\n ToolCallState,\n ToolResultState,\n} from './activities/chat/stream/index'\n\nexport { uiMessagesToWire } from './utilities/ag-ui-wire'\nexport type { WireMessage } from './utilities/ag-ui-wire'\n\nexport type {\n AudioPart,\n ContentPart,\n ContentPartDataSource,\n ContentPartSource,\n ContentPartUrlSource,\n CustomEvent,\n DocumentPart,\n ImagePart,\n MediaInputMetadata,\n MediaInputRole,\n MediaPrompt,\n MediaPromptPart,\n MessagePart,\n ModelMessage,\n RunErrorEvent,\n RunFinishedEvent,\n SchemaInput,\n StreamChunk,\n StructuredOutputPart,\n TextPart,\n ThinkingPart,\n ToolCall,\n ToolCallPart,\n ToolResultPart,\n UIMessage,\n UIResourcePart,\n VideoPart,\n InferSchemaType,\n} from './types'\n\nexport type {\n AudioVisualization,\n RealtimeAdapter,\n RealtimeConnection,\n RealtimeError,\n RealtimeErrorCode,\n RealtimeEvent,\n RealtimeEventHandler,\n RealtimeEventPayloads,\n RealtimeMessage,\n RealtimeMessagePart,\n RealtimeMode,\n RealtimeSessionConfig,\n RealtimeStatus,\n RealtimeToken,\n RealtimeAudioPart,\n RealtimeImagePart,\n RealtimeTextPart,\n RealtimeToolCallPart,\n RealtimeToolResultPart,\n VADConfig,\n} from './realtime/types'\n"],"names":["EventType"],"mappings":";;;;;;;AAAO,IAAK,8BAAAA,eAAL;AACLA,aAAA,oBAAA,IAAqB;AACrBA,aAAA,sBAAA,IAAuB;AACvBA,aAAA,kBAAA,IAAmB;AACnBA,aAAA,oBAAA,IAAqB;AACrBA,aAAA,iBAAA,IAAkB;AAClBA,aAAA,gBAAA,IAAiB;AACjBA,aAAA,eAAA,IAAgB;AAChBA,aAAA,iBAAA,IAAkB;AAClBA,aAAA,kBAAA,IAAmB;AACnBA,aAAA,gBAAA,IAAiB;AACjBA,aAAA,cAAA,IAAe;AACfA,aAAA,6BAAA,IAA8B;AAC9BA,aAAA,+BAAA,IAAgC;AAChCA,aAAA,2BAAA,IAA4B;AAC5BA,aAAA,gBAAA,IAAiB;AACjBA,aAAA,aAAA,IAAc;AACdA,aAAA,mBAAA,IAAoB;AACpBA,aAAA,mBAAA,IAAoB;AACpBA,aAAA,gBAAA,IAAiB;AACjBA,aAAA,KAAA,IAAM;AACNA,aAAA,QAAA,IAAS;AACTA,aAAA,aAAA,IAAc;AACdA,aAAA,cAAA,IAAe;AACfA,aAAA,WAAA,IAAY;AACZA,aAAA,cAAA,IAAe;AACfA,aAAA,eAAA,IAAgB;AAChBA,aAAA,iBAAA,IAAkB;AAClBA,aAAA,yBAAA,IAA0B;AAC1BA,aAAA,2BAAA,IAA4B;AAC5BA,aAAA,uBAAA,IAAwB;AACxBA,aAAA,yBAAA,IAA0B;AAC1BA,aAAA,eAAA,IAAgB;AAChBA,aAAA,2BAAA,IAA4B;AAjClB,SAAAA;AAAA,GAAA,aAAA,CAAA,CAAA;"}
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -18,10 +18,10 @@ export type { ProviderTool } from './tools/provider-tool.js';
|
|
|
18
18
|
export { brandProviderTool } from './tools/provider-tool.js';
|
|
19
19
|
export { maxIterations, untilFinishReason, combineStrategies, } from './activities/chat/agent-loop-strategies.js';
|
|
20
20
|
export { createToolRegistry, createFrozenRegistry, type ToolRegistry, } from './tool-registry.js';
|
|
21
|
-
export type { ChatMiddleware, ChatMiddlewareContext, ChatMiddlewarePhase, ChatMiddlewareConfig, StructuredOutputMiddlewareConfig, ToolCallHookContext, BeforeToolCallDecision, AfterToolCallInfo, IterationInfo, ToolPhaseCompleteInfo, UsageInfo, FinishInfo, AbortInfo, ErrorInfo, } from './activities/chat/middleware/index.js';
|
|
21
|
+
export type { ChatMiddleware, ChatMiddlewareContext, ChatMiddlewarePhase, ChatMiddlewareConfig, StructuredOutputMiddlewareConfig, ToolCallHookContext, BeforeToolCallDecision, AfterToolCallInfo, IterationInfo, ToolPhaseCompleteInfo, UsageInfo, FinishInfo, AbortInfo, ErrorInfo, SandboxFileEvent, ChatSandboxHooks, } from './activities/chat/middleware/index.js';
|
|
22
22
|
export type { GenerationMiddleware, GenerationMiddlewareContext, GenerationActivity, GenerationUsageInfo, GenerationFinishInfo, GenerationAbortInfo, GenerationErrorInfo, AnyGenerationMiddleware, } from './activities/middleware/index.js';
|
|
23
23
|
export { createCapability, defineChatMiddleware, createChatMiddleware, } from './activities/chat/middleware/index.js';
|
|
24
|
-
export type { Capability, CapabilityHandle, CapabilityContext, CapabilityGetter, CapabilityProvider, } from './activities/chat/middleware/index.js';
|
|
24
|
+
export type { Capability, CapabilityHandle, CapabilityContext, CapabilityGetter, CapabilityProvider, DefinedChatMiddleware, AnyChatMiddleware, } from './activities/chat/middleware/index.js';
|
|
25
25
|
export * from './types.js';
|
|
26
26
|
export { firstSentence, renderLazyCatalogEntry, } from './activities/chat/tools/lazy-tools.js';
|
|
27
27
|
export { buildBaseUsage, type BaseUsageInput } from './utilities/usage.js';
|
|
@@ -19,6 +19,8 @@ export declare class InternalLogger {
|
|
|
19
19
|
middleware(message: string, meta?: Record<string, unknown>): void;
|
|
20
20
|
/** Log before/after a tool-call execution. Chat-only. */
|
|
21
21
|
tools(message: string, meta?: Record<string, unknown>): void;
|
|
22
|
+
/** Log sandbox internals (watcher, file events, hook dispatch). Chat-only. */
|
|
23
|
+
sandbox(message: string, meta?: Record<string, unknown>): void;
|
|
22
24
|
/** Log an agent-loop iteration marker or phase transition. Chat-only. */
|
|
23
25
|
agentLoop(message: string, meta?: Record<string, unknown>): void;
|
|
24
26
|
/** Log a config transform returned by a middleware `onConfig` hook. Chat-only. */
|
|
@@ -6,7 +6,8 @@ const CATEGORY_EMOJI = {
|
|
|
6
6
|
tools: "🔧",
|
|
7
7
|
agentLoop: "🔁",
|
|
8
8
|
config: "⚙️",
|
|
9
|
-
errors: "❌"
|
|
9
|
+
errors: "❌",
|
|
10
|
+
sandbox: "📦"
|
|
10
11
|
};
|
|
11
12
|
class InternalLogger {
|
|
12
13
|
constructor(logger, categories) {
|
|
@@ -45,6 +46,10 @@ class InternalLogger {
|
|
|
45
46
|
tools(message, meta) {
|
|
46
47
|
this.emit("debug", "tools", message, meta);
|
|
47
48
|
}
|
|
49
|
+
/** Log sandbox internals (watcher, file events, hook dispatch). Chat-only. */
|
|
50
|
+
sandbox(message, meta) {
|
|
51
|
+
this.emit("debug", "sandbox", message, meta);
|
|
52
|
+
}
|
|
48
53
|
/** Log an agent-loop iteration marker or phase transition. Chat-only. */
|
|
49
54
|
agentLoop(message, meta) {
|
|
50
55
|
this.emit("debug", "agentLoop", message, meta);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal-logger.js","sources":["../../../src/logger/internal-logger.ts"],"sourcesContent":["import type { DebugCategories, Logger } from './types'\n\n/**\n * Fully-resolved categories map. Every flag is a definite boolean (never\n * undefined), produced by `resolveDebugOption` from a `DebugOption`.\n */\nexport type ResolvedCategories = Required<DebugCategories>\n\n/**\n * Package-internal logger wrapper used by every activity and adapter in\n * `@tanstack/ai`. Wraps a user-supplied (or default `ConsoleLogger`) `Logger`\n * plus a fully-resolved per-category map. Each category has a dedicated\n * method that no-ops when its flag is `false`, or prepends a\n * `[tanstack-ai:<category>] ` prefix and calls the underlying logger's\n * `error` (for the `errors` category) or `debug` (for everything else).\n *\n * Not exported from the package root. Adapter packages consume it via the\n * `@tanstack/ai/adapter-internals` subpath export.\n */\n/**\n * Emoji marker per category — bracketing the `[tanstack-ai:<cat>]` tag on\n * both sides makes it trivial to visually pick out a category when scanning\n * dense streaming logs.\n */\nconst CATEGORY_EMOJI: Record<keyof ResolvedCategories, string> = {\n request: '📤',\n provider: '📥',\n output: '📨',\n middleware: '🧩',\n tools: '🔧',\n agentLoop: '🔁',\n config: '⚙️',\n errors: '❌',\n}\n\nexport class InternalLogger {\n constructor(\n private readonly logger: Logger,\n private readonly categories: ResolvedCategories,\n ) {}\n\n /** Whether a category is enabled. Cheap, safe to call on hot paths. */\n isEnabled(category: keyof ResolvedCategories): boolean {\n return this.categories[category]\n }\n\n private emit(\n level: 'debug' | 'error',\n category: keyof ResolvedCategories,\n message: string,\n meta?: Record<string, unknown>,\n ): void {\n if (!this.categories[category]) return\n const emoji = CATEGORY_EMOJI[category]\n const prefixed = `${emoji} [tanstack-ai:${category}] ${emoji} ${message}`\n try {\n if (level === 'error') this.logger.error(prefixed, meta)\n else this.logger.debug(prefixed, meta)\n } catch {\n // User-supplied logger threw; swallow so we never mask the original\n // error that triggered this log call.\n }\n }\n\n /** Log a raw chunk/frame received from a provider SDK. */\n provider(message: string, meta?: Record<string, unknown>): void {\n this.emit('debug', 'provider', message, meta)\n }\n\n /** Log a chunk/result yielded to the consumer after middleware. */\n output(message: string, meta?: Record<string, unknown>): void {\n this.emit('debug', 'output', message, meta)\n }\n\n /** Log inputs/outputs around a middleware hook invocation. Chat-only. */\n middleware(message: string, meta?: Record<string, unknown>): void {\n this.emit('debug', 'middleware', message, meta)\n }\n\n /** Log before/after a tool-call execution. Chat-only. */\n tools(message: string, meta?: Record<string, unknown>): void {\n this.emit('debug', 'tools', message, meta)\n }\n\n /** Log an agent-loop iteration marker or phase transition. Chat-only. */\n agentLoop(message: string, meta?: Record<string, unknown>): void {\n this.emit('debug', 'agentLoop', message, meta)\n }\n\n /** Log a config transform returned by a middleware `onConfig` hook. Chat-only. */\n config(message: string, meta?: Record<string, unknown>): void {\n this.emit('debug', 'config', message, meta)\n }\n\n /**\n * Log a caught error. Defaults to on even when `debug` is unspecified.\n * Uses the underlying logger's `error` level.\n */\n errors(message: string, meta?: Record<string, unknown>): void {\n this.emit('error', 'errors', message, meta)\n }\n\n /** Log outgoing request metadata before an adapter SDK call. */\n request(message: string, meta?: Record<string, unknown>): void {\n this.emit('debug', 'request', message, meta)\n }\n\n /**\n * Log a non-fatal misconfiguration or recoverable anomaly. Gated by the\n * `errors` category — on by default (and when `debug` is unspecified), so\n * silent-drop conditions surface, but still silenced by `debug: false`,\n * which honors the \"disable everything including errors\" contract. Routes to\n * the underlying logger's `warn` level.\n */\n warn(message: string, meta?: Record<string, unknown>): void {\n if (!this.categories.errors) return\n const prefixed = `⚠️ [tanstack-ai:warn] ⚠️ ${message}`\n try {\n this.logger.warn(prefixed, meta)\n } catch {\n // User-supplied logger threw; swallow so a broken logger never masks the\n // condition we were trying to surface.\n }\n }\n}\n"],"names":[],"mappings":"AAwBA,MAAM,iBAA2D;AAAA,EAC/D,SAAS;AAAA,EACT,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,QAAQ;
|
|
1
|
+
{"version":3,"file":"internal-logger.js","sources":["../../../src/logger/internal-logger.ts"],"sourcesContent":["import type { DebugCategories, Logger } from './types'\n\n/**\n * Fully-resolved categories map. Every flag is a definite boolean (never\n * undefined), produced by `resolveDebugOption` from a `DebugOption`.\n */\nexport type ResolvedCategories = Required<DebugCategories>\n\n/**\n * Package-internal logger wrapper used by every activity and adapter in\n * `@tanstack/ai`. Wraps a user-supplied (or default `ConsoleLogger`) `Logger`\n * plus a fully-resolved per-category map. Each category has a dedicated\n * method that no-ops when its flag is `false`, or prepends a\n * `[tanstack-ai:<category>] ` prefix and calls the underlying logger's\n * `error` (for the `errors` category) or `debug` (for everything else).\n *\n * Not exported from the package root. Adapter packages consume it via the\n * `@tanstack/ai/adapter-internals` subpath export.\n */\n/**\n * Emoji marker per category — bracketing the `[tanstack-ai:<cat>]` tag on\n * both sides makes it trivial to visually pick out a category when scanning\n * dense streaming logs.\n */\nconst CATEGORY_EMOJI: Record<keyof ResolvedCategories, string> = {\n request: '📤',\n provider: '📥',\n output: '📨',\n middleware: '🧩',\n tools: '🔧',\n agentLoop: '🔁',\n config: '⚙️',\n errors: '❌',\n sandbox: '📦',\n}\n\nexport class InternalLogger {\n constructor(\n private readonly logger: Logger,\n private readonly categories: ResolvedCategories,\n ) {}\n\n /** Whether a category is enabled. Cheap, safe to call on hot paths. */\n isEnabled(category: keyof ResolvedCategories): boolean {\n return this.categories[category]\n }\n\n private emit(\n level: 'debug' | 'error',\n category: keyof ResolvedCategories,\n message: string,\n meta?: Record<string, unknown>,\n ): void {\n if (!this.categories[category]) return\n const emoji = CATEGORY_EMOJI[category]\n const prefixed = `${emoji} [tanstack-ai:${category}] ${emoji} ${message}`\n try {\n if (level === 'error') this.logger.error(prefixed, meta)\n else this.logger.debug(prefixed, meta)\n } catch {\n // User-supplied logger threw; swallow so we never mask the original\n // error that triggered this log call.\n }\n }\n\n /** Log a raw chunk/frame received from a provider SDK. */\n provider(message: string, meta?: Record<string, unknown>): void {\n this.emit('debug', 'provider', message, meta)\n }\n\n /** Log a chunk/result yielded to the consumer after middleware. */\n output(message: string, meta?: Record<string, unknown>): void {\n this.emit('debug', 'output', message, meta)\n }\n\n /** Log inputs/outputs around a middleware hook invocation. Chat-only. */\n middleware(message: string, meta?: Record<string, unknown>): void {\n this.emit('debug', 'middleware', message, meta)\n }\n\n /** Log before/after a tool-call execution. Chat-only. */\n tools(message: string, meta?: Record<string, unknown>): void {\n this.emit('debug', 'tools', message, meta)\n }\n\n /** Log sandbox internals (watcher, file events, hook dispatch). Chat-only. */\n sandbox(message: string, meta?: Record<string, unknown>): void {\n this.emit('debug', 'sandbox', message, meta)\n }\n\n /** Log an agent-loop iteration marker or phase transition. Chat-only. */\n agentLoop(message: string, meta?: Record<string, unknown>): void {\n this.emit('debug', 'agentLoop', message, meta)\n }\n\n /** Log a config transform returned by a middleware `onConfig` hook. Chat-only. */\n config(message: string, meta?: Record<string, unknown>): void {\n this.emit('debug', 'config', message, meta)\n }\n\n /**\n * Log a caught error. Defaults to on even when `debug` is unspecified.\n * Uses the underlying logger's `error` level.\n */\n errors(message: string, meta?: Record<string, unknown>): void {\n this.emit('error', 'errors', message, meta)\n }\n\n /** Log outgoing request metadata before an adapter SDK call. */\n request(message: string, meta?: Record<string, unknown>): void {\n this.emit('debug', 'request', message, meta)\n }\n\n /**\n * Log a non-fatal misconfiguration or recoverable anomaly. Gated by the\n * `errors` category — on by default (and when `debug` is unspecified), so\n * silent-drop conditions surface, but still silenced by `debug: false`,\n * which honors the \"disable everything including errors\" contract. Routes to\n * the underlying logger's `warn` level.\n */\n warn(message: string, meta?: Record<string, unknown>): void {\n if (!this.categories.errors) return\n const prefixed = `⚠️ [tanstack-ai:warn] ⚠️ ${message}`\n try {\n this.logger.warn(prefixed, meta)\n } catch {\n // User-supplied logger threw; swallow so a broken logger never masks the\n // condition we were trying to surface.\n }\n }\n}\n"],"names":[],"mappings":"AAwBA,MAAM,iBAA2D;AAAA,EAC/D,SAAS;AAAA,EACT,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AACX;AAEO,MAAM,eAAe;AAAA,EAC1B,YACmB,QACA,YACjB;AAFiB,SAAA,SAAA;AACA,SAAA,aAAA;AAAA,EAChB;AAAA,EAFgB;AAAA,EACA;AAAA;AAAA,EAInB,UAAU,UAA6C;AACrD,WAAO,KAAK,WAAW,QAAQ;AAAA,EACjC;AAAA,EAEQ,KACN,OACA,UACA,SACA,MACM;AACN,QAAI,CAAC,KAAK,WAAW,QAAQ,EAAG;AAChC,UAAM,QAAQ,eAAe,QAAQ;AACrC,UAAM,WAAW,GAAG,KAAK,i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AO,KAAK,UAAU,IAAI;AAAA,IACjC,QAAQ;AAAA,IAGR;AAAA,EACF;AACF;"}
|
|
@@ -8,7 +8,8 @@ const ALL_OFF = {
|
|
|
8
8
|
agentLoop: false,
|
|
9
9
|
config: false,
|
|
10
10
|
errors: false,
|
|
11
|
-
request: false
|
|
11
|
+
request: false,
|
|
12
|
+
sandbox: false
|
|
12
13
|
};
|
|
13
14
|
const ALL_ON = {
|
|
14
15
|
provider: true,
|
|
@@ -18,7 +19,8 @@ const ALL_ON = {
|
|
|
18
19
|
agentLoop: true,
|
|
19
20
|
config: true,
|
|
20
21
|
errors: true,
|
|
21
|
-
request: true
|
|
22
|
+
request: true,
|
|
23
|
+
sandbox: true
|
|
22
24
|
};
|
|
23
25
|
const errorsOnlyCategories = () => ({
|
|
24
26
|
...ALL_OFF,
|
|
@@ -32,7 +34,8 @@ const resolveCategoriesFromPartial = (partial) => ({
|
|
|
32
34
|
agentLoop: partial.agentLoop ?? true,
|
|
33
35
|
config: partial.config ?? true,
|
|
34
36
|
errors: partial.errors ?? true,
|
|
35
|
-
request: partial.request ?? true
|
|
37
|
+
request: partial.request ?? true,
|
|
38
|
+
sandbox: partial.sandbox ?? true
|
|
36
39
|
});
|
|
37
40
|
function resolveDebugOption(debug) {
|
|
38
41
|
if (debug === void 0) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve.js","sources":["../../../src/logger/resolve.ts"],"sourcesContent":["import { ConsoleLogger } from './console-logger'\nimport { InternalLogger } from './internal-logger'\nimport type { ResolvedCategories } from './internal-logger'\nimport type { DebugCategories, DebugConfig, DebugOption, Logger } from './types'\n\nconst ALL_OFF: ResolvedCategories = {\n provider: false,\n output: false,\n middleware: false,\n tools: false,\n agentLoop: false,\n config: false,\n errors: false,\n request: false,\n}\n\nconst ALL_ON: ResolvedCategories = {\n provider: true,\n output: true,\n middleware: true,\n tools: true,\n agentLoop: true,\n config: true,\n errors: true,\n request: true,\n}\n\nconst errorsOnlyCategories = (): ResolvedCategories => ({\n ...ALL_OFF,\n errors: true,\n})\n\nconst resolveCategoriesFromPartial = (\n partial: DebugCategories,\n): ResolvedCategories => ({\n provider: partial.provider ?? true,\n output: partial.output ?? true,\n middleware: partial.middleware ?? true,\n tools: partial.tools ?? true,\n agentLoop: partial.agentLoop ?? true,\n config: partial.config ?? true,\n errors: partial.errors ?? true,\n request: partial.request ?? true,\n})\n\n/**\n * Normalize a `DebugOption` into an `InternalLogger` ready to be threaded\n * through the library's activities and adapters. See the `DebugOption`\n * resolution table in the spec for the complete rules.\n *\n * - `undefined`: only the `errors` category is enabled; default `ConsoleLogger`.\n * - `true`: all categories enabled; default `ConsoleLogger`.\n * - `false`: all categories disabled (including `errors`); default `ConsoleLogger`.\n * - `DebugConfig`: each unspecified category defaults to `true`; an optional\n * `logger` replaces the default `ConsoleLogger`.\n */\nexport function resolveDebugOption(\n debug: DebugOption | undefined,\n): InternalLogger {\n if (debug === undefined) {\n return new InternalLogger(new ConsoleLogger(), errorsOnlyCategories())\n }\n if (debug === true) {\n return new InternalLogger(new ConsoleLogger(), ALL_ON)\n }\n if (debug === false) {\n return new InternalLogger(new ConsoleLogger(), ALL_OFF)\n }\n const { logger, ...cats }: DebugConfig = debug\n const userLogger: Logger = logger ?? new ConsoleLogger()\n return new InternalLogger(userLogger, resolveCategoriesFromPartial(cats))\n}\n"],"names":[],"mappings":";;AAKA,MAAM,UAA8B;AAAA,EAClC,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AACX;AAEA,MAAM,SAA6B;AAAA,EACjC,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AACX;AAEA,MAAM,uBAAuB,OAA2B;AAAA,EACtD,GAAG;AAAA,EACH,QAAQ;AACV;AAEA,MAAM,+BAA+B,CACnC,aACwB;AAAA,EACxB,UAAU,QAAQ,YAAY;AAAA,EAC9B,QAAQ,QAAQ,UAAU;AAAA,EAC1B,YAAY,QAAQ,cAAc;AAAA,EAClC,OAAO,QAAQ,SAAS;AAAA,EACxB,WAAW,QAAQ,aAAa;AAAA,EAChC,QAAQ,QAAQ,UAAU;AAAA,EAC1B,QAAQ,QAAQ,UAAU;AAAA,EAC1B,SAAS,QAAQ,WAAW;AAC9B;AAaO,SAAS,mBACd,OACgB;AAChB,MAAI,UAAU,QAAW;AACvB,WAAO,IAAI,eAAe,IAAI,cAAA,GAAiB,sBAAsB;AAAA,EACvE;AACA,MAAI,UAAU,MAAM;AAClB,WAAO,IAAI,eAAe,IAAI,cAAA,GAAiB,MAAM;AAAA,EACvD;AACA,MAAI,UAAU,OAAO;AACnB,WAAO,IAAI,eAAe,IAAI,cAAA,GAAiB,OAAO;AAAA,EACxD;AACA,QAAM,EAAE,QAAQ,GAAG,KAAA,IAAsB;AACzC,QAAM,aAAqB,UAAU,IAAI,cAAA;AACzC,SAAO,IAAI,eAAe,YAAY,6BAA6B,IAAI,CAAC;AAC1E;"}
|
|
1
|
+
{"version":3,"file":"resolve.js","sources":["../../../src/logger/resolve.ts"],"sourcesContent":["import { ConsoleLogger } from './console-logger'\nimport { InternalLogger } from './internal-logger'\nimport type { ResolvedCategories } from './internal-logger'\nimport type { DebugCategories, DebugConfig, DebugOption, Logger } from './types'\n\nconst ALL_OFF: ResolvedCategories = {\n provider: false,\n output: false,\n middleware: false,\n tools: false,\n agentLoop: false,\n config: false,\n errors: false,\n request: false,\n sandbox: false,\n}\n\nconst ALL_ON: ResolvedCategories = {\n provider: true,\n output: true,\n middleware: true,\n tools: true,\n agentLoop: true,\n config: true,\n errors: true,\n request: true,\n sandbox: true,\n}\n\nconst errorsOnlyCategories = (): ResolvedCategories => ({\n ...ALL_OFF,\n errors: true,\n})\n\nconst resolveCategoriesFromPartial = (\n partial: DebugCategories,\n): ResolvedCategories => ({\n provider: partial.provider ?? true,\n output: partial.output ?? true,\n middleware: partial.middleware ?? true,\n tools: partial.tools ?? true,\n agentLoop: partial.agentLoop ?? true,\n config: partial.config ?? true,\n errors: partial.errors ?? true,\n request: partial.request ?? true,\n sandbox: partial.sandbox ?? true,\n})\n\n/**\n * Normalize a `DebugOption` into an `InternalLogger` ready to be threaded\n * through the library's activities and adapters. See the `DebugOption`\n * resolution table in the spec for the complete rules.\n *\n * - `undefined`: only the `errors` category is enabled; default `ConsoleLogger`.\n * - `true`: all categories enabled; default `ConsoleLogger`.\n * - `false`: all categories disabled (including `errors`); default `ConsoleLogger`.\n * - `DebugConfig`: each unspecified category defaults to `true`; an optional\n * `logger` replaces the default `ConsoleLogger`.\n */\nexport function resolveDebugOption(\n debug: DebugOption | undefined,\n): InternalLogger {\n if (debug === undefined) {\n return new InternalLogger(new ConsoleLogger(), errorsOnlyCategories())\n }\n if (debug === true) {\n return new InternalLogger(new ConsoleLogger(), ALL_ON)\n }\n if (debug === false) {\n return new InternalLogger(new ConsoleLogger(), ALL_OFF)\n }\n const { logger, ...cats }: DebugConfig = debug\n const userLogger: Logger = logger ?? new ConsoleLogger()\n return new InternalLogger(userLogger, resolveCategoriesFromPartial(cats))\n}\n"],"names":[],"mappings":";;AAKA,MAAM,UAA8B;AAAA,EAClC,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,SAAS;AACX;AAEA,MAAM,SAA6B;AAAA,EACjC,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,SAAS;AACX;AAEA,MAAM,uBAAuB,OAA2B;AAAA,EACtD,GAAG;AAAA,EACH,QAAQ;AACV;AAEA,MAAM,+BAA+B,CACnC,aACwB;AAAA,EACxB,UAAU,QAAQ,YAAY;AAAA,EAC9B,QAAQ,QAAQ,UAAU;AAAA,EAC1B,YAAY,QAAQ,cAAc;AAAA,EAClC,OAAO,QAAQ,SAAS;AAAA,EACxB,WAAW,QAAQ,aAAa;AAAA,EAChC,QAAQ,QAAQ,UAAU;AAAA,EAC1B,QAAQ,QAAQ,UAAU;AAAA,EAC1B,SAAS,QAAQ,WAAW;AAAA,EAC5B,SAAS,QAAQ,WAAW;AAC9B;AAaO,SAAS,mBACd,OACgB;AAChB,MAAI,UAAU,QAAW;AACvB,WAAO,IAAI,eAAe,IAAI,cAAA,GAAiB,sBAAsB;AAAA,EACvE;AACA,MAAI,UAAU,MAAM;AAClB,WAAO,IAAI,eAAe,IAAI,cAAA,GAAiB,MAAM;AAAA,EACvD;AACA,MAAI,UAAU,OAAO;AACnB,WAAO,IAAI,eAAe,IAAI,cAAA,GAAiB,OAAO;AAAA,EACxD;AACA,QAAM,EAAE,QAAQ,GAAG,KAAA,IAAsB;AACzC,QAAM,aAAqB,UAAU,IAAI,cAAA;AACzC,SAAO,IAAI,eAAe,YAAY,6BAA6B,IAAI,CAAC;AAC1E;"}
|
|
@@ -59,6 +59,11 @@ export interface DebugCategories {
|
|
|
59
59
|
* Outgoing call metadata (provider, model, message/tool counts) emitted before each adapter SDK call.
|
|
60
60
|
*/
|
|
61
61
|
request?: boolean;
|
|
62
|
+
/**
|
|
63
|
+
* Sandbox internals: watcher start/stop + mechanism, file events, sandbox
|
|
64
|
+
* hook dispatch, ensure/bootstrap and lifecycle transitions. Chat-only.
|
|
65
|
+
*/
|
|
66
|
+
sandbox?: boolean;
|
|
62
67
|
}
|
|
63
68
|
/**
|
|
64
69
|
* Granular debug configuration combining per-category toggles with an optional custom logger. Any unspecified category flag defaults to `true`.
|
package/dist/esm/types.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { StandardJSONSchemaV1, StandardSchemaV1 } from '@standard-schema/spec';
|
|
2
2
|
import { InternalLogger } from './logger/internal-logger.js';
|
|
3
3
|
import { SystemPrompt } from './system-prompts.js';
|
|
4
|
+
import { CapabilityContext } from './activities/chat/middleware/capabilities.js';
|
|
4
5
|
import { CompletionTokensDetails, PromptTokensDetails, ProviderUsageDetails, TokenUsage, UsageCostBreakdown } from '@tanstack/ai-event-client';
|
|
5
6
|
import { BaseEvent as AGUIBaseEvent, CustomEvent as AGUICustomEvent, MessagesSnapshotEvent as AGUIMessagesSnapshotEvent, ReasoningEncryptedValueEvent as AGUIReasoningEncryptedValueEvent, ReasoningEndEvent as AGUIReasoningEndEvent, ReasoningMessageContentEvent as AGUIReasoningMessageContentEvent, ReasoningMessageEndEvent as AGUIReasoningMessageEndEvent, ReasoningMessageStartEvent as AGUIReasoningMessageStartEvent, ReasoningStartEvent as AGUIReasoningStartEvent, RunErrorEvent as AGUIRunErrorEvent, RunFinishedEvent as AGUIRunFinishedEvent, RunStartedEvent as AGUIRunStartedEvent, StateDeltaEvent as AGUIStateDeltaEvent, StateSnapshotEvent as AGUIStateSnapshotEvent, StepFinishedEvent as AGUIStepFinishedEvent, StepStartedEvent as AGUIStepStartedEvent, TextMessageContentEvent as AGUITextMessageContentEvent, TextMessageEndEvent as AGUITextMessageEndEvent, TextMessageStartEvent as AGUITextMessageStartEvent, ToolCallArgsEvent as AGUIToolCallArgsEvent, ToolCallEndEvent as AGUIToolCallEndEvent, ToolCallResultEvent as AGUIToolCallResultEvent, ToolCallStartEvent as AGUIToolCallStartEvent, EventType } from '@ag-ui/core';
|
|
6
7
|
/**
|
|
@@ -298,7 +299,28 @@ export interface StructuredOutputPart<TData = unknown> {
|
|
|
298
299
|
/** Populated when `status === 'error'`. */
|
|
299
300
|
errorMessage?: string;
|
|
300
301
|
}
|
|
301
|
-
export
|
|
302
|
+
export interface UIResourcePart {
|
|
303
|
+
type: 'ui-resource';
|
|
304
|
+
/** The ui:// resource object in MCP-native shape — fed straight to the renderer. */
|
|
305
|
+
resource: {
|
|
306
|
+
uri: string;
|
|
307
|
+
mimeType: string;
|
|
308
|
+
text?: string;
|
|
309
|
+
blob?: string;
|
|
310
|
+
};
|
|
311
|
+
/** Pool prefix / config key — routes interactive calls to the right MCP server. */
|
|
312
|
+
serverId?: string;
|
|
313
|
+
/** Links the widget to the originating tool call — correlates it with the
|
|
314
|
+
* sibling ToolCallPart/ToolResultPart in the same message. */
|
|
315
|
+
toolCallId: string;
|
|
316
|
+
/** Server-native (unprefixed) MCP tool name whose UI this resource renders.
|
|
317
|
+
* Required by the renderer (`@mcp-ui/client`'s `AppRenderer` `toolName` prop). */
|
|
318
|
+
toolName: string;
|
|
319
|
+
/** Reserved for future passthrough of the resource/tool `_meta.ui` (e.g. frame-size hints).
|
|
320
|
+
* Currently always `undefined` — nothing populates this field yet. */
|
|
321
|
+
meta?: Record<string, unknown>;
|
|
322
|
+
}
|
|
323
|
+
export type MessagePart<TData = unknown> = TextPart | ImagePart | AudioPart | VideoPart | DocumentPart | ToolCallPart | ToolResultPart | ThinkingPart | StructuredOutputPart<TData> | UIResourcePart;
|
|
302
324
|
/**
|
|
303
325
|
* UIMessage - Domain-specific message format optimized for building chat UIs
|
|
304
326
|
* Contains parts that can be text, tool calls, or tool results. Generic over
|
|
@@ -740,6 +762,23 @@ export interface TextOptions<TProviderOptionsSuperset extends Record<string, any
|
|
|
740
762
|
* Surfaced for observability/middleware; not consumed by the LLM call.
|
|
741
763
|
*/
|
|
742
764
|
parentRunId?: string;
|
|
765
|
+
/**
|
|
766
|
+
* Middleware capability context for this run. The engine populates it with
|
|
767
|
+
* the live middleware context so harness adapters that declare
|
|
768
|
+
* `requires: [SomeCapability]` can read provided capabilities from inside
|
|
769
|
+
* `chatStream` — e.g. `getSandbox(options.capabilities)`. Capabilities are
|
|
770
|
+
* provisioned by middleware `setup` before the adapter runs. Undefined for
|
|
771
|
+
* direct adapter usage outside the chat engine.
|
|
772
|
+
*/
|
|
773
|
+
capabilities?: CapabilityContext;
|
|
774
|
+
/**
|
|
775
|
+
* Client approval decisions for this run, keyed by approval id. The engine
|
|
776
|
+
* populates this from approvals carried on the incoming messages. Harness
|
|
777
|
+
* adapters consult it to resolve `ask`-policy permission requests (the agent
|
|
778
|
+
* pauses on a risky action; the client re-runs with a decision recorded
|
|
779
|
+
* here). Undefined for direct adapter usage outside the chat engine.
|
|
780
|
+
*/
|
|
781
|
+
approvals?: ReadonlyMap<string, boolean>;
|
|
743
782
|
}
|
|
744
783
|
/**
|
|
745
784
|
* Re-export EventType enum from @ag-ui/core for use in event creation.
|
|
@@ -1082,6 +1121,18 @@ export interface ToolInputAvailableEvent extends CustomEvent {
|
|
|
1082
1121
|
input: unknown;
|
|
1083
1122
|
};
|
|
1084
1123
|
}
|
|
1124
|
+
/** Emitted when an MCP tool returns a ui:// resource (MCP Apps). Reconciled into
|
|
1125
|
+
* a UIResourcePart on the assistant UIMessage. Never enters model input. */
|
|
1126
|
+
export interface UIResourceEvent extends CustomEvent {
|
|
1127
|
+
name: 'ui-resource';
|
|
1128
|
+
value: {
|
|
1129
|
+
resource: UIResourcePart['resource'];
|
|
1130
|
+
serverId?: string;
|
|
1131
|
+
toolCallId: string;
|
|
1132
|
+
toolName: string;
|
|
1133
|
+
meta?: Record<string, unknown>;
|
|
1134
|
+
};
|
|
1135
|
+
}
|
|
1085
1136
|
/**
|
|
1086
1137
|
* Public type for streams returned by `chat({ outputSchema, stream: true })`.
|
|
1087
1138
|
*
|
package/package.json
CHANGED
|
@@ -2,13 +2,14 @@
|
|
|
2
2
|
name: ai-core/adapter-configuration
|
|
3
3
|
description: >
|
|
4
4
|
Provider adapter selection and configuration: openaiText, anthropicText,
|
|
5
|
-
geminiText, ollamaText, grokText, groqText, openRouterText,
|
|
6
|
-
type safety with modelOptions, reasoning/thinking configuration,
|
|
5
|
+
geminiText, ollamaText, grokText, groqText, openRouterText, bedrockText,
|
|
6
|
+
openaiCompatible. Per-model type safety with modelOptions, reasoning/thinking configuration,
|
|
7
7
|
runtime adapter switching, extendAdapter() for custom models, createModel().
|
|
8
8
|
Generic OpenAI-compatible providers (DeepSeek, Together, Fireworks, etc.) via
|
|
9
9
|
openaiCompatible({ baseURL, apiKey, models }) from @tanstack/ai-openai/compatible.
|
|
10
10
|
API key env vars: OPENAI_API_KEY, ANTHROPIC_API_KEY, GOOGLE_API_KEY/GEMINI_API_KEY,
|
|
11
|
-
XAI_API_KEY, GROQ_API_KEY, OPENROUTER_API_KEY, OLLAMA_HOST
|
|
11
|
+
XAI_API_KEY, GROQ_API_KEY, OPENROUTER_API_KEY, OLLAMA_HOST,
|
|
12
|
+
BEDROCK_API_KEY (or AWS_BEARER_TOKEN_BEDROCK).
|
|
12
13
|
type: sub-skill
|
|
13
14
|
library: tanstack-ai
|
|
14
15
|
library_version: '0.10.0'
|
|
@@ -78,6 +79,7 @@ The text adapter is the primary one for chat/completions:
|
|
|
78
79
|
| Groq | `@tanstack/ai-groq` | `groqText` | `GROQ_API_KEY` |
|
|
79
80
|
| OpenRouter | `@tanstack/ai-openrouter` | `openRouterText` | `OPENROUTER_API_KEY` |
|
|
80
81
|
| Ollama | `@tanstack/ai-ollama` | `ollamaText` | `OLLAMA_HOST` (default: `http://localhost:11434`) |
|
|
82
|
+
| Bedrock | `@tanstack/ai-bedrock` | `bedrockText` | `BEDROCK_API_KEY` or `AWS_BEARER_TOKEN_BEDROCK` |
|
|
81
83
|
| OpenAI-compatible | `@tanstack/ai-openai/compatible` | `openaiCompatible` / `openaiCompatibleText` | provider-specific (passed via `apiKey`) |
|
|
82
84
|
|
|
83
85
|
```typescript
|
|
@@ -89,6 +91,7 @@ import { grokText } from '@tanstack/ai-grok'
|
|
|
89
91
|
import { groqText } from '@tanstack/ai-groq'
|
|
90
92
|
import { openRouterText } from '@tanstack/ai-openrouter'
|
|
91
93
|
import { ollamaText } from '@tanstack/ai-ollama'
|
|
94
|
+
import { bedrockText } from '@tanstack/ai-bedrock'
|
|
92
95
|
|
|
93
96
|
// Model string is passed to the factory, NOT to chat()
|
|
94
97
|
const adapter = openaiText('gpt-5.2')
|
|
@@ -98,6 +101,7 @@ const adapter4 = grokText('grok-4')
|
|
|
98
101
|
const adapter5 = groqText('llama-3.3-70b-versatile')
|
|
99
102
|
const adapter6 = openRouterText('anthropic/claude-sonnet-4')
|
|
100
103
|
const adapter7 = ollamaText('llama3.3')
|
|
104
|
+
const adapter8 = bedrockText('us.anthropic.claude-3-7-sonnet-20250219-v1:0')
|
|
101
105
|
|
|
102
106
|
// Optional: pass explicit API key
|
|
103
107
|
const adapterWithKey = openaiText('gpt-5.2', {
|
|
@@ -105,6 +109,14 @@ const adapterWithKey = openaiText('gpt-5.2', {
|
|
|
105
109
|
})
|
|
106
110
|
```
|
|
107
111
|
|
|
112
|
+
`@tanstack/ai-bedrock` (Amazon Bedrock) branches on `config.api`:
|
|
113
|
+
|
|
114
|
+
- `bedrockText(model)` or `bedrockText(model, { api: 'converse' })` (the default) — Bedrock's native Converse API via `@aws-sdk/client-bedrock-runtime` (adapter name `bedrock-converse`). Reaches the broad catalog: Claude, Nova, Llama, Mistral, DeepSeek, and more.
|
|
115
|
+
- `bedrockText(model, { api: 'chat' })` — OpenAI-compatible Chat Completions endpoint (adapter name `bedrock`). Open-weight models only (gpt-oss, DeepSeek V3.x, Gemma, Qwen, etc.). Does NOT reach Claude, Nova, or Llama.
|
|
116
|
+
- `bedrockText(model, { api: 'responses' })` — OpenAI-compatible Responses API, mantle-only (adapter name `bedrock-responses`). Currently gpt-oss family.
|
|
117
|
+
|
|
118
|
+
Use `createBedrockText(model, apiKey, config?)` to pass the key explicitly. Auth resolves from `BEDROCK_API_KEY` / `AWS_BEARER_TOKEN_BEDROCK`, or SigV4 via the standard AWS credential chain (no extra packages needed — handled by `@aws-sdk/client-bedrock-runtime`).
|
|
119
|
+
|
|
108
120
|
### 2. Runtime Adapter Switching
|
|
109
121
|
|
|
110
122
|
Use an adapter factory map to switch providers dynamically based on user
|
|
@@ -397,15 +409,16 @@ Source: docs/migration/migration.md
|
|
|
397
409
|
Each provider uses a specific env var name. Using the wrong one causes a
|
|
398
410
|
runtime error:
|
|
399
411
|
|
|
400
|
-
| Provider | Correct Env Var
|
|
401
|
-
| ---------- |
|
|
402
|
-
| OpenAI | `OPENAI_API_KEY`
|
|
403
|
-
| Anthropic | `ANTHROPIC_API_KEY`
|
|
404
|
-
| Gemini | `GOOGLE_API_KEY` or `GEMINI_API_KEY`
|
|
405
|
-
| Grok (xAI) | `XAI_API_KEY`
|
|
406
|
-
| Groq | `GROQ_API_KEY`
|
|
407
|
-
| OpenRouter | `OPENROUTER_API_KEY`
|
|
408
|
-
| Ollama | `OLLAMA_HOST`
|
|
412
|
+
| Provider | Correct Env Var | Common Mistake |
|
|
413
|
+
| ---------- | ---------------------------------------------- | ------------------------------------------------------------------------ |
|
|
414
|
+
| OpenAI | `OPENAI_API_KEY` | |
|
|
415
|
+
| Anthropic | `ANTHROPIC_API_KEY` | |
|
|
416
|
+
| Gemini | `GOOGLE_API_KEY` or `GEMINI_API_KEY` | `GOOGLE_GENAI_API_KEY` (does not work) |
|
|
417
|
+
| Grok (xAI) | `XAI_API_KEY` | `GROK_API_KEY` (does not work) |
|
|
418
|
+
| Groq | `GROQ_API_KEY` | |
|
|
419
|
+
| OpenRouter | `OPENROUTER_API_KEY` | |
|
|
420
|
+
| Ollama | `OLLAMA_HOST` | No API key needed, just the host URL (default: `http://localhost:11434`) |
|
|
421
|
+
| Bedrock | `BEDROCK_API_KEY` / `AWS_BEARER_TOKEN_BEDROCK` | Falls back to SigV4 credentials when no API key is set |
|
|
409
422
|
|
|
410
423
|
Source: adapter source code (`utils/client.ts` in each adapter package).
|
|
411
424
|
|