@yourgpt/copilot-sdk 2.1.1 → 2.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-33JSFVGH.cjs → chunk-7MZLBGFQ.cjs} +23 -23
- package/dist/{chunk-33JSFVGH.cjs.map → chunk-7MZLBGFQ.cjs.map} +1 -1
- package/dist/{chunk-BRUDSHCV.js → chunk-BMYNG3WM.js} +2 -2
- package/dist/{chunk-BRUDSHCV.js.map → chunk-BMYNG3WM.js.map} +1 -1
- package/dist/{chunk-5UMM5VYB.cjs → chunk-BNBEKK3U.cjs} +77 -31
- package/dist/chunk-BNBEKK3U.cjs.map +1 -0
- package/dist/{chunk-HNRFRNMY.cjs → chunk-CSEZZ5DX.cjs} +2 -2
- package/dist/{chunk-HNRFRNMY.cjs.map → chunk-CSEZZ5DX.cjs.map} +1 -1
- package/dist/{chunk-O33I4HBL.cjs → chunk-GSTTJ46F.cjs} +5 -5
- package/dist/{chunk-O33I4HBL.cjs.map → chunk-GSTTJ46F.cjs.map} +1 -1
- package/dist/{chunk-7YZVSG62.js → chunk-VUHP6TAN.js} +3 -3
- package/dist/{chunk-7YZVSG62.js.map → chunk-VUHP6TAN.js.map} +1 -1
- package/dist/{chunk-SNI7VN2U.js → chunk-VXT2O6R6.js} +53 -7
- package/dist/chunk-VXT2O6R6.js.map +1 -0
- package/dist/{chunk-7PJ4GAJR.js → chunk-XAC7NTIO.js} +4 -4
- package/dist/{chunk-7PJ4GAJR.js.map → chunk-XAC7NTIO.js.map} +1 -1
- package/dist/core/index.cjs +80 -80
- package/dist/core/index.d.cts +3 -3
- package/dist/core/index.d.ts +3 -3
- package/dist/core/index.js +3 -3
- package/dist/{index-25qIYJ21.d.ts → index-Du3Akr_E.d.ts} +1 -1
- package/dist/{index-C261xY-B.d.cts → index-jwRcC2QD.d.cts} +1 -1
- package/dist/mcp/index.d.cts +3 -3
- package/dist/mcp/index.d.ts +3 -3
- package/dist/react/index.cjs +49 -49
- package/dist/react/index.d.cts +25 -5
- package/dist/react/index.d.ts +25 -5
- package/dist/react/index.js +4 -4
- package/dist/tools/anthropic/index.d.cts +1 -1
- package/dist/tools/anthropic/index.d.ts +1 -1
- package/dist/tools/brave/index.cjs +2 -2
- package/dist/tools/brave/index.d.cts +1 -1
- package/dist/tools/brave/index.d.ts +1 -1
- package/dist/tools/brave/index.js +1 -1
- package/dist/tools/exa/index.cjs +2 -2
- package/dist/tools/exa/index.d.cts +1 -1
- package/dist/tools/exa/index.d.ts +1 -1
- package/dist/tools/exa/index.js +1 -1
- package/dist/tools/google/index.cjs +2 -2
- package/dist/tools/google/index.d.cts +1 -1
- package/dist/tools/google/index.d.ts +1 -1
- package/dist/tools/google/index.js +1 -1
- package/dist/tools/openai/index.cjs +2 -2
- package/dist/tools/openai/index.d.cts +1 -1
- package/dist/tools/openai/index.d.ts +1 -1
- package/dist/tools/openai/index.js +1 -1
- package/dist/tools/searxng/index.cjs +2 -2
- package/dist/tools/searxng/index.d.cts +1 -1
- package/dist/tools/searxng/index.d.ts +1 -1
- package/dist/tools/searxng/index.js +1 -1
- package/dist/tools/serper/index.cjs +2 -2
- package/dist/tools/serper/index.d.cts +1 -1
- package/dist/tools/serper/index.d.ts +1 -1
- package/dist/tools/serper/index.js +1 -1
- package/dist/tools/tavily/index.cjs +2 -2
- package/dist/tools/tavily/index.d.cts +1 -1
- package/dist/tools/tavily/index.d.ts +1 -1
- package/dist/tools/tavily/index.js +1 -1
- package/dist/tools/web-search/index.cjs +3 -3
- package/dist/tools/web-search/index.d.cts +2 -2
- package/dist/tools/web-search/index.d.ts +2 -2
- package/dist/tools/web-search/index.js +2 -2
- package/dist/{tools-Clyufshc.d.cts → tools-BHQRB_YT.d.cts} +5 -0
- package/dist/{tools-Clyufshc.d.ts → tools-BHQRB_YT.d.ts} +5 -0
- package/dist/{types-DM6M_pv_.d.cts → types-8_Hp2rmm.d.cts} +1 -1
- package/dist/{types-wudOhedT.d.ts → types-OYi-iUVY.d.ts} +1 -1
- package/dist/ui/index.cjs +39 -18
- package/dist/ui/index.cjs.map +1 -1
- package/dist/ui/index.d.cts +6 -1
- package/dist/ui/index.d.ts +6 -1
- package/dist/ui/index.js +35 -14
- package/dist/ui/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-5UMM5VYB.cjs.map +0 -1
- package/dist/chunk-SNI7VN2U.js.map +0 -1
|
@@ -63,5 +63,5 @@ function failure(error) {
|
|
|
63
63
|
}
|
|
64
64
|
|
|
65
65
|
export { createToolResult, failure, success, tool, toolToAnthropicFormat, toolToOpenAIFormat };
|
|
66
|
-
//# sourceMappingURL=chunk-
|
|
67
|
-
//# sourceMappingURL=chunk-
|
|
66
|
+
//# sourceMappingURL=chunk-BMYNG3WM.js.map
|
|
67
|
+
//# sourceMappingURL=chunk-BMYNG3WM.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/types/tools.ts"],"names":["tool"],"mappings":";AAmwBO,SAAS,KACd,MAAA,EACuC;AACvC,EAAA,OAAO;AAAA,IACL,aAAa,MAAA,CAAO,WAAA;AAAA,IACpB,QAAA,EAAU,OAAO,QAAA,IAAY,QAAA;AAAA;AAAA,IAE7B,OAAO,MAAA,CAAO,KAAA;AAAA,IACd,gBAAgB,MAAA,CAAO,cAAA;AAAA,IACvB,gBAAgB,MAAA,CAAO,cAAA;AAAA;AAAA,IAEvB,WAAA,EAAa,OAAO,WAAA,IAAe;AAAA,MACjC,IAAA,EAAM,QAAA;AAAA,MACN,YAAY,EAAC;AAAA,MACb,UAAU;AAAC,KACb;AAAA,IACA,SAAS,MAAA,CAAO,OAAA;AAAA,IAChB,QAAQ,MAAA,CAAO,MAAA;AAAA,IACf,WAAW,MAAA,CAAO,SAAA;AAAA,IAClB,QAAQ,MAAA,CAAO,MAAA;AAAA,IACf,eAAe,MAAA,CAAO,aAAA;AAAA,IACtB,iBAAiB,MAAA,CAAO,eAAA;AAAA,IACxB,gBAAgB,MAAA,CAAO,cAAA;AAAA,IACvB,WAAW,MAAA,CAAO;AAAA,GACpB;AACF;AASO,SAAS,mBAAmBA,KAAAA,EAA8B;AAC/D,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,UAAA;AAAA,IACN,QAAA,EAAU;AAAA,MACR,MAAMA,KAAAA,CAAK,IAAA;AAAA,MACX,aAAaA,KAAAA,CAAK,WAAA;AAAA,MAClB,YAAYA,KAAAA,CAAK;AAAA;AACnB,GACF;AACF;AAKO,SAAS,sBAAsBA,KAAAA,EAA8B;AAClE,EAAA,OAAO;AAAA,IACL,MAAMA,KAAAA,CAAK,IAAA;AAAA,IACX,aAAaA,KAAAA,CAAK,WAAA;AAAA,IAClB,cAAcA,KAAAA,CAAK;AAAA,GACrB;AACF;AAKO,SAAS,gBAAA,CACd,YACA,QAAA,EACmB;AACnB,EAAA,OAAO;AAAA,IACL,UAAA;AAAA,IACA,OAAA,EAAS,IAAA,CAAK,SAAA,CAAU,QAAQ,CAAA;AAAA,IAChC,SAAS,QAAA,CAAS,OAAA;AAAA,IAClB,OAAO,QAAA,CAAS;AAAA,GAClB;AACF;AAKO,SAAS,OAAA,CACd,MACA,OAAA,EACiB;AACjB,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,IAAA;AAAA,IACT,IAAA;AAAA,IACA;AAAA,GACF;AACF;AAKO,SAAS,QAAQ,KAAA,EAA6B;AACnD,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,KAAA;AAAA,IACT;AAAA,GACF;AACF","file":"chunk-BRUDSHCV.js","sourcesContent":["/**\n * Tool-related types for the agentic loop\n */\n\nimport type { ActionRenderProps } from \"./actions\";\n\n// ============================================\n// Provider Types\n// ============================================\n\n/**\n * Supported AI providers for tool calling\n */\nexport type AIProvider =\n | \"anthropic\"\n | \"openai\"\n | \"xai\"\n | \"grok\"\n | \"gemini\"\n | \"groq\"\n | \"ollama\";\n\n/**\n * Where the tool executes\n */\nexport type ToolLocation = \"server\" | \"client\";\n\n/**\n * Source/origin of the tool\n * - \"mcp\": Tool from an MCP (Model Context Protocol) server\n * - \"native\": Built-in SDK tool\n * - \"custom\": User-defined tool\n */\nexport type ToolSource = \"mcp\" | \"native\" | \"custom\";\n\n// ============================================\n// Tool Definition Types\n// ============================================\n\n/**\n * JSON Schema property definition\n */\nexport interface JSONSchemaProperty {\n type:\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"object\"\n | \"array\"\n | \"integer\"\n | \"null\";\n description?: string;\n enum?: (string | number | boolean)[];\n items?: JSONSchemaProperty;\n properties?: Record<string, JSONSchemaProperty>;\n required?: string[];\n default?: unknown;\n minLength?: number;\n maxLength?: number;\n minimum?: number;\n maximum?: number;\n pattern?: string;\n}\n\n/**\n * JSON Schema for tool input\n */\nexport interface ToolInputSchema {\n type: \"object\";\n properties: Record<string, JSONSchemaProperty>;\n required?: string[];\n additionalProperties?: boolean;\n}\n\n/**\n * Tool execution context\n *\n * Provides runtime information to tool handlers including cancellation signals,\n * request metadata, and custom context data.\n */\nexport interface ToolContext {\n /** Abort signal for cancellation */\n signal?: AbortSignal;\n /** Thread ID if using threads */\n threadId?: string;\n /** Custom context data passed from runtime config */\n data?: Record<string, unknown>;\n\n // ============================================\n // Rich Context (Vercel AI SDK pattern)\n // ============================================\n\n /**\n * Unique ID for this specific tool call.\n * Useful for logging, tracing, and correlating tool executions.\n */\n toolCallId?: string;\n\n /**\n * Request headers (for auth in server tools).\n * Contains headers from the original HTTP request.\n *\n * @example\n * ```typescript\n * handler: async (params, context) => {\n * const token = context?.headers?.authorization;\n * if (!token) return failure('Authentication required');\n * // ...\n * }\n * ```\n */\n headers?: Record<string, string>;\n\n /**\n * Full request metadata for server-side tools.\n * Provides access to HTTP method, URL, and headers.\n *\n * @example\n * ```typescript\n * handler: async (params, context) => {\n * console.log(`Tool called from: ${context?.request?.url}`);\n * // Forward auth to internal service\n * const authHeader = context?.request?.headers?.authorization;\n * }\n * ```\n */\n request?: {\n /** HTTP method (GET, POST, etc.) */\n method?: string;\n /** Request URL path */\n url?: string;\n /** Request headers */\n headers?: Record<string, string>;\n };\n\n /**\n * Data passed from user's approval action.\n * Only present when tool has `needsApproval: true` and user approved with extra data.\n *\n * @example\n * ```typescript\n * // In render function:\n * approval.onApprove({ supervisor: selectedSupervisor });\n *\n * // In handler:\n * handler: async (params, context) => {\n * const supervisor = context?.approvalData?.supervisor;\n * await assignToSupervisor(params.ticketId, supervisor);\n * }\n * ```\n */\n approvalData?: Record<string, unknown>;\n}\n\n// ============================================\n// AI Response Control Types\n// ============================================\n\n/**\n * AI response behavior for tool results.\n *\n * Controls what the AI sees after a tool executes and renders UI.\n *\n * - `'none'`: AI generates minimal response, UI component handles display\n * - `'brief'`: AI gets summary context (via aiContext), gives brief acknowledgment\n * - `'full'`: AI receives full data and responds accordingly (default)\n */\nexport type AIResponseMode = \"none\" | \"brief\" | \"full\";\n\n/**\n * Multimodal content for AI to analyze\n */\nexport type AIContent =\n | { type: \"image\"; data: string; mediaType: string }\n | { type: \"text\"; text: string };\n\n/**\n * Tool response format\n */\nexport interface ToolResponse<T = unknown> {\n /** Whether the tool succeeded */\n success: boolean;\n /** Human-readable message */\n message?: string;\n /** Error message if failed */\n error?: string;\n /** Result data */\n data?: T;\n\n // ============================================\n // AI Response Control (result-level overrides)\n // ============================================\n\n /**\n * Override AI context for this specific result.\n * Takes precedence over tool-level aiContext config.\n * If set, this message is sent to AI instead of full result data.\n *\n * @example\n * ```typescript\n * return {\n * success: true,\n * data: sensitiveData,\n * _aiContext: '[Data retrieved - contains sensitive info, displayed to user]'\n * };\n * ```\n */\n _aiContext?: string;\n\n /**\n * Override AI response mode for this specific result.\n * Takes precedence over tool-level aiResponseMode config.\n */\n _aiResponseMode?: AIResponseMode;\n\n /**\n * Content for AI to analyze (images, documents, etc.).\n * When present, these are included as multimodal content for AI analysis.\n *\n * @example\n * ```typescript\n * // Screenshot for AI to analyze\n * return {\n * success: true,\n * message: 'Screenshot captured',\n * _aiContent: [{ type: 'image', data: base64, mediaType: 'image/png' }]\n * };\n * ```\n */\n _aiContent?: AIContent[];\n\n /**\n * MCP-UI resources for rendering interactive UI components.\n * These are extracted from MCP tool results and rendered as iframes.\n * Not sent to the AI - purely for UI rendering.\n *\n * @example\n * ```typescript\n * // MCP tool returning UI\n * return {\n * success: true,\n * message: 'Product displayed',\n * _uiResources: [{\n * uri: 'ui://shop/product/123',\n * mimeType: 'text/html',\n * content: '<div class=\"product\">...</div>',\n * metadata: { height: '300px' }\n * }]\n * };\n * ```\n */\n _uiResources?: Array<{\n uri: string;\n mimeType:\n | \"text/html\"\n | \"text/uri-list\"\n | \"application/vnd.mcp-ui.remote-dom\";\n content?: string;\n blob?: string;\n metadata?: {\n title?: string;\n width?: string;\n height?: string;\n sandbox?: string[];\n className?: string;\n };\n }>;\n}\n\n/**\n * Approval callbacks passed to render when tool requires user action.\n * Only present when status is \"approval-required\".\n */\nexport interface ToolApprovalCallbacks {\n /**\n * Approve execution and optionally pass extra data to the handler.\n * The extraData is available in handler via `context.approvalData`.\n *\n * @example\n * ```tsx\n * // Simple approval\n * approval.onApprove();\n *\n * // Approval with data (e.g., user selection)\n * approval.onApprove({ supervisor: { name: \"John\", role: \"Manager\" } });\n * ```\n */\n onApprove: (extraData?: Record<string, unknown>) => void;\n\n /**\n * Reject the tool execution with optional reason.\n * This stops the tool from executing and returns an error to AI.\n */\n onReject: (reason?: string) => void;\n\n /** Custom message from tool's approvalMessage config */\n message?: string;\n}\n\n/**\n * Props passed to tool render function.\n *\n * The render function is called for every status change, enabling\n * full lifecycle rendering similar to Vercel AI SDK.\n *\n * @example\n * ```tsx\n * render: ({ status, args, approval, result }) => {\n * if (status === \"approval-required\" && approval) {\n * return <ApprovalCard onConfirm={() => approval.onApprove()} />;\n * }\n * if (status === \"executing\") {\n * return <LoadingSkeleton />;\n * }\n * if (status === \"completed\") {\n * return <ResultCard data={result.data} />;\n * }\n * return null;\n * }\n * ```\n */\nexport interface ToolRenderProps<TParams = Record<string, unknown>> {\n /**\n * Current execution status:\n * - `pending`: Tool call received, waiting to start\n * - `approval-required`: Waiting for user approval (when needsApproval is set)\n * - `executing`: Handler is running\n * - `completed`: Handler finished successfully\n * - `error`: Handler failed\n */\n status: \"pending\" | \"approval-required\" | \"executing\" | \"completed\" | \"error\";\n\n /** Arguments passed to the tool */\n args: TParams;\n\n /** Result if completed */\n result?: ToolResponse;\n\n /** Error if failed */\n error?: string;\n\n /** Tool call ID */\n toolCallId: string;\n\n /** Tool name */\n toolName: string;\n\n /**\n * Approval callbacks - only present when status is \"approval-required\".\n * Use these to create custom approval UIs that can pass extra data to the handler.\n */\n approval?: ToolApprovalCallbacks;\n}\n\n/**\n * Tool definition with JSON Schema\n */\nexport interface ToolDefinition<TParams = Record<string, unknown>> {\n /** Unique tool name */\n name: string;\n /** Tool description for LLM */\n description: string;\n /** Where the tool executes (server or client) */\n location: ToolLocation;\n /**\n * Source/origin of the tool.\n * Used to distinguish MCP tools from native/custom tools for UI rendering.\n * @default \"custom\"\n */\n source?: ToolSource;\n\n // ============================================\n // Display Configuration\n // ============================================\n\n /**\n * Human-readable title for UI display.\n * Can be a static string or a function that generates title from args.\n *\n * @example\n * ```typescript\n * title: \"Get order details\"\n * // or dynamic:\n * title: (args) => `Order #${args.orderId}`\n * ```\n */\n title?: string | ((args: TParams) => string);\n\n /**\n * Title shown while executing (present tense with \"...\").\n * If not provided, uses `title` with \"...\" appended.\n *\n * @example\n * ```typescript\n * executingTitle: (args) => `Fetching order #${args.orderId}...`\n * ```\n */\n executingTitle?: string | ((args: TParams) => string);\n\n /**\n * Title shown after completion.\n * If not provided, defaults to `title`.\n *\n * @example\n * ```typescript\n * completedTitle: (args) => `Retrieved order #${args.orderId}`\n * ```\n */\n completedTitle?: string | ((args: TParams) => string);\n /** JSON Schema for input parameters */\n inputSchema: ToolInputSchema;\n /** Handler function (optional for client tools registered on server) */\n handler?: (\n params: TParams,\n context?: ToolContext,\n ) => Promise<ToolResponse> | ToolResponse;\n /** Optional render function for UI */\n render?: (props: ToolRenderProps<TParams>) => unknown;\n /** Whether the tool is available (for conditional registration) */\n available?: boolean;\n\n /**\n * Hide this tool's execution from the chat UI.\n * When true, tool calls and results won't be displayed to the user,\n * but the tool will still execute normally.\n * @default false\n */\n hidden?: boolean;\n\n /**\n * Require user approval before execution.\n * Can be:\n * - `true`: Always require approval\n * - `false` or `undefined`: No approval needed (default)\n * - `(params) => boolean`: Conditional approval based on input\n *\n * Similar to Vercel AI SDK v6's needsApproval pattern.\n */\n needsApproval?: boolean | ((params: TParams) => boolean | Promise<boolean>);\n\n /**\n * Custom message shown in the approval UI.\n * Can be a string or a function that generates a message from params.\n * If not provided, a default message with the tool name is shown.\n */\n approvalMessage?: string | ((params: TParams) => string);\n\n // ============================================\n // AI Response Control\n // ============================================\n\n /**\n * How the AI should respond when this tool's result is rendered as UI.\n *\n * - `'none'`: AI generates minimal response (\"[Result displayed to user]\").\n * Use for tools where UI component fully handles the display (stats cards, etc.)\n *\n * - `'brief'`: AI receives summary context (from aiContext) and gives brief acknowledgment.\n * Use for charts/visualizations where AI should acknowledge but not repeat data.\n *\n * - `'full'`: AI receives complete data and responds accordingly (default).\n * Use for tools where AI should analyze and elaborate on results.\n *\n * @default 'full'\n *\n * @example\n * ```typescript\n * // Chart tool - AI acknowledges without repeating data\n * const chartTool: ToolDefinition = {\n * name: 'get_chart',\n * aiResponseMode: 'brief',\n * aiContext: (result) => `[Chart displayed: ${result.data.title}]`,\n * handler: async () => ({ success: true, data: chartData })\n * };\n * ```\n */\n aiResponseMode?: AIResponseMode;\n\n /**\n * Context/summary sent to AI instead of (or along with) full result.\n *\n * Used when:\n * - `aiResponseMode: 'brief'` - This becomes the only thing AI sees\n * - `aiResponseMode: 'full'` - This is prepended to full data for context\n *\n * Can be:\n * - `string`: Static message (e.g., \"[Weather data displayed]\")\n * - `function`: Dynamic based on result (e.g., (result) => `[Chart: ${result.data.title}]`)\n *\n * @example\n * ```typescript\n * // Static context\n * aiContext: '[Analytics chart displayed to user]'\n *\n * // Dynamic context based on result\n * aiContext: (result, args) => {\n * const { title, currentValue } = result.data;\n * return `[Chart displayed: ${title}, showing ${currentValue}]`;\n * }\n * ```\n */\n aiContext?:\n | string\n | ((result: ToolResponse, args: Record<string, unknown>) => string);\n}\n\n// ============================================\n// Unified Tool Call Types (Provider-Agnostic)\n// ============================================\n\n/**\n * Unified tool call format (internal representation)\n */\nexport interface UnifiedToolCall {\n /** Unique tool call ID */\n id: string;\n /** Tool name */\n name: string;\n /** Tool input arguments */\n input: Record<string, unknown>;\n}\n\n/**\n * Unified tool result format\n */\nexport interface UnifiedToolResult {\n /** Tool call ID this result is for */\n toolCallId: string;\n /** Serialized result content (JSON string) */\n content: string;\n /** Whether the tool succeeded */\n success: boolean;\n /** Error message if failed */\n error?: string;\n}\n\n// ============================================\n// Tool Execution Types\n// ============================================\n\n/**\n * Tool execution status\n */\nexport type ToolExecutionStatus =\n | \"pending\"\n | \"executing\"\n | \"completed\"\n | \"error\";\n\n/**\n * Tool approval status (for human-in-the-loop)\n *\n * Similar to Vercel AI SDK v6's tool approval pattern.\n */\nexport type ToolApprovalStatus =\n | \"none\" // No approval needed (default)\n | \"required\" // Waiting for user decision\n | \"approved\" // User approved, execution can proceed\n | \"rejected\"; // User rejected, execution skipped\n\n// ============================================\n// Permission Persistence Types\n// ============================================\n\n/**\n * Permission level for tool execution\n *\n * Controls whether approval is needed and how the choice is remembered:\n * - \"ask\" - Always prompt user (default)\n * - \"allow_always\" - Auto-approve, persisted to storage\n * - \"deny_always\" - Auto-reject, persisted to storage\n * - \"session\" - Auto-approve for current session only\n */\nexport type PermissionLevel =\n | \"ask\"\n | \"allow_always\"\n | \"deny_always\"\n | \"session\";\n\n/**\n * Stored tool permission record\n */\nexport interface ToolPermission {\n /** Tool name (unique identifier) */\n toolName: string;\n /** Permission level */\n level: PermissionLevel;\n /** When permission was set */\n createdAt: number;\n /** Last time this permission was used */\n lastUsedAt?: number;\n}\n\n/**\n * Permission storage configuration\n */\nexport interface PermissionStorageConfig {\n /**\n * Storage type:\n * - \"localStorage\" - Persists across browser sessions\n * - \"sessionStorage\" - Clears when tab closes\n * - \"memory\" - In-memory only (for SSR or testing)\n */\n type: \"localStorage\" | \"sessionStorage\" | \"memory\";\n /** Storage key prefix (default: \"yourgpt-permissions\") */\n keyPrefix?: string;\n}\n\n/**\n * Permission storage adapter interface (for custom implementations)\n */\nexport interface PermissionStorageAdapter {\n /** Get permission for a tool */\n get(toolName: string): Promise<ToolPermission | null>;\n /** Set permission for a tool */\n set(permission: ToolPermission): Promise<void>;\n /** Remove permission for a tool */\n remove(toolName: string): Promise<void>;\n /** Get all permissions */\n getAll(): Promise<ToolPermission[]>;\n /** Clear all permissions */\n clear(): Promise<void>;\n}\n\n/**\n * Tool execution record (for UI tracking)\n */\nexport interface ToolExecution {\n /** Tool call ID */\n id: string;\n /** Tool name */\n name: string;\n /** Tool arguments */\n args: Record<string, unknown>;\n /** Execution status */\n status: ToolExecutionStatus;\n /** Result if completed */\n result?: ToolResponse;\n /** Error message if failed */\n error?: string;\n /** Timestamp when execution started */\n timestamp: number;\n /** Duration in ms (set when completed) */\n duration?: number;\n\n // Approval fields (for needsApproval tools)\n\n /** Approval status for this execution */\n approvalStatus: ToolApprovalStatus;\n /** Message shown in approval UI (from tool's approvalMessage) */\n approvalMessage?: string;\n /** Timestamp when user responded to approval request */\n approvalTimestamp?: number;\n}\n\n// ============================================\n// Agent Loop Types\n// ============================================\n\n/**\n * Agentic loop configuration\n */\nexport interface AgentLoopConfig {\n /** Maximum iterations before stopping (default: 20) */\n maxIterations?: number;\n /** Enable debug logging */\n debug?: boolean;\n /** Whether to enable the agentic loop (default: true) */\n enabled?: boolean;\n}\n\n/**\n * Agent loop state (for tracking)\n */\nexport interface AgentLoopState {\n /** Current iteration number */\n iteration: number;\n /** Maximum iterations allowed */\n maxIterations: number;\n /** Whether the loop is currently running */\n running: boolean;\n /** Whether max iterations was reached */\n maxIterationsReached: boolean;\n /** Whether the loop was aborted */\n aborted: boolean;\n}\n\n// ============================================\n// ToolSet Type (Vercel AI SDK pattern)\n// ============================================\n\n/**\n * A set of tools, keyed by tool name\n *\n * @example\n * ```typescript\n * const myTools: ToolSet = {\n * capture_screenshot: screenshotTool,\n * get_weather: weatherTool,\n * };\n * ```\n */\nexport type ToolSet = Record<string, ToolDefinition>;\n\n// ============================================\n// Tool Helper Function (Vercel AI SDK pattern)\n// ============================================\n\n/**\n * Configuration for creating a tool\n */\nexport interface ToolConfig<TParams = Record<string, unknown>> {\n /** Tool description for LLM */\n description: string;\n /** Where the tool executes (default: 'client') */\n location?: ToolLocation;\n\n // Display Configuration\n /** Human-readable title for UI display */\n title?: string | ((args: TParams) => string);\n /** Title shown while executing */\n executingTitle?: string | ((args: TParams) => string);\n /** Title shown after completion */\n completedTitle?: string | ((args: TParams) => string);\n\n /** JSON Schema for input parameters */\n inputSchema?: ToolInputSchema;\n /** Handler function */\n handler?: (\n params: TParams,\n context?: ToolContext,\n ) => Promise<ToolResponse> | ToolResponse;\n /** Optional render function for UI */\n render?: (props: ToolRenderProps<TParams>) => unknown;\n /** Whether the tool is available */\n available?: boolean;\n /** Hide this tool from chat UI display */\n hidden?: boolean;\n /** Require user approval before execution */\n needsApproval?: boolean | ((params: TParams) => boolean | Promise<boolean>);\n /** Custom message shown in the approval UI */\n approvalMessage?: string | ((params: TParams) => string);\n /** AI response mode for this tool (default: 'full') */\n aiResponseMode?: AIResponseMode;\n /** Context/summary sent to AI instead of full result */\n aiContext?:\n | string\n | ((result: ToolResponse, args: Record<string, unknown>) => string);\n}\n\n/**\n * Create a tool definition (similar to Vercel AI SDK's tool())\n *\n * @example\n * ```typescript\n * const weatherTool = tool({\n * description: 'Get weather for a location',\n * inputSchema: {\n * type: 'object',\n * properties: {\n * location: { type: 'string', description: 'City name' },\n * },\n * required: ['location'],\n * },\n * handler: async ({ location }) => {\n * const weather = await fetchWeather(location);\n * return success(weather);\n * },\n * });\n * ```\n */\nexport function tool<TParams = Record<string, unknown>>(\n config: ToolConfig<TParams>,\n): Omit<ToolDefinition<TParams>, \"name\"> {\n return {\n description: config.description,\n location: config.location ?? \"client\",\n // Display configuration\n title: config.title,\n executingTitle: config.executingTitle,\n completedTitle: config.completedTitle,\n // Schema and handlers\n inputSchema: config.inputSchema ?? {\n type: \"object\",\n properties: {},\n required: [],\n },\n handler: config.handler,\n render: config.render,\n available: config.available,\n hidden: config.hidden,\n needsApproval: config.needsApproval,\n approvalMessage: config.approvalMessage,\n aiResponseMode: config.aiResponseMode,\n aiContext: config.aiContext,\n };\n}\n\n// ============================================\n// Helper Functions\n// ============================================\n\n/**\n * Convert ToolDefinition to OpenAI tool format\n */\nexport function toolToOpenAIFormat(tool: ToolDefinition): object {\n return {\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n },\n };\n}\n\n/**\n * Convert ToolDefinition to Anthropic tool format\n */\nexport function toolToAnthropicFormat(tool: ToolDefinition): object {\n return {\n name: tool.name,\n description: tool.description,\n input_schema: tool.inputSchema,\n };\n}\n\n/**\n * Create a tool result response\n */\nexport function createToolResult(\n toolCallId: string,\n response: ToolResponse,\n): UnifiedToolResult {\n return {\n toolCallId,\n content: JSON.stringify(response),\n success: response.success,\n error: response.error,\n };\n}\n\n/**\n * Create a successful tool response\n */\nexport function success<T = unknown>(\n data?: T,\n message?: string,\n): ToolResponse<T> {\n return {\n success: true,\n data,\n message,\n };\n}\n\n/**\n * Create a failed tool response\n */\nexport function failure(error: string): ToolResponse {\n return {\n success: false,\n error,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/types/tools.ts"],"names":["tool"],"mappings":";AAywBO,SAAS,KACd,MAAA,EACuC;AACvC,EAAA,OAAO;AAAA,IACL,aAAa,MAAA,CAAO,WAAA;AAAA,IACpB,QAAA,EAAU,OAAO,QAAA,IAAY,QAAA;AAAA;AAAA,IAE7B,OAAO,MAAA,CAAO,KAAA;AAAA,IACd,gBAAgB,MAAA,CAAO,cAAA;AAAA,IACvB,gBAAgB,MAAA,CAAO,cAAA;AAAA;AAAA,IAEvB,WAAA,EAAa,OAAO,WAAA,IAAe;AAAA,MACjC,IAAA,EAAM,QAAA;AAAA,MACN,YAAY,EAAC;AAAA,MACb,UAAU;AAAC,KACb;AAAA,IACA,SAAS,MAAA,CAAO,OAAA;AAAA,IAChB,QAAQ,MAAA,CAAO,MAAA;AAAA,IACf,WAAW,MAAA,CAAO,SAAA;AAAA,IAClB,QAAQ,MAAA,CAAO,MAAA;AAAA,IACf,eAAe,MAAA,CAAO,aAAA;AAAA,IACtB,iBAAiB,MAAA,CAAO,eAAA;AAAA,IACxB,gBAAgB,MAAA,CAAO,cAAA;AAAA,IACvB,WAAW,MAAA,CAAO;AAAA,GACpB;AACF;AASO,SAAS,mBAAmBA,KAAAA,EAA8B;AAC/D,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,UAAA;AAAA,IACN,QAAA,EAAU;AAAA,MACR,MAAMA,KAAAA,CAAK,IAAA;AAAA,MACX,aAAaA,KAAAA,CAAK,WAAA;AAAA,MAClB,YAAYA,KAAAA,CAAK;AAAA;AACnB,GACF;AACF;AAKO,SAAS,sBAAsBA,KAAAA,EAA8B;AAClE,EAAA,OAAO;AAAA,IACL,MAAMA,KAAAA,CAAK,IAAA;AAAA,IACX,aAAaA,KAAAA,CAAK,WAAA;AAAA,IAClB,cAAcA,KAAAA,CAAK;AAAA,GACrB;AACF;AAKO,SAAS,gBAAA,CACd,YACA,QAAA,EACmB;AACnB,EAAA,OAAO;AAAA,IACL,UAAA;AAAA,IACA,OAAA,EAAS,IAAA,CAAK,SAAA,CAAU,QAAQ,CAAA;AAAA,IAChC,SAAS,QAAA,CAAS,OAAA;AAAA,IAClB,OAAO,QAAA,CAAS;AAAA,GAClB;AACF;AAKO,SAAS,OAAA,CACd,MACA,OAAA,EACiB;AACjB,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,IAAA;AAAA,IACT,IAAA;AAAA,IACA;AAAA,GACF;AACF;AAKO,SAAS,QAAQ,KAAA,EAA6B;AACnD,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,KAAA;AAAA,IACT;AAAA,GACF;AACF","file":"chunk-BMYNG3WM.js","sourcesContent":["/**\n * Tool-related types for the agentic loop\n */\n\nimport type { ActionRenderProps } from \"./actions\";\n\n// ============================================\n// Provider Types\n// ============================================\n\n/**\n * Supported AI providers for tool calling\n */\nexport type AIProvider =\n | \"anthropic\"\n | \"openai\"\n | \"xai\"\n | \"grok\"\n | \"gemini\"\n | \"groq\"\n | \"ollama\";\n\n/**\n * Where the tool executes\n */\nexport type ToolLocation = \"server\" | \"client\";\n\n/**\n * Source/origin of the tool\n * - \"mcp\": Tool from an MCP (Model Context Protocol) server\n * - \"native\": Built-in SDK tool\n * - \"custom\": User-defined tool\n */\nexport type ToolSource = \"mcp\" | \"native\" | \"custom\";\n\n// ============================================\n// Tool Definition Types\n// ============================================\n\n/**\n * JSON Schema property definition\n */\nexport interface JSONSchemaProperty {\n type:\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"object\"\n | \"array\"\n | \"integer\"\n | \"null\";\n description?: string;\n enum?: (string | number | boolean)[];\n items?: JSONSchemaProperty;\n properties?: Record<string, JSONSchemaProperty>;\n required?: string[];\n default?: unknown;\n minLength?: number;\n maxLength?: number;\n minimum?: number;\n maximum?: number;\n pattern?: string;\n}\n\n/**\n * JSON Schema for tool input\n */\nexport interface ToolInputSchema {\n type: \"object\";\n properties: Record<string, JSONSchemaProperty>;\n required?: string[];\n additionalProperties?: boolean;\n}\n\n/**\n * Tool execution context\n *\n * Provides runtime information to tool handlers including cancellation signals,\n * request metadata, and custom context data.\n */\nexport interface ToolContext {\n /** Abort signal for cancellation */\n signal?: AbortSignal;\n /** Thread ID if using threads */\n threadId?: string;\n /** Custom context data passed from runtime config */\n data?: Record<string, unknown>;\n\n // ============================================\n // Rich Context (Vercel AI SDK pattern)\n // ============================================\n\n /**\n * Unique ID for this specific tool call.\n * Useful for logging, tracing, and correlating tool executions.\n */\n toolCallId?: string;\n\n /**\n * Request headers (for auth in server tools).\n * Contains headers from the original HTTP request.\n *\n * @example\n * ```typescript\n * handler: async (params, context) => {\n * const token = context?.headers?.authorization;\n * if (!token) return failure('Authentication required');\n * // ...\n * }\n * ```\n */\n headers?: Record<string, string>;\n\n /**\n * Full request metadata for server-side tools.\n * Provides access to HTTP method, URL, and headers.\n *\n * @example\n * ```typescript\n * handler: async (params, context) => {\n * console.log(`Tool called from: ${context?.request?.url}`);\n * // Forward auth to internal service\n * const authHeader = context?.request?.headers?.authorization;\n * }\n * ```\n */\n request?: {\n /** HTTP method (GET, POST, etc.) */\n method?: string;\n /** Request URL path */\n url?: string;\n /** Request headers */\n headers?: Record<string, string>;\n };\n\n /**\n * Data passed from user's approval action.\n * Only present when tool has `needsApproval: true` and user approved with extra data.\n *\n * @example\n * ```typescript\n * // In render function:\n * approval.onApprove({ supervisor: selectedSupervisor });\n *\n * // In handler:\n * handler: async (params, context) => {\n * const supervisor = context?.approvalData?.supervisor;\n * await assignToSupervisor(params.ticketId, supervisor);\n * }\n * ```\n */\n approvalData?: Record<string, unknown>;\n}\n\n// ============================================\n// AI Response Control Types\n// ============================================\n\n/**\n * AI response behavior for tool results.\n *\n * Controls what the AI sees after a tool executes and renders UI.\n *\n * - `'none'`: AI generates minimal response, UI component handles display\n * - `'brief'`: AI gets summary context (via aiContext), gives brief acknowledgment\n * - `'full'`: AI receives full data and responds accordingly (default)\n */\nexport type AIResponseMode = \"none\" | \"brief\" | \"full\";\n\n/**\n * Multimodal content for AI to analyze\n */\nexport type AIContent =\n | { type: \"image\"; data: string; mediaType: string }\n | { type: \"text\"; text: string };\n\n/**\n * Tool response format\n */\nexport interface ToolResponse<T = unknown> {\n /** Whether the tool succeeded */\n success: boolean;\n /** Human-readable message */\n message?: string;\n /** Error message if failed */\n error?: string;\n /** Result data */\n data?: T;\n\n // ============================================\n // AI Response Control (result-level overrides)\n // ============================================\n\n /**\n * Override AI context for this specific result.\n * Takes precedence over tool-level aiContext config.\n * If set, this message is sent to AI instead of full result data.\n *\n * @example\n * ```typescript\n * return {\n * success: true,\n * data: sensitiveData,\n * _aiContext: '[Data retrieved - contains sensitive info, displayed to user]'\n * };\n * ```\n */\n _aiContext?: string;\n\n /**\n * Override AI response mode for this specific result.\n * Takes precedence over tool-level aiResponseMode config.\n */\n _aiResponseMode?: AIResponseMode;\n\n /**\n * Content for AI to analyze (images, documents, etc.).\n * When present, these are included as multimodal content for AI analysis.\n *\n * @example\n * ```typescript\n * // Screenshot for AI to analyze\n * return {\n * success: true,\n * message: 'Screenshot captured',\n * _aiContent: [{ type: 'image', data: base64, mediaType: 'image/png' }]\n * };\n * ```\n */\n _aiContent?: AIContent[];\n\n /**\n * MCP-UI resources for rendering interactive UI components.\n * These are extracted from MCP tool results and rendered as iframes.\n * Not sent to the AI - purely for UI rendering.\n *\n * @example\n * ```typescript\n * // MCP tool returning UI\n * return {\n * success: true,\n * message: 'Product displayed',\n * _uiResources: [{\n * uri: 'ui://shop/product/123',\n * mimeType: 'text/html',\n * content: '<div class=\"product\">...</div>',\n * metadata: { height: '300px' }\n * }]\n * };\n * ```\n */\n _uiResources?: Array<{\n uri: string;\n mimeType:\n | \"text/html\"\n | \"text/uri-list\"\n | \"application/vnd.mcp-ui.remote-dom\";\n content?: string;\n blob?: string;\n metadata?: {\n title?: string;\n width?: string;\n height?: string;\n sandbox?: string[];\n className?: string;\n };\n }>;\n}\n\n/**\n * Approval callbacks passed to render when tool requires user action.\n * Only present when status is \"approval-required\".\n */\nexport interface ToolApprovalCallbacks {\n /**\n * Approve execution and optionally pass extra data to the handler.\n * The extraData is available in handler via `context.approvalData`.\n *\n * @example\n * ```tsx\n * // Simple approval\n * approval.onApprove();\n *\n * // Approval with data (e.g., user selection)\n * approval.onApprove({ supervisor: { name: \"John\", role: \"Manager\" } });\n * ```\n */\n onApprove: (extraData?: Record<string, unknown>) => void;\n\n /**\n * Reject the tool execution with optional reason.\n * This stops the tool from executing and returns an error to AI.\n */\n onReject: (reason?: string) => void;\n\n /** Custom message from tool's approvalMessage config */\n message?: string;\n}\n\n/**\n * Props passed to tool render function.\n *\n * The render function is called for every status change, enabling\n * full lifecycle rendering similar to Vercel AI SDK.\n *\n * @example\n * ```tsx\n * render: ({ status, args, approval, result }) => {\n * if (status === \"approval-required\" && approval) {\n * return <ApprovalCard onConfirm={() => approval.onApprove()} />;\n * }\n * if (status === \"executing\") {\n * return <LoadingSkeleton />;\n * }\n * if (status === \"completed\") {\n * return <ResultCard data={result.data} />;\n * }\n * return null;\n * }\n * ```\n */\nexport interface ToolRenderProps<TParams = Record<string, unknown>> {\n /**\n * Current execution status:\n * - `pending`: Tool call received, waiting to start\n * - `approval-required`: Waiting for user approval (when needsApproval is set)\n * - `executing`: Handler is running\n * - `completed`: Handler finished successfully\n * - `error`: Handler failed\n */\n status: \"pending\" | \"approval-required\" | \"executing\" | \"completed\" | \"error\";\n\n /** Arguments passed to the tool */\n args: TParams;\n\n /** Result if completed */\n result?: ToolResponse;\n\n /** Error if failed */\n error?: string;\n\n /** Tool call ID */\n toolCallId: string;\n\n /** Tool name */\n toolName: string;\n\n /**\n * Approval callbacks - only present when status is \"approval-required\".\n * Use these to create custom approval UIs that can pass extra data to the handler.\n */\n approval?: ToolApprovalCallbacks;\n}\n\n/**\n * Tool definition with JSON Schema\n */\nexport interface ToolDefinition<TParams = Record<string, unknown>> {\n /** Unique tool name */\n name: string;\n /** Tool description for LLM */\n description: string;\n /** Where the tool executes (server or client) */\n location: ToolLocation;\n /**\n * Source/origin of the tool.\n * Used to distinguish MCP tools from native/custom tools for UI rendering.\n * @default \"custom\"\n */\n source?: ToolSource;\n\n // ============================================\n // Display Configuration\n // ============================================\n\n /**\n * Human-readable title for UI display.\n * Can be a static string or a function that generates title from args.\n *\n * @example\n * ```typescript\n * title: \"Get order details\"\n * // or dynamic:\n * title: (args) => `Order #${args.orderId}`\n * ```\n */\n title?: string | ((args: TParams) => string);\n\n /**\n * Title shown while executing (present tense with \"...\").\n * If not provided, uses `title` with \"...\" appended.\n *\n * @example\n * ```typescript\n * executingTitle: (args) => `Fetching order #${args.orderId}...`\n * ```\n */\n executingTitle?: string | ((args: TParams) => string);\n\n /**\n * Title shown after completion.\n * If not provided, defaults to `title`.\n *\n * @example\n * ```typescript\n * completedTitle: (args) => `Retrieved order #${args.orderId}`\n * ```\n */\n completedTitle?: string | ((args: TParams) => string);\n /** JSON Schema for input parameters */\n inputSchema: ToolInputSchema;\n /** Handler function (optional for client tools registered on server) */\n handler?: (\n params: TParams,\n context?: ToolContext,\n ) => Promise<ToolResponse> | ToolResponse;\n /** Optional render function for UI */\n render?: (props: ToolRenderProps<TParams>) => unknown;\n /** Whether the tool is available (for conditional registration) */\n available?: boolean;\n\n /**\n * Hide this tool's execution from the chat UI.\n * When true, tool calls and results won't be displayed to the user,\n * but the tool will still execute normally.\n * @default false\n */\n hidden?: boolean;\n\n /**\n * Require user approval before execution.\n * Can be:\n * - `true`: Always require approval\n * - `false` or `undefined`: No approval needed (default)\n * - `(params) => boolean`: Conditional approval based on input\n *\n * Similar to Vercel AI SDK v6's needsApproval pattern.\n */\n needsApproval?: boolean | ((params: TParams) => boolean | Promise<boolean>);\n\n /**\n * Custom message shown in the approval UI.\n * Can be a string or a function that generates a message from params.\n * If not provided, a default message with the tool name is shown.\n */\n approvalMessage?: string | ((params: TParams) => string);\n\n // ============================================\n // AI Response Control\n // ============================================\n\n /**\n * How the AI should respond when this tool's result is rendered as UI.\n *\n * - `'none'`: AI generates minimal response (\"[Result displayed to user]\").\n * Use for tools where UI component fully handles the display (stats cards, etc.)\n *\n * - `'brief'`: AI receives summary context (from aiContext) and gives brief acknowledgment.\n * Use for charts/visualizations where AI should acknowledge but not repeat data.\n *\n * - `'full'`: AI receives complete data and responds accordingly (default).\n * Use for tools where AI should analyze and elaborate on results.\n *\n * @default 'full'\n *\n * @example\n * ```typescript\n * // Chart tool - AI acknowledges without repeating data\n * const chartTool: ToolDefinition = {\n * name: 'get_chart',\n * aiResponseMode: 'brief',\n * aiContext: (result) => `[Chart displayed: ${result.data.title}]`,\n * handler: async () => ({ success: true, data: chartData })\n * };\n * ```\n */\n aiResponseMode?: AIResponseMode;\n\n /**\n * Context/summary sent to AI instead of (or along with) full result.\n *\n * Used when:\n * - `aiResponseMode: 'brief'` - This becomes the only thing AI sees\n * - `aiResponseMode: 'full'` - This is prepended to full data for context\n *\n * Can be:\n * - `string`: Static message (e.g., \"[Weather data displayed]\")\n * - `function`: Dynamic based on result (e.g., (result) => `[Chart: ${result.data.title}]`)\n *\n * @example\n * ```typescript\n * // Static context\n * aiContext: '[Analytics chart displayed to user]'\n *\n * // Dynamic context based on result\n * aiContext: (result, args) => {\n * const { title, currentValue } = result.data;\n * return `[Chart displayed: ${title}, showing ${currentValue}]`;\n * }\n * ```\n */\n aiContext?:\n | string\n | ((result: ToolResponse, args: Record<string, unknown>) => string);\n}\n\n// ============================================\n// Unified Tool Call Types (Provider-Agnostic)\n// ============================================\n\n/**\n * Unified tool call format (internal representation)\n */\nexport interface UnifiedToolCall {\n /** Unique tool call ID */\n id: string;\n /** Tool name */\n name: string;\n /** Tool input arguments */\n input: Record<string, unknown>;\n}\n\n/**\n * Unified tool result format\n */\nexport interface UnifiedToolResult {\n /** Tool call ID this result is for */\n toolCallId: string;\n /** Serialized result content (JSON string) */\n content: string;\n /** Whether the tool succeeded */\n success: boolean;\n /** Error message if failed */\n error?: string;\n}\n\n// ============================================\n// Tool Execution Types\n// ============================================\n\n/**\n * Tool execution status\n */\nexport type ToolExecutionStatus =\n | \"pending\"\n | \"executing\"\n | \"completed\"\n | \"error\";\n\n/**\n * Tool approval status (for human-in-the-loop)\n *\n * Similar to Vercel AI SDK v6's tool approval pattern.\n */\nexport type ToolApprovalStatus =\n | \"none\" // No approval needed (default)\n | \"required\" // Waiting for user decision\n | \"approved\" // User approved, execution can proceed\n | \"rejected\"; // User rejected, execution skipped\n\n// ============================================\n// Permission Persistence Types\n// ============================================\n\n/**\n * Permission level for tool execution\n *\n * Controls whether approval is needed and how the choice is remembered:\n * - \"ask\" - Always prompt user (default)\n * - \"allow_always\" - Auto-approve, persisted to storage\n * - \"deny_always\" - Auto-reject, persisted to storage\n * - \"session\" - Auto-approve for current session only\n */\nexport type PermissionLevel =\n | \"ask\"\n | \"allow_always\"\n | \"deny_always\"\n | \"session\";\n\n/**\n * Stored tool permission record\n */\nexport interface ToolPermission {\n /** Tool name (unique identifier) */\n toolName: string;\n /** Permission level */\n level: PermissionLevel;\n /** When permission was set */\n createdAt: number;\n /** Last time this permission was used */\n lastUsedAt?: number;\n}\n\n/**\n * Permission storage configuration\n */\nexport interface PermissionStorageConfig {\n /**\n * Storage type:\n * - \"localStorage\" - Persists across browser sessions\n * - \"sessionStorage\" - Clears when tab closes\n * - \"memory\" - In-memory only (for SSR or testing)\n */\n type: \"localStorage\" | \"sessionStorage\" | \"memory\";\n /** Storage key prefix (default: \"yourgpt-permissions\") */\n keyPrefix?: string;\n}\n\n/**\n * Permission storage adapter interface (for custom implementations)\n */\nexport interface PermissionStorageAdapter {\n /** Get permission for a tool */\n get(toolName: string): Promise<ToolPermission | null>;\n /** Set permission for a tool */\n set(permission: ToolPermission): Promise<void>;\n /** Remove permission for a tool */\n remove(toolName: string): Promise<void>;\n /** Get all permissions */\n getAll(): Promise<ToolPermission[]>;\n /** Clear all permissions */\n clear(): Promise<void>;\n}\n\n/**\n * Tool execution record (for UI tracking)\n */\nexport interface ToolExecution {\n /** Tool call ID */\n id: string;\n /** Tool name */\n name: string;\n /** Tool arguments */\n args: Record<string, unknown>;\n /** Execution status */\n status: ToolExecutionStatus;\n /** Result if completed */\n result?: ToolResponse;\n /** Error message if failed */\n error?: string;\n /** Timestamp when execution started */\n timestamp: number;\n /** Duration in ms (set when completed) */\n duration?: number;\n\n // Approval fields (for needsApproval tools)\n\n /** Approval status for this execution */\n approvalStatus: ToolApprovalStatus;\n /** Message shown in approval UI (from tool's approvalMessage) */\n approvalMessage?: string;\n /** Timestamp when user responded to approval request */\n approvalTimestamp?: number;\n\n /**\n * Whether this tool execution should be hidden from the UI.\n * Server-side tools can set this to hide internal operations from users.\n */\n hidden?: boolean;\n}\n\n// ============================================\n// Agent Loop Types\n// ============================================\n\n/**\n * Agentic loop configuration\n */\nexport interface AgentLoopConfig {\n /** Maximum iterations before stopping (default: 20) */\n maxIterations?: number;\n /** Enable debug logging */\n debug?: boolean;\n /** Whether to enable the agentic loop (default: true) */\n enabled?: boolean;\n}\n\n/**\n * Agent loop state (for tracking)\n */\nexport interface AgentLoopState {\n /** Current iteration number */\n iteration: number;\n /** Maximum iterations allowed */\n maxIterations: number;\n /** Whether the loop is currently running */\n running: boolean;\n /** Whether max iterations was reached */\n maxIterationsReached: boolean;\n /** Whether the loop was aborted */\n aborted: boolean;\n}\n\n// ============================================\n// ToolSet Type (Vercel AI SDK pattern)\n// ============================================\n\n/**\n * A set of tools, keyed by tool name\n *\n * @example\n * ```typescript\n * const myTools: ToolSet = {\n * capture_screenshot: screenshotTool,\n * get_weather: weatherTool,\n * };\n * ```\n */\nexport type ToolSet = Record<string, ToolDefinition>;\n\n// ============================================\n// Tool Helper Function (Vercel AI SDK pattern)\n// ============================================\n\n/**\n * Configuration for creating a tool\n */\nexport interface ToolConfig<TParams = Record<string, unknown>> {\n /** Tool description for LLM */\n description: string;\n /** Where the tool executes (default: 'client') */\n location?: ToolLocation;\n\n // Display Configuration\n /** Human-readable title for UI display */\n title?: string | ((args: TParams) => string);\n /** Title shown while executing */\n executingTitle?: string | ((args: TParams) => string);\n /** Title shown after completion */\n completedTitle?: string | ((args: TParams) => string);\n\n /** JSON Schema for input parameters */\n inputSchema?: ToolInputSchema;\n /** Handler function */\n handler?: (\n params: TParams,\n context?: ToolContext,\n ) => Promise<ToolResponse> | ToolResponse;\n /** Optional render function for UI */\n render?: (props: ToolRenderProps<TParams>) => unknown;\n /** Whether the tool is available */\n available?: boolean;\n /** Hide this tool from chat UI display */\n hidden?: boolean;\n /** Require user approval before execution */\n needsApproval?: boolean | ((params: TParams) => boolean | Promise<boolean>);\n /** Custom message shown in the approval UI */\n approvalMessage?: string | ((params: TParams) => string);\n /** AI response mode for this tool (default: 'full') */\n aiResponseMode?: AIResponseMode;\n /** Context/summary sent to AI instead of full result */\n aiContext?:\n | string\n | ((result: ToolResponse, args: Record<string, unknown>) => string);\n}\n\n/**\n * Create a tool definition (similar to Vercel AI SDK's tool())\n *\n * @example\n * ```typescript\n * const weatherTool = tool({\n * description: 'Get weather for a location',\n * inputSchema: {\n * type: 'object',\n * properties: {\n * location: { type: 'string', description: 'City name' },\n * },\n * required: ['location'],\n * },\n * handler: async ({ location }) => {\n * const weather = await fetchWeather(location);\n * return success(weather);\n * },\n * });\n * ```\n */\nexport function tool<TParams = Record<string, unknown>>(\n config: ToolConfig<TParams>,\n): Omit<ToolDefinition<TParams>, \"name\"> {\n return {\n description: config.description,\n location: config.location ?? \"client\",\n // Display configuration\n title: config.title,\n executingTitle: config.executingTitle,\n completedTitle: config.completedTitle,\n // Schema and handlers\n inputSchema: config.inputSchema ?? {\n type: \"object\",\n properties: {},\n required: [],\n },\n handler: config.handler,\n render: config.render,\n available: config.available,\n hidden: config.hidden,\n needsApproval: config.needsApproval,\n approvalMessage: config.approvalMessage,\n aiResponseMode: config.aiResponseMode,\n aiContext: config.aiContext,\n };\n}\n\n// ============================================\n// Helper Functions\n// ============================================\n\n/**\n * Convert ToolDefinition to OpenAI tool format\n */\nexport function toolToOpenAIFormat(tool: ToolDefinition): object {\n return {\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n },\n };\n}\n\n/**\n * Convert ToolDefinition to Anthropic tool format\n */\nexport function toolToAnthropicFormat(tool: ToolDefinition): object {\n return {\n name: tool.name,\n description: tool.description,\n input_schema: tool.inputSchema,\n };\n}\n\n/**\n * Create a tool result response\n */\nexport function createToolResult(\n toolCallId: string,\n response: ToolResponse,\n): UnifiedToolResult {\n return {\n toolCallId,\n content: JSON.stringify(response),\n success: response.success,\n error: response.error,\n };\n}\n\n/**\n * Create a successful tool response\n */\nexport function success<T = unknown>(\n data?: T,\n message?: string,\n): ToolResponse<T> {\n return {\n success: true,\n data,\n message,\n };\n}\n\n/**\n * Create a failed tool response\n */\nexport function failure(error: string): ToolResponse {\n return {\n success: false,\n error,\n };\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunk7MZLBGFQ_cjs = require('./chunk-7MZLBGFQ.cjs');
|
|
4
4
|
var chunkJGPDQDY4_cjs = require('./chunk-JGPDQDY4.cjs');
|
|
5
5
|
var react = require('react');
|
|
6
6
|
var jsxRuntime = require('react/jsx-runtime');
|
|
@@ -183,7 +183,8 @@ function processStreamChunk(chunk, state) {
|
|
|
183
183
|
newResults.set(chunk.id, {
|
|
184
184
|
id: chunk.id,
|
|
185
185
|
name: chunk.name,
|
|
186
|
-
status: "executing"
|
|
186
|
+
status: "executing",
|
|
187
|
+
hidden: chunk.hidden
|
|
187
188
|
});
|
|
188
189
|
return { ...state, toolResults: newResults };
|
|
189
190
|
}
|
|
@@ -1026,6 +1027,25 @@ ${this.dynamicContext}`.trim() : this.config.systemPrompt,
|
|
|
1026
1027
|
}
|
|
1027
1028
|
if (isStreamDone(chunk)) {
|
|
1028
1029
|
this.debug("streamDone", { chunk });
|
|
1030
|
+
if (chunk.type === "done" && chunk.messages?.length) {
|
|
1031
|
+
this.debug("processDoneMessages", {
|
|
1032
|
+
count: chunk.messages.length
|
|
1033
|
+
});
|
|
1034
|
+
for (const msg of chunk.messages) {
|
|
1035
|
+
if (msg.role === "assistant" && !msg.tool_calls?.length && msg.content) {
|
|
1036
|
+
continue;
|
|
1037
|
+
}
|
|
1038
|
+
const message = {
|
|
1039
|
+
id: generateMessageId(),
|
|
1040
|
+
role: msg.role,
|
|
1041
|
+
content: msg.content ?? "",
|
|
1042
|
+
toolCalls: msg.tool_calls,
|
|
1043
|
+
toolCallId: msg.tool_call_id,
|
|
1044
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
1045
|
+
};
|
|
1046
|
+
this.state.pushMessage(message);
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1029
1049
|
break;
|
|
1030
1050
|
}
|
|
1031
1051
|
}
|
|
@@ -1052,13 +1072,37 @@ ${this.dynamicContext}`.trim() : this.config.systemPrompt,
|
|
|
1052
1072
|
* Handle JSON (non-streaming) response
|
|
1053
1073
|
*/
|
|
1054
1074
|
handleJsonResponse(response) {
|
|
1075
|
+
const toolCallHiddenMap = /* @__PURE__ */ new Map();
|
|
1076
|
+
if (response.toolCalls) {
|
|
1077
|
+
for (const tc of response.toolCalls) {
|
|
1078
|
+
if (tc.hidden !== void 0) {
|
|
1079
|
+
toolCallHiddenMap.set(tc.id, tc.hidden);
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1055
1083
|
for (const msg of response.messages ?? []) {
|
|
1084
|
+
let metadata;
|
|
1085
|
+
if (msg.role === "assistant" && msg.tool_calls && toolCallHiddenMap.size > 0) {
|
|
1086
|
+
const toolCallsHidden = {};
|
|
1087
|
+
for (const tc of msg.tool_calls) {
|
|
1088
|
+
const hidden = toolCallHiddenMap.get(tc.id);
|
|
1089
|
+
if (hidden !== void 0) {
|
|
1090
|
+
toolCallsHidden[tc.id] = hidden;
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
if (Object.keys(toolCallsHidden).length > 0) {
|
|
1094
|
+
metadata = { toolCallsHidden };
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1056
1097
|
const message = {
|
|
1057
1098
|
id: generateMessageId(),
|
|
1058
1099
|
role: msg.role,
|
|
1059
1100
|
content: msg.content ?? "",
|
|
1060
1101
|
toolCalls: msg.tool_calls,
|
|
1061
|
-
|
|
1102
|
+
// CRITICAL: Preserve toolCallId for tool messages (fixes Anthropic API errors)
|
|
1103
|
+
toolCallId: msg.tool_call_id,
|
|
1104
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
1105
|
+
metadata
|
|
1062
1106
|
};
|
|
1063
1107
|
this.state.pushMessage(message);
|
|
1064
1108
|
}
|
|
@@ -1322,7 +1366,8 @@ var AbstractAgentLoop = class {
|
|
|
1322
1366
|
args: toolCall.args,
|
|
1323
1367
|
status: "pending",
|
|
1324
1368
|
approvalStatus: "none",
|
|
1325
|
-
startedAt: /* @__PURE__ */ new Date()
|
|
1369
|
+
startedAt: /* @__PURE__ */ new Date(),
|
|
1370
|
+
hidden: tool?.hidden
|
|
1326
1371
|
};
|
|
1327
1372
|
this.addToolExecution(execution);
|
|
1328
1373
|
this.callbacks.onToolStart?.(execution);
|
|
@@ -2729,17 +2774,17 @@ function useAITools(options = {}) {
|
|
|
2729
2774
|
const rememberedConsentRef = react.useRef(/* @__PURE__ */ new Set());
|
|
2730
2775
|
react.useEffect(() => {
|
|
2731
2776
|
if (!autoStart || !isEnabled) return;
|
|
2732
|
-
if (consoleCapture && !
|
|
2733
|
-
|
|
2777
|
+
if (consoleCapture && !chunk7MZLBGFQ_cjs.isConsoleCaptureActive()) {
|
|
2778
|
+
chunk7MZLBGFQ_cjs.startConsoleCapture(consoleOptions);
|
|
2734
2779
|
setActiveCaptures((prev) => ({ ...prev, console: true }));
|
|
2735
2780
|
}
|
|
2736
|
-
if (network && !
|
|
2737
|
-
|
|
2781
|
+
if (network && !chunk7MZLBGFQ_cjs.isNetworkCaptureActive()) {
|
|
2782
|
+
chunk7MZLBGFQ_cjs.startNetworkCapture(networkOptions);
|
|
2738
2783
|
setActiveCaptures((prev) => ({ ...prev, network: true }));
|
|
2739
2784
|
}
|
|
2740
2785
|
return () => {
|
|
2741
|
-
|
|
2742
|
-
|
|
2786
|
+
chunk7MZLBGFQ_cjs.stopConsoleCapture();
|
|
2787
|
+
chunk7MZLBGFQ_cjs.stopNetworkCapture();
|
|
2743
2788
|
};
|
|
2744
2789
|
}, [
|
|
2745
2790
|
autoStart,
|
|
@@ -2754,12 +2799,12 @@ function useAITools(options = {}) {
|
|
|
2754
2799
|
if (!screenshot) {
|
|
2755
2800
|
throw new Error("Screenshot capture is not enabled");
|
|
2756
2801
|
}
|
|
2757
|
-
if (!
|
|
2802
|
+
if (!chunk7MZLBGFQ_cjs.isScreenshotSupported()) {
|
|
2758
2803
|
throw new Error(
|
|
2759
2804
|
"Screenshot capture is not supported in this environment"
|
|
2760
2805
|
);
|
|
2761
2806
|
}
|
|
2762
|
-
return
|
|
2807
|
+
return chunk7MZLBGFQ_cjs.captureScreenshot({ ...screenshotOptions, ...opts });
|
|
2763
2808
|
},
|
|
2764
2809
|
[screenshot, screenshotOptions]
|
|
2765
2810
|
);
|
|
@@ -2768,7 +2813,7 @@ function useAITools(options = {}) {
|
|
|
2768
2813
|
if (!consoleCapture) {
|
|
2769
2814
|
return { logs: [], totalCaptured: 0 };
|
|
2770
2815
|
}
|
|
2771
|
-
return
|
|
2816
|
+
return chunk7MZLBGFQ_cjs.getConsoleLogs({ ...consoleOptions, ...opts });
|
|
2772
2817
|
},
|
|
2773
2818
|
[consoleCapture, consoleOptions]
|
|
2774
2819
|
);
|
|
@@ -2777,7 +2822,7 @@ function useAITools(options = {}) {
|
|
|
2777
2822
|
if (!network) {
|
|
2778
2823
|
return { requests: [], totalCaptured: 0 };
|
|
2779
2824
|
}
|
|
2780
|
-
return
|
|
2825
|
+
return chunk7MZLBGFQ_cjs.getNetworkRequests({ ...networkOptions, ...opts });
|
|
2781
2826
|
},
|
|
2782
2827
|
[network, networkOptions]
|
|
2783
2828
|
);
|
|
@@ -2870,23 +2915,23 @@ function useAITools(options = {}) {
|
|
|
2870
2915
|
]
|
|
2871
2916
|
);
|
|
2872
2917
|
const startCapturing = react.useCallback(() => {
|
|
2873
|
-
if (consoleCapture && !
|
|
2874
|
-
|
|
2918
|
+
if (consoleCapture && !chunk7MZLBGFQ_cjs.isConsoleCaptureActive()) {
|
|
2919
|
+
chunk7MZLBGFQ_cjs.startConsoleCapture(consoleOptions);
|
|
2875
2920
|
setActiveCaptures((prev) => ({ ...prev, console: true }));
|
|
2876
2921
|
}
|
|
2877
|
-
if (network && !
|
|
2878
|
-
|
|
2922
|
+
if (network && !chunk7MZLBGFQ_cjs.isNetworkCaptureActive()) {
|
|
2923
|
+
chunk7MZLBGFQ_cjs.startNetworkCapture(networkOptions);
|
|
2879
2924
|
setActiveCaptures((prev) => ({ ...prev, network: true }));
|
|
2880
2925
|
}
|
|
2881
2926
|
}, [consoleCapture, network, consoleOptions, networkOptions]);
|
|
2882
2927
|
const stopCapturing = react.useCallback(() => {
|
|
2883
|
-
|
|
2884
|
-
|
|
2928
|
+
chunk7MZLBGFQ_cjs.stopConsoleCapture();
|
|
2929
|
+
chunk7MZLBGFQ_cjs.stopNetworkCapture();
|
|
2885
2930
|
setActiveCaptures({ console: false, network: false });
|
|
2886
2931
|
}, []);
|
|
2887
2932
|
const clearCaptured = react.useCallback(() => {
|
|
2888
|
-
|
|
2889
|
-
|
|
2933
|
+
chunk7MZLBGFQ_cjs.clearConsoleLogs();
|
|
2934
|
+
chunk7MZLBGFQ_cjs.clearNetworkRequests();
|
|
2890
2935
|
}, []);
|
|
2891
2936
|
const formatForAI = react.useCallback((context) => {
|
|
2892
2937
|
const parts = [];
|
|
@@ -2896,16 +2941,16 @@ function useAITools(options = {}) {
|
|
|
2896
2941
|
);
|
|
2897
2942
|
}
|
|
2898
2943
|
if (context.consoleLogs && context.consoleLogs.logs.length > 0) {
|
|
2899
|
-
parts.push(
|
|
2944
|
+
parts.push(chunk7MZLBGFQ_cjs.formatLogsForAI(context.consoleLogs.logs));
|
|
2900
2945
|
}
|
|
2901
2946
|
if (context.networkRequests && context.networkRequests.requests.length > 0) {
|
|
2902
|
-
parts.push(
|
|
2947
|
+
parts.push(chunk7MZLBGFQ_cjs.formatRequestsForAI(context.networkRequests.requests));
|
|
2903
2948
|
}
|
|
2904
2949
|
return parts.length > 0 ? parts.join("\n\n---\n\n") : "No context captured.";
|
|
2905
2950
|
}, []);
|
|
2906
2951
|
const detectIntentFn = react.useCallback(
|
|
2907
2952
|
(message) => {
|
|
2908
|
-
const result =
|
|
2953
|
+
const result = chunk7MZLBGFQ_cjs.detectIntent(message);
|
|
2909
2954
|
result.suggestedTools = result.suggestedTools.filter((tool) => {
|
|
2910
2955
|
if (tool === "screenshot") return screenshot;
|
|
2911
2956
|
if (tool === "console") return consoleCapture;
|
|
@@ -3020,7 +3065,7 @@ function convertZodSchema(schema, _toolName) {
|
|
|
3020
3065
|
}
|
|
3021
3066
|
} catch {
|
|
3022
3067
|
}
|
|
3023
|
-
return
|
|
3068
|
+
return chunk7MZLBGFQ_cjs.zodObjectToInputSchema(schema);
|
|
3024
3069
|
}
|
|
3025
3070
|
function useToolWithSchema(config, dependencies = []) {
|
|
3026
3071
|
const { registerTool, unregisterTool } = useCopilot();
|
|
@@ -3142,7 +3187,8 @@ function useToolExecutor() {
|
|
|
3142
3187
|
args: toolCall.input,
|
|
3143
3188
|
status: "executing",
|
|
3144
3189
|
timestamp: Date.now(),
|
|
3145
|
-
approvalStatus: "none"
|
|
3190
|
+
approvalStatus: "none",
|
|
3191
|
+
hidden: tool.hidden
|
|
3146
3192
|
};
|
|
3147
3193
|
addToolExecution?.(execution);
|
|
3148
3194
|
try {
|
|
@@ -3328,7 +3374,7 @@ function useAgent(options) {
|
|
|
3328
3374
|
if (!response.ok) {
|
|
3329
3375
|
throw new Error(`Agent error: ${response.status}`);
|
|
3330
3376
|
}
|
|
3331
|
-
for await (const event of
|
|
3377
|
+
for await (const event of chunk7MZLBGFQ_cjs.streamSSE(response)) {
|
|
3332
3378
|
handleAgentEvent(event);
|
|
3333
3379
|
}
|
|
3334
3380
|
} catch (err) {
|
|
@@ -3822,7 +3868,7 @@ function createReactThreadManagerState(initialThreads) {
|
|
|
3822
3868
|
}
|
|
3823
3869
|
|
|
3824
3870
|
// src/react/internal/ReactThreadManager.ts
|
|
3825
|
-
var _ReactThreadManager = class _ReactThreadManager extends
|
|
3871
|
+
var _ReactThreadManager = class _ReactThreadManager extends chunk7MZLBGFQ_cjs.ThreadManager {
|
|
3826
3872
|
constructor(config = {}, callbacks = {}) {
|
|
3827
3873
|
const reactState = new ReactThreadManagerState();
|
|
3828
3874
|
super({ ...config, state: reactState }, callbacks);
|
|
@@ -4489,5 +4535,5 @@ exports.useToolExecutor = useToolExecutor;
|
|
|
4489
4535
|
exports.useToolWithSchema = useToolWithSchema;
|
|
4490
4536
|
exports.useTools = useTools;
|
|
4491
4537
|
exports.useToolsWithSchema = useToolsWithSchema;
|
|
4492
|
-
//# sourceMappingURL=chunk-
|
|
4493
|
-
//# sourceMappingURL=chunk-
|
|
4538
|
+
//# sourceMappingURL=chunk-BNBEKK3U.cjs.map
|
|
4539
|
+
//# sourceMappingURL=chunk-BNBEKK3U.cjs.map
|