@yourgpt/copilot-sdk 2.1.0 → 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-MUZ2RYS2.cjs → chunk-BNBEKK3U.cjs} +226 -33
- 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-3SP6V22Y.js → chunk-VXT2O6R6.js} +202 -9
- 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 +130 -15
- package/dist/react/index.d.ts +130 -15
- 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-3SP6V22Y.js.map +0 -1
- package/dist/chunk-MUZ2RYS2.cjs.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
|
}
|
|
@@ -337,6 +338,33 @@ function createEmptyAssistantMessage(id) {
|
|
|
337
338
|
};
|
|
338
339
|
}
|
|
339
340
|
|
|
341
|
+
// src/core/utils/resolvable.ts
|
|
342
|
+
function isGetter(value) {
|
|
343
|
+
return typeof value === "function";
|
|
344
|
+
}
|
|
345
|
+
async function resolveValue(value) {
|
|
346
|
+
if (!isGetter(value)) {
|
|
347
|
+
return value;
|
|
348
|
+
}
|
|
349
|
+
try {
|
|
350
|
+
return await value();
|
|
351
|
+
} catch (error) {
|
|
352
|
+
console.error("[Copilot SDK] Error resolving dynamic config value:", error);
|
|
353
|
+
throw error;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
async function resolveValues(values) {
|
|
357
|
+
const entries = Object.entries(values);
|
|
358
|
+
const hasGetters = entries.some(([, v]) => isGetter(v));
|
|
359
|
+
if (!hasGetters) {
|
|
360
|
+
return values;
|
|
361
|
+
}
|
|
362
|
+
const resolved = await Promise.all(
|
|
363
|
+
entries.map(async ([key, val]) => [key, await resolveValue(val)])
|
|
364
|
+
);
|
|
365
|
+
return Object.fromEntries(resolved);
|
|
366
|
+
}
|
|
367
|
+
|
|
340
368
|
// src/chat/adapters/HttpTransport.ts
|
|
341
369
|
var HttpTransport = class {
|
|
342
370
|
constructor(config) {
|
|
@@ -350,16 +378,28 @@ var HttpTransport = class {
|
|
|
350
378
|
}
|
|
351
379
|
/**
|
|
352
380
|
* Send a chat request
|
|
381
|
+
* Resolves dynamic config values (url, headers, body) fresh at request time
|
|
353
382
|
*/
|
|
354
383
|
async send(request) {
|
|
355
384
|
this.abortController = new AbortController();
|
|
356
385
|
this.streaming = true;
|
|
357
386
|
try {
|
|
358
|
-
|
|
387
|
+
console.log(
|
|
388
|
+
"[HttpTransport] Config headers type:",
|
|
389
|
+
typeof this.config.headers
|
|
390
|
+
);
|
|
391
|
+
console.log("[HttpTransport] Config headers:", this.config.headers);
|
|
392
|
+
const resolved = await resolveValues({
|
|
393
|
+
url: this.config.url,
|
|
394
|
+
headers: this.config.headers ?? {},
|
|
395
|
+
configBody: this.config.body ?? {}
|
|
396
|
+
});
|
|
397
|
+
console.log("[HttpTransport] Resolved headers:", resolved.headers);
|
|
398
|
+
const response = await fetch(resolved.url, {
|
|
359
399
|
method: "POST",
|
|
360
400
|
headers: {
|
|
361
401
|
"Content-Type": "application/json",
|
|
362
|
-
...
|
|
402
|
+
...resolved.headers
|
|
363
403
|
},
|
|
364
404
|
body: JSON.stringify({
|
|
365
405
|
messages: request.messages,
|
|
@@ -369,6 +409,7 @@ var HttpTransport = class {
|
|
|
369
409
|
tools: request.tools,
|
|
370
410
|
actions: request.actions,
|
|
371
411
|
streaming: this.config.streaming,
|
|
412
|
+
...resolved.configBody,
|
|
372
413
|
...request.body
|
|
373
414
|
}),
|
|
374
415
|
signal: this.abortController.signal
|
|
@@ -410,6 +451,36 @@ var HttpTransport = class {
|
|
|
410
451
|
isStreaming() {
|
|
411
452
|
return this.streaming;
|
|
412
453
|
}
|
|
454
|
+
/**
|
|
455
|
+
* Update headers configuration
|
|
456
|
+
* Can be static headers or a getter function for dynamic resolution
|
|
457
|
+
*
|
|
458
|
+
* @example
|
|
459
|
+
* ```typescript
|
|
460
|
+
* // Static
|
|
461
|
+
* transport.setHeaders({ "x-api-key": "new-key" });
|
|
462
|
+
*
|
|
463
|
+
* // Dynamic (resolved fresh on each request)
|
|
464
|
+
* transport.setHeaders(() => ({ Authorization: `Bearer ${getToken()}` }));
|
|
465
|
+
* ```
|
|
466
|
+
*/
|
|
467
|
+
setHeaders(headers) {
|
|
468
|
+
this.config.headers = headers;
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* Update URL configuration
|
|
472
|
+
* Can be static URL or a getter function for dynamic resolution
|
|
473
|
+
*/
|
|
474
|
+
setUrl(url) {
|
|
475
|
+
this.config.url = url;
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Update body configuration
|
|
479
|
+
* Additional properties merged into every request body
|
|
480
|
+
*/
|
|
481
|
+
setBody(body) {
|
|
482
|
+
this.config.body = body;
|
|
483
|
+
}
|
|
413
484
|
/**
|
|
414
485
|
* Create an async iterable from a ReadableStream
|
|
415
486
|
*/
|
|
@@ -533,6 +604,7 @@ var AbstractChat = class {
|
|
|
533
604
|
systemPrompt: init.systemPrompt,
|
|
534
605
|
streaming: init.streaming ?? true,
|
|
535
606
|
headers: init.headers,
|
|
607
|
+
body: init.body,
|
|
536
608
|
threadId: init.threadId,
|
|
537
609
|
debug: init.debug
|
|
538
610
|
};
|
|
@@ -540,6 +612,7 @@ var AbstractChat = class {
|
|
|
540
612
|
this.transport = init.transport ?? new HttpTransport({
|
|
541
613
|
url: init.runtimeUrl,
|
|
542
614
|
headers: init.headers,
|
|
615
|
+
body: init.body,
|
|
543
616
|
streaming: init.streaming ?? true
|
|
544
617
|
});
|
|
545
618
|
this.callbacks = init.callbacks ?? {};
|
|
@@ -805,6 +878,39 @@ var AbstractChat = class {
|
|
|
805
878
|
this.config.systemPrompt = prompt;
|
|
806
879
|
this.debug("System prompt updated", { length: prompt.length });
|
|
807
880
|
}
|
|
881
|
+
/**
|
|
882
|
+
* Set headers configuration
|
|
883
|
+
* Can be static headers or a getter function for dynamic resolution
|
|
884
|
+
*/
|
|
885
|
+
setHeaders(headers) {
|
|
886
|
+
this.config.headers = headers;
|
|
887
|
+
if (this.transport.setHeaders && headers !== void 0) {
|
|
888
|
+
this.transport.setHeaders(headers);
|
|
889
|
+
}
|
|
890
|
+
this.debug("Headers config updated");
|
|
891
|
+
}
|
|
892
|
+
/**
|
|
893
|
+
* Set URL configuration
|
|
894
|
+
* Can be static URL or a getter function for dynamic resolution
|
|
895
|
+
*/
|
|
896
|
+
setUrl(url) {
|
|
897
|
+
this.config.runtimeUrl = url;
|
|
898
|
+
if (this.transport.setUrl) {
|
|
899
|
+
this.transport.setUrl(url);
|
|
900
|
+
}
|
|
901
|
+
this.debug("URL config updated");
|
|
902
|
+
}
|
|
903
|
+
/**
|
|
904
|
+
* Set body configuration
|
|
905
|
+
* Additional properties merged into every request body
|
|
906
|
+
*/
|
|
907
|
+
setBody(body) {
|
|
908
|
+
this.config.body = body;
|
|
909
|
+
if (this.transport.setBody && body !== void 0) {
|
|
910
|
+
this.transport.setBody(body);
|
|
911
|
+
}
|
|
912
|
+
this.debug("Body config updated");
|
|
913
|
+
}
|
|
808
914
|
/**
|
|
809
915
|
* Build the request payload
|
|
810
916
|
*/
|
|
@@ -921,6 +1027,25 @@ ${this.dynamicContext}`.trim() : this.config.systemPrompt,
|
|
|
921
1027
|
}
|
|
922
1028
|
if (isStreamDone(chunk)) {
|
|
923
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
|
+
}
|
|
924
1049
|
break;
|
|
925
1050
|
}
|
|
926
1051
|
}
|
|
@@ -947,13 +1072,37 @@ ${this.dynamicContext}`.trim() : this.config.systemPrompt,
|
|
|
947
1072
|
* Handle JSON (non-streaming) response
|
|
948
1073
|
*/
|
|
949
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
|
+
}
|
|
950
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
|
+
}
|
|
951
1097
|
const message = {
|
|
952
1098
|
id: generateMessageId(),
|
|
953
1099
|
role: msg.role,
|
|
954
1100
|
content: msg.content ?? "",
|
|
955
1101
|
toolCalls: msg.tool_calls,
|
|
956
|
-
|
|
1102
|
+
// CRITICAL: Preserve toolCallId for tool messages (fixes Anthropic API errors)
|
|
1103
|
+
toolCallId: msg.tool_call_id,
|
|
1104
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
1105
|
+
metadata
|
|
957
1106
|
};
|
|
958
1107
|
this.state.pushMessage(message);
|
|
959
1108
|
}
|
|
@@ -1217,7 +1366,8 @@ var AbstractAgentLoop = class {
|
|
|
1217
1366
|
args: toolCall.args,
|
|
1218
1367
|
status: "pending",
|
|
1219
1368
|
approvalStatus: "none",
|
|
1220
|
-
startedAt: /* @__PURE__ */ new Date()
|
|
1369
|
+
startedAt: /* @__PURE__ */ new Date(),
|
|
1370
|
+
hidden: tool?.hidden
|
|
1221
1371
|
};
|
|
1222
1372
|
this.addToolExecution(execution);
|
|
1223
1373
|
this.callbacks.onToolStart?.(execution);
|
|
@@ -1480,6 +1630,7 @@ var ChatWithTools = class {
|
|
|
1480
1630
|
systemPrompt: config.systemPrompt,
|
|
1481
1631
|
streaming: config.streaming,
|
|
1482
1632
|
headers: config.headers,
|
|
1633
|
+
body: config.body,
|
|
1483
1634
|
threadId: config.threadId,
|
|
1484
1635
|
debug: config.debug,
|
|
1485
1636
|
initialMessages: config.initialMessages,
|
|
@@ -1663,6 +1814,27 @@ var ChatWithTools = class {
|
|
|
1663
1814
|
setSystemPrompt(prompt) {
|
|
1664
1815
|
this.chat.setSystemPrompt(prompt);
|
|
1665
1816
|
}
|
|
1817
|
+
/**
|
|
1818
|
+
* Set headers configuration
|
|
1819
|
+
* Can be static headers or a getter function for dynamic resolution
|
|
1820
|
+
*/
|
|
1821
|
+
setHeaders(headers) {
|
|
1822
|
+
this.chat.setHeaders(headers);
|
|
1823
|
+
}
|
|
1824
|
+
/**
|
|
1825
|
+
* Set URL configuration
|
|
1826
|
+
* Can be static URL or a getter function for dynamic resolution
|
|
1827
|
+
*/
|
|
1828
|
+
setUrl(url) {
|
|
1829
|
+
this.chat.setUrl(url);
|
|
1830
|
+
}
|
|
1831
|
+
/**
|
|
1832
|
+
* Set body configuration
|
|
1833
|
+
* Additional properties merged into every request body
|
|
1834
|
+
*/
|
|
1835
|
+
setBody(body) {
|
|
1836
|
+
this.chat.setBody(body);
|
|
1837
|
+
}
|
|
1666
1838
|
// ============================================
|
|
1667
1839
|
// Tool Registration
|
|
1668
1840
|
// ============================================
|
|
@@ -2221,6 +2393,7 @@ function CopilotProvider({
|
|
|
2221
2393
|
onError,
|
|
2222
2394
|
streaming,
|
|
2223
2395
|
headers,
|
|
2396
|
+
body,
|
|
2224
2397
|
debug = false,
|
|
2225
2398
|
maxIterations,
|
|
2226
2399
|
maxIterationsMessage,
|
|
@@ -2265,6 +2438,7 @@ function CopilotProvider({
|
|
|
2265
2438
|
initialMessages: uiInitialMessages,
|
|
2266
2439
|
streaming,
|
|
2267
2440
|
headers,
|
|
2441
|
+
body,
|
|
2268
2442
|
debug,
|
|
2269
2443
|
maxIterations,
|
|
2270
2444
|
maxIterationsMessage
|
|
@@ -2289,6 +2463,24 @@ function CopilotProvider({
|
|
|
2289
2463
|
debugLog("System prompt updated from prop");
|
|
2290
2464
|
}
|
|
2291
2465
|
}, [systemPrompt, debugLog]);
|
|
2466
|
+
react.useEffect(() => {
|
|
2467
|
+
if (chatRef.current && headers !== void 0) {
|
|
2468
|
+
chatRef.current.setHeaders(headers);
|
|
2469
|
+
debugLog("Headers config updated from prop");
|
|
2470
|
+
}
|
|
2471
|
+
}, [headers, debugLog]);
|
|
2472
|
+
react.useEffect(() => {
|
|
2473
|
+
if (chatRef.current && body !== void 0) {
|
|
2474
|
+
chatRef.current.setBody(body);
|
|
2475
|
+
debugLog("Body config updated from prop");
|
|
2476
|
+
}
|
|
2477
|
+
}, [body, debugLog]);
|
|
2478
|
+
react.useEffect(() => {
|
|
2479
|
+
if (chatRef.current && runtimeUrl !== void 0) {
|
|
2480
|
+
chatRef.current.setUrl(runtimeUrl);
|
|
2481
|
+
debugLog("URL config updated from prop");
|
|
2482
|
+
}
|
|
2483
|
+
}, [runtimeUrl, debugLog]);
|
|
2292
2484
|
const messages = react.useSyncExternalStore(
|
|
2293
2485
|
chatRef.current.subscribe,
|
|
2294
2486
|
() => chatRef.current.messages,
|
|
@@ -2582,17 +2774,17 @@ function useAITools(options = {}) {
|
|
|
2582
2774
|
const rememberedConsentRef = react.useRef(/* @__PURE__ */ new Set());
|
|
2583
2775
|
react.useEffect(() => {
|
|
2584
2776
|
if (!autoStart || !isEnabled) return;
|
|
2585
|
-
if (consoleCapture && !
|
|
2586
|
-
|
|
2777
|
+
if (consoleCapture && !chunk7MZLBGFQ_cjs.isConsoleCaptureActive()) {
|
|
2778
|
+
chunk7MZLBGFQ_cjs.startConsoleCapture(consoleOptions);
|
|
2587
2779
|
setActiveCaptures((prev) => ({ ...prev, console: true }));
|
|
2588
2780
|
}
|
|
2589
|
-
if (network && !
|
|
2590
|
-
|
|
2781
|
+
if (network && !chunk7MZLBGFQ_cjs.isNetworkCaptureActive()) {
|
|
2782
|
+
chunk7MZLBGFQ_cjs.startNetworkCapture(networkOptions);
|
|
2591
2783
|
setActiveCaptures((prev) => ({ ...prev, network: true }));
|
|
2592
2784
|
}
|
|
2593
2785
|
return () => {
|
|
2594
|
-
|
|
2595
|
-
|
|
2786
|
+
chunk7MZLBGFQ_cjs.stopConsoleCapture();
|
|
2787
|
+
chunk7MZLBGFQ_cjs.stopNetworkCapture();
|
|
2596
2788
|
};
|
|
2597
2789
|
}, [
|
|
2598
2790
|
autoStart,
|
|
@@ -2607,12 +2799,12 @@ function useAITools(options = {}) {
|
|
|
2607
2799
|
if (!screenshot) {
|
|
2608
2800
|
throw new Error("Screenshot capture is not enabled");
|
|
2609
2801
|
}
|
|
2610
|
-
if (!
|
|
2802
|
+
if (!chunk7MZLBGFQ_cjs.isScreenshotSupported()) {
|
|
2611
2803
|
throw new Error(
|
|
2612
2804
|
"Screenshot capture is not supported in this environment"
|
|
2613
2805
|
);
|
|
2614
2806
|
}
|
|
2615
|
-
return
|
|
2807
|
+
return chunk7MZLBGFQ_cjs.captureScreenshot({ ...screenshotOptions, ...opts });
|
|
2616
2808
|
},
|
|
2617
2809
|
[screenshot, screenshotOptions]
|
|
2618
2810
|
);
|
|
@@ -2621,7 +2813,7 @@ function useAITools(options = {}) {
|
|
|
2621
2813
|
if (!consoleCapture) {
|
|
2622
2814
|
return { logs: [], totalCaptured: 0 };
|
|
2623
2815
|
}
|
|
2624
|
-
return
|
|
2816
|
+
return chunk7MZLBGFQ_cjs.getConsoleLogs({ ...consoleOptions, ...opts });
|
|
2625
2817
|
},
|
|
2626
2818
|
[consoleCapture, consoleOptions]
|
|
2627
2819
|
);
|
|
@@ -2630,7 +2822,7 @@ function useAITools(options = {}) {
|
|
|
2630
2822
|
if (!network) {
|
|
2631
2823
|
return { requests: [], totalCaptured: 0 };
|
|
2632
2824
|
}
|
|
2633
|
-
return
|
|
2825
|
+
return chunk7MZLBGFQ_cjs.getNetworkRequests({ ...networkOptions, ...opts });
|
|
2634
2826
|
},
|
|
2635
2827
|
[network, networkOptions]
|
|
2636
2828
|
);
|
|
@@ -2723,23 +2915,23 @@ function useAITools(options = {}) {
|
|
|
2723
2915
|
]
|
|
2724
2916
|
);
|
|
2725
2917
|
const startCapturing = react.useCallback(() => {
|
|
2726
|
-
if (consoleCapture && !
|
|
2727
|
-
|
|
2918
|
+
if (consoleCapture && !chunk7MZLBGFQ_cjs.isConsoleCaptureActive()) {
|
|
2919
|
+
chunk7MZLBGFQ_cjs.startConsoleCapture(consoleOptions);
|
|
2728
2920
|
setActiveCaptures((prev) => ({ ...prev, console: true }));
|
|
2729
2921
|
}
|
|
2730
|
-
if (network && !
|
|
2731
|
-
|
|
2922
|
+
if (network && !chunk7MZLBGFQ_cjs.isNetworkCaptureActive()) {
|
|
2923
|
+
chunk7MZLBGFQ_cjs.startNetworkCapture(networkOptions);
|
|
2732
2924
|
setActiveCaptures((prev) => ({ ...prev, network: true }));
|
|
2733
2925
|
}
|
|
2734
2926
|
}, [consoleCapture, network, consoleOptions, networkOptions]);
|
|
2735
2927
|
const stopCapturing = react.useCallback(() => {
|
|
2736
|
-
|
|
2737
|
-
|
|
2928
|
+
chunk7MZLBGFQ_cjs.stopConsoleCapture();
|
|
2929
|
+
chunk7MZLBGFQ_cjs.stopNetworkCapture();
|
|
2738
2930
|
setActiveCaptures({ console: false, network: false });
|
|
2739
2931
|
}, []);
|
|
2740
2932
|
const clearCaptured = react.useCallback(() => {
|
|
2741
|
-
|
|
2742
|
-
|
|
2933
|
+
chunk7MZLBGFQ_cjs.clearConsoleLogs();
|
|
2934
|
+
chunk7MZLBGFQ_cjs.clearNetworkRequests();
|
|
2743
2935
|
}, []);
|
|
2744
2936
|
const formatForAI = react.useCallback((context) => {
|
|
2745
2937
|
const parts = [];
|
|
@@ -2749,16 +2941,16 @@ function useAITools(options = {}) {
|
|
|
2749
2941
|
);
|
|
2750
2942
|
}
|
|
2751
2943
|
if (context.consoleLogs && context.consoleLogs.logs.length > 0) {
|
|
2752
|
-
parts.push(
|
|
2944
|
+
parts.push(chunk7MZLBGFQ_cjs.formatLogsForAI(context.consoleLogs.logs));
|
|
2753
2945
|
}
|
|
2754
2946
|
if (context.networkRequests && context.networkRequests.requests.length > 0) {
|
|
2755
|
-
parts.push(
|
|
2947
|
+
parts.push(chunk7MZLBGFQ_cjs.formatRequestsForAI(context.networkRequests.requests));
|
|
2756
2948
|
}
|
|
2757
2949
|
return parts.length > 0 ? parts.join("\n\n---\n\n") : "No context captured.";
|
|
2758
2950
|
}, []);
|
|
2759
2951
|
const detectIntentFn = react.useCallback(
|
|
2760
2952
|
(message) => {
|
|
2761
|
-
const result =
|
|
2953
|
+
const result = chunk7MZLBGFQ_cjs.detectIntent(message);
|
|
2762
2954
|
result.suggestedTools = result.suggestedTools.filter((tool) => {
|
|
2763
2955
|
if (tool === "screenshot") return screenshot;
|
|
2764
2956
|
if (tool === "console") return consoleCapture;
|
|
@@ -2873,7 +3065,7 @@ function convertZodSchema(schema, _toolName) {
|
|
|
2873
3065
|
}
|
|
2874
3066
|
} catch {
|
|
2875
3067
|
}
|
|
2876
|
-
return
|
|
3068
|
+
return chunk7MZLBGFQ_cjs.zodObjectToInputSchema(schema);
|
|
2877
3069
|
}
|
|
2878
3070
|
function useToolWithSchema(config, dependencies = []) {
|
|
2879
3071
|
const { registerTool, unregisterTool } = useCopilot();
|
|
@@ -2995,7 +3187,8 @@ function useToolExecutor() {
|
|
|
2995
3187
|
args: toolCall.input,
|
|
2996
3188
|
status: "executing",
|
|
2997
3189
|
timestamp: Date.now(),
|
|
2998
|
-
approvalStatus: "none"
|
|
3190
|
+
approvalStatus: "none",
|
|
3191
|
+
hidden: tool.hidden
|
|
2999
3192
|
};
|
|
3000
3193
|
addToolExecution?.(execution);
|
|
3001
3194
|
try {
|
|
@@ -3181,7 +3374,7 @@ function useAgent(options) {
|
|
|
3181
3374
|
if (!response.ok) {
|
|
3182
3375
|
throw new Error(`Agent error: ${response.status}`);
|
|
3183
3376
|
}
|
|
3184
|
-
for await (const event of
|
|
3377
|
+
for await (const event of chunk7MZLBGFQ_cjs.streamSSE(response)) {
|
|
3185
3378
|
handleAgentEvent(event);
|
|
3186
3379
|
}
|
|
3187
3380
|
} catch (err) {
|
|
@@ -3675,7 +3868,7 @@ function createReactThreadManagerState(initialThreads) {
|
|
|
3675
3868
|
}
|
|
3676
3869
|
|
|
3677
3870
|
// src/react/internal/ReactThreadManager.ts
|
|
3678
|
-
var _ReactThreadManager = class _ReactThreadManager extends
|
|
3871
|
+
var _ReactThreadManager = class _ReactThreadManager extends chunk7MZLBGFQ_cjs.ThreadManager {
|
|
3679
3872
|
constructor(config = {}, callbacks = {}) {
|
|
3680
3873
|
const reactState = new ReactThreadManagerState();
|
|
3681
3874
|
super({ ...config, state: reactState }, callbacks);
|
|
@@ -4342,5 +4535,5 @@ exports.useToolExecutor = useToolExecutor;
|
|
|
4342
4535
|
exports.useToolWithSchema = useToolWithSchema;
|
|
4343
4536
|
exports.useTools = useTools;
|
|
4344
4537
|
exports.useToolsWithSchema = useToolsWithSchema;
|
|
4345
|
-
//# sourceMappingURL=chunk-
|
|
4346
|
-
//# sourceMappingURL=chunk-
|
|
4538
|
+
//# sourceMappingURL=chunk-BNBEKK3U.cjs.map
|
|
4539
|
+
//# sourceMappingURL=chunk-BNBEKK3U.cjs.map
|