@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.
Files changed (75) hide show
  1. package/dist/{chunk-33JSFVGH.cjs → chunk-7MZLBGFQ.cjs} +23 -23
  2. package/dist/{chunk-33JSFVGH.cjs.map → chunk-7MZLBGFQ.cjs.map} +1 -1
  3. package/dist/{chunk-BRUDSHCV.js → chunk-BMYNG3WM.js} +2 -2
  4. package/dist/{chunk-BRUDSHCV.js.map → chunk-BMYNG3WM.js.map} +1 -1
  5. package/dist/{chunk-MUZ2RYS2.cjs → chunk-BNBEKK3U.cjs} +226 -33
  6. package/dist/chunk-BNBEKK3U.cjs.map +1 -0
  7. package/dist/{chunk-HNRFRNMY.cjs → chunk-CSEZZ5DX.cjs} +2 -2
  8. package/dist/{chunk-HNRFRNMY.cjs.map → chunk-CSEZZ5DX.cjs.map} +1 -1
  9. package/dist/{chunk-O33I4HBL.cjs → chunk-GSTTJ46F.cjs} +5 -5
  10. package/dist/{chunk-O33I4HBL.cjs.map → chunk-GSTTJ46F.cjs.map} +1 -1
  11. package/dist/{chunk-7YZVSG62.js → chunk-VUHP6TAN.js} +3 -3
  12. package/dist/{chunk-7YZVSG62.js.map → chunk-VUHP6TAN.js.map} +1 -1
  13. package/dist/{chunk-3SP6V22Y.js → chunk-VXT2O6R6.js} +202 -9
  14. package/dist/chunk-VXT2O6R6.js.map +1 -0
  15. package/dist/{chunk-7PJ4GAJR.js → chunk-XAC7NTIO.js} +4 -4
  16. package/dist/{chunk-7PJ4GAJR.js.map → chunk-XAC7NTIO.js.map} +1 -1
  17. package/dist/core/index.cjs +80 -80
  18. package/dist/core/index.d.cts +3 -3
  19. package/dist/core/index.d.ts +3 -3
  20. package/dist/core/index.js +3 -3
  21. package/dist/{index-25qIYJ21.d.ts → index-Du3Akr_E.d.ts} +1 -1
  22. package/dist/{index-C261xY-B.d.cts → index-jwRcC2QD.d.cts} +1 -1
  23. package/dist/mcp/index.d.cts +3 -3
  24. package/dist/mcp/index.d.ts +3 -3
  25. package/dist/react/index.cjs +49 -49
  26. package/dist/react/index.d.cts +130 -15
  27. package/dist/react/index.d.ts +130 -15
  28. package/dist/react/index.js +4 -4
  29. package/dist/tools/anthropic/index.d.cts +1 -1
  30. package/dist/tools/anthropic/index.d.ts +1 -1
  31. package/dist/tools/brave/index.cjs +2 -2
  32. package/dist/tools/brave/index.d.cts +1 -1
  33. package/dist/tools/brave/index.d.ts +1 -1
  34. package/dist/tools/brave/index.js +1 -1
  35. package/dist/tools/exa/index.cjs +2 -2
  36. package/dist/tools/exa/index.d.cts +1 -1
  37. package/dist/tools/exa/index.d.ts +1 -1
  38. package/dist/tools/exa/index.js +1 -1
  39. package/dist/tools/google/index.cjs +2 -2
  40. package/dist/tools/google/index.d.cts +1 -1
  41. package/dist/tools/google/index.d.ts +1 -1
  42. package/dist/tools/google/index.js +1 -1
  43. package/dist/tools/openai/index.cjs +2 -2
  44. package/dist/tools/openai/index.d.cts +1 -1
  45. package/dist/tools/openai/index.d.ts +1 -1
  46. package/dist/tools/openai/index.js +1 -1
  47. package/dist/tools/searxng/index.cjs +2 -2
  48. package/dist/tools/searxng/index.d.cts +1 -1
  49. package/dist/tools/searxng/index.d.ts +1 -1
  50. package/dist/tools/searxng/index.js +1 -1
  51. package/dist/tools/serper/index.cjs +2 -2
  52. package/dist/tools/serper/index.d.cts +1 -1
  53. package/dist/tools/serper/index.d.ts +1 -1
  54. package/dist/tools/serper/index.js +1 -1
  55. package/dist/tools/tavily/index.cjs +2 -2
  56. package/dist/tools/tavily/index.d.cts +1 -1
  57. package/dist/tools/tavily/index.d.ts +1 -1
  58. package/dist/tools/tavily/index.js +1 -1
  59. package/dist/tools/web-search/index.cjs +3 -3
  60. package/dist/tools/web-search/index.d.cts +2 -2
  61. package/dist/tools/web-search/index.d.ts +2 -2
  62. package/dist/tools/web-search/index.js +2 -2
  63. package/dist/{tools-Clyufshc.d.cts → tools-BHQRB_YT.d.cts} +5 -0
  64. package/dist/{tools-Clyufshc.d.ts → tools-BHQRB_YT.d.ts} +5 -0
  65. package/dist/{types-DM6M_pv_.d.cts → types-8_Hp2rmm.d.cts} +1 -1
  66. package/dist/{types-wudOhedT.d.ts → types-OYi-iUVY.d.ts} +1 -1
  67. package/dist/ui/index.cjs +39 -18
  68. package/dist/ui/index.cjs.map +1 -1
  69. package/dist/ui/index.d.cts +6 -1
  70. package/dist/ui/index.d.ts +6 -1
  71. package/dist/ui/index.js +35 -14
  72. package/dist/ui/index.js.map +1 -1
  73. package/package.json +1 -1
  74. package/dist/chunk-3SP6V22Y.js.map +0 -1
  75. package/dist/chunk-MUZ2RYS2.cjs.map +0 -1
@@ -70,5 +70,5 @@ exports.success = success;
70
70
  exports.tool = tool;
71
71
  exports.toolToAnthropicFormat = toolToAnthropicFormat;
72
72
  exports.toolToOpenAIFormat = toolToOpenAIFormat;
73
- //# sourceMappingURL=chunk-HNRFRNMY.cjs.map
74
- //# sourceMappingURL=chunk-HNRFRNMY.cjs.map
73
+ //# sourceMappingURL=chunk-CSEZZ5DX.cjs.map
74
+ //# sourceMappingURL=chunk-CSEZZ5DX.cjs.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-HNRFRNMY.cjs","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-CSEZZ5DX.cjs","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,10 +1,10 @@
1
1
  'use strict';
2
2
 
3
- var chunkHNRFRNMY_cjs = require('./chunk-HNRFRNMY.cjs');
3
+ var chunkCSEZZ5DX_cjs = require('./chunk-CSEZZ5DX.cjs');
4
4
  var chunkASV6JLYG_cjs = require('./chunk-ASV6JLYG.cjs');
5
5
 
6
6
  // src/core/tools/builtin/webSearch.ts
7
- var webSearchTool = chunkHNRFRNMY_cjs.tool({
7
+ var webSearchTool = chunkCSEZZ5DX_cjs.tool({
8
8
  description: `Search the web for current information. Use this when the user asks about:
9
9
  - Recent events, news, or current affairs
10
10
  - Real-time data (prices, weather, stocks, sports scores)
@@ -70,7 +70,7 @@ function createWebSearchTool(config) {
70
70
  };
71
71
  } catch (error) {
72
72
  const errorMessage = error instanceof Error ? error.message : "Web search failed";
73
- return chunkHNRFRNMY_cjs.failure(errorMessage);
73
+ return chunkCSEZZ5DX_cjs.failure(errorMessage);
74
74
  }
75
75
  }
76
76
  };
@@ -78,5 +78,5 @@ function createWebSearchTool(config) {
78
78
 
79
79
  exports.createWebSearchTool = createWebSearchTool;
80
80
  exports.webSearchTool = webSearchTool;
81
- //# sourceMappingURL=chunk-O33I4HBL.cjs.map
82
- //# sourceMappingURL=chunk-O33I4HBL.cjs.map
81
+ //# sourceMappingURL=chunk-GSTTJ46F.cjs.map
82
+ //# sourceMappingURL=chunk-GSTTJ46F.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/tools/builtin/webSearch.ts"],"names":["tool","formatSearchResultsForAI","executeWebSearch","summarizeSearchResults","failure"],"mappings":";;;;;;AAoDO,IAAM,gBAAgBA,sBAAA,CAAsB;AAAA,EACjD,WAAA,EAAa,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qDAAA,CAAA;AAAA,EAOb,QAAA,EAAU,QAAA;AAAA;AAAA,EAEV,KAAA,EAAO,CAAC,IAAA,KAAS,CAAA,eAAA,EAAkB,KAAK,KAAK,CAAA,CAAA,CAAA;AAAA,EAC7C,cAAA,EAAgB,CAAC,IAAA,KAAS,CAAA,uBAAA,EAA0B,KAAK,KAAK,CAAA,IAAA,CAAA;AAAA,EAC9D,cAAA,EAAgB,CAAC,IAAA,KAAS,CAAA,mBAAA,EAAsB,KAAK,KAAK,CAAA,CAAA,CAAA;AAAA,EAE1D,WAAA,EAAa;AAAA,IACX,IAAA,EAAM,QAAA;AAAA,IACN,UAAA,EAAY;AAAA,MACV,KAAA,EAAO;AAAA,QACL,IAAA,EAAM,QAAA;AAAA,QACN,WAAA,EAAa;AAAA,OACf;AAAA,MACA,UAAA,EAAY;AAAA,QACV,IAAA,EAAM,QAAA;AAAA,QACN,WAAA,EACE,2DAAA;AAAA,QACF,OAAA,EAAS,CAAA;AAAA,QACT,OAAA,EAAS;AAAA,OACX;AAAA,MACA,WAAA,EAAa;AAAA,QACX,IAAA,EAAM,QAAA;AAAA,QACN,IAAA,EAAM,CAAC,OAAA,EAAS,UAAU,CAAA;AAAA,QAC1B,WAAA,EACE;AAAA;AACJ,KACF;AAAA,IACA,QAAA,EAAU,CAAC,OAAO;AAAA,GACpB;AAAA,EAEA,aAAA,EAAe,KAAA;AAAA;AAAA;AAAA,EAGf,cAAA,EAAgB,MAAA;AAAA,EAChB,SAAA,EAAW,CAAC,MAAA,EAAQ,IAAA,KAAS;AAC3B,IAAA,IAAI,CAAC,MAAA,CAAO,OAAA,EAAS,OAAO,CAAA,eAAA,EAAkB,OAAO,KAAK,CAAA,CAAA;AAC1D,IAAA,MAAM,OAAO,MAAA,CAAO,IAAA;AACpB,IAAA,OAAOC,2CAAyB,IAAI,CAAA;AAAA,EACtC;AACF,CAAC;AAoEM,SAAS,oBACd,MAAA,EACiC;AACjC,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,YAAA;AAAA,IACN,GAAG,aAAA;AAAA,IACH,OAAA,EAAS,OAAO,MAAA,KAA4B;AAC1C,MAAA,IAAI;AACF,QAAA,MAAM,WAAW,MAAMC,kCAAA;AAAA,UACrB;AAAA,YACE,OAAO,MAAA,CAAO,KAAA;AAAA,YACd,UAAA,EAAY,MAAA,CAAO,UAAA,IAAc,MAAA,CAAO,UAAA,IAAc,CAAA;AAAA,YACtD,WAAA,EAAa,MAAA,CAAO,WAAA,IAAe,MAAA,CAAO,WAAA,IAAe;AAAA,WAC3D;AAAA,UACA;AAAA,SACF;AAGA,QAAA,MAAM,SAAA,GAAYD,2CAAyB,QAAQ,CAAA;AAEnD,QAAA,OAAO;AAAA,UACL,OAAA,EAAS,IAAA;AAAA,UACT,OAAA,EAASE,yCAAuB,QAAQ,CAAA;AAAA,UACxC,IAAA,EAAM,QAAA;AAAA,UACN,UAAA,EAAY;AAAA,SACd;AAAA,MACF,SAAS,KAAA,EAAO;AACd,QAAA,MAAM,YAAA,GACJ,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,mBAAA;AAC3C,QAAA,OAAOC,0BAAQ,YAAY,CAAA;AAAA,MAC7B;AAAA,IACF;AAAA,GACF;AACF","file":"chunk-O33I4HBL.cjs","sourcesContent":["/**\n * Built-in Web Search Tool\n *\n * A pre-configured tool for searching the web with multiple provider support.\n * Runs on the server to protect API keys.\n *\n * Supports tree-shaking - import providers directly for smaller bundles.\n *\n * @example\n * ```typescript\n * // Option 1: String provider (lazy loaded at runtime)\n * import { createWebSearchTool } from '@yourgpt/copilot-sdk';\n * const webSearch = createWebSearchTool({\n * provider: 'tavily',\n * apiKey: process.env.TAVILY_API_KEY,\n * });\n *\n * // Option 2: Direct provider import (best for tree-shaking)\n * import { createWebSearchTool, tavilyProvider } from '@yourgpt/copilot-sdk';\n * const webSearch = createWebSearchTool({\n * provider: tavilyProvider,\n * apiKey: process.env.TAVILY_API_KEY,\n * });\n *\n * // Add to your runtime\n * const runtime = createRuntime({\n * tools: [webSearch],\n * });\n * ```\n */\n\nimport { tool, success, failure } from \"../../types/tools\";\nimport type { ToolDefinition } from \"../../types/tools\";\nimport {\n executeWebSearch,\n formatSearchResultsForAI,\n summarizeSearchResults,\n type WebSearchConfigExtended,\n} from \"../webSearch\";\nimport type {\n WebSearchConfig,\n WebSearchParams,\n WebSearchResponse,\n WebSearchProviderInterface,\n} from \"../webSearch/types\";\n\n/**\n * Base web search tool definition\n *\n * This is the core tool definition. Use `createWebSearchTool()` to create\n * a configured instance with your provider settings.\n */\nexport const webSearchTool = tool<WebSearchParams>({\n description: `Search the web for current information. Use this when the user asks about:\n- Recent events, news, or current affairs\n- Real-time data (prices, weather, stocks, sports scores)\n- Information that might have changed after your training cutoff\n- Facts that need verification with current sources\n- Research topics that require up-to-date information`,\n\n location: \"server\", // Runs on server to protect API keys\n\n title: (args) => `Searching for \"${args.query}\"`,\n executingTitle: (args) => `Searching the web for \"${args.query}\"...`,\n completedTitle: (args) => `Found results for \"${args.query}\"`,\n\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"The search query to find relevant information\",\n },\n maxResults: {\n type: \"number\",\n description:\n \"Maximum number of results to return (default: 5, max: 10)\",\n minimum: 1,\n maximum: 10,\n },\n searchDepth: {\n type: \"string\",\n enum: [\"basic\", \"advanced\"],\n description:\n \"Search depth - 'advanced' provides more thorough results but may be slower\",\n },\n },\n required: [\"query\"],\n },\n\n needsApproval: false, // No user data exposed, just searching\n\n // Control what AI sees from results\n aiResponseMode: \"full\",\n aiContext: (result, args) => {\n if (!result.success) return `Search failed: ${result.error}`;\n const data = result.data as WebSearchResponse;\n return formatSearchResultsForAI(data);\n },\n});\n\n/**\n * Create a configured web search tool\n *\n * Supports both string provider names (lazy loaded) and direct provider imports (tree-shakeable).\n *\n * @param config - Web search configuration including provider and API key\n * @returns A configured tool definition ready to use\n *\n * @example\n * ```typescript\n * // ===== BEST FOR TREE-SHAKING: Direct provider import =====\n * import { createWebSearchTool, openaiProvider } from '@yourgpt/copilot-sdk/core';\n *\n * const webSearch = createWebSearchTool({\n * provider: openaiProvider, // Only this provider in bundle\n * apiKey: process.env.OPENAI_API_KEY,\n * });\n *\n * // ===== STRING PROVIDERS (Lazy loaded at runtime) =====\n *\n * // OpenAI (uses your OpenAI API key)\n * const webSearch = createWebSearchTool({\n * provider: 'openai',\n * apiKey: process.env.OPENAI_API_KEY,\n * });\n *\n * // Google (uses your Google/Gemini API key)\n * const webSearch = createWebSearchTool({\n * provider: 'google',\n * apiKey: process.env.GOOGLE_API_KEY,\n * });\n *\n * // Tavily (AI-optimized search with answer generation)\n * const webSearch = createWebSearchTool({\n * provider: 'tavily',\n * apiKey: process.env.TAVILY_API_KEY,\n * includeAnswer: true,\n * maxResults: 5,\n * });\n *\n * // Serper (Google results)\n * const webSearch = createWebSearchTool({\n * provider: 'serper',\n * apiKey: process.env.SERPER_API_KEY,\n * });\n *\n * // Brave Search (privacy-focused)\n * const webSearch = createWebSearchTool({\n * provider: 'brave',\n * apiKey: process.env.BRAVE_API_KEY,\n * });\n *\n * // Self-hosted SearXNG (no API key needed)\n * const webSearch = createWebSearchTool({\n * provider: 'searxng',\n * baseUrl: 'https://your-searxng-instance.com',\n * });\n *\n * // Exa (AI-optimized semantic search)\n * const webSearch = createWebSearchTool({\n * provider: 'exa',\n * apiKey: process.env.EXA_API_KEY,\n * searchDepth: 'advanced',\n * });\n * ```\n */\nexport function createWebSearchTool(\n config: WebSearchConfigExtended,\n): ToolDefinition<WebSearchParams> {\n return {\n name: \"web_search\",\n ...webSearchTool,\n handler: async (params: WebSearchParams) => {\n try {\n const response = await executeWebSearch(\n {\n query: params.query,\n maxResults: params.maxResults ?? config.maxResults ?? 5,\n searchDepth: params.searchDepth ?? config.searchDepth ?? \"basic\",\n },\n config,\n );\n\n // Build the AI context string\n const aiContext = formatSearchResultsForAI(response);\n\n return {\n success: true,\n message: summarizeSearchResults(response),\n data: response,\n _aiContext: aiContext,\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : \"Web search failed\";\n return failure(errorMessage);\n }\n },\n };\n}\n\n/**\n * Utility types for web search tool configuration\n */\nexport type {\n WebSearchConfig,\n WebSearchParams,\n WebSearchResponse,\n WebSearchProviderInterface,\n};\nexport type { WebSearchConfigExtended };\n"]}
1
+ {"version":3,"sources":["../src/core/tools/builtin/webSearch.ts"],"names":["tool","formatSearchResultsForAI","executeWebSearch","summarizeSearchResults","failure"],"mappings":";;;;;;AAoDO,IAAM,gBAAgBA,sBAAA,CAAsB;AAAA,EACjD,WAAA,EAAa,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qDAAA,CAAA;AAAA,EAOb,QAAA,EAAU,QAAA;AAAA;AAAA,EAEV,KAAA,EAAO,CAAC,IAAA,KAAS,CAAA,eAAA,EAAkB,KAAK,KAAK,CAAA,CAAA,CAAA;AAAA,EAC7C,cAAA,EAAgB,CAAC,IAAA,KAAS,CAAA,uBAAA,EAA0B,KAAK,KAAK,CAAA,IAAA,CAAA;AAAA,EAC9D,cAAA,EAAgB,CAAC,IAAA,KAAS,CAAA,mBAAA,EAAsB,KAAK,KAAK,CAAA,CAAA,CAAA;AAAA,EAE1D,WAAA,EAAa;AAAA,IACX,IAAA,EAAM,QAAA;AAAA,IACN,UAAA,EAAY;AAAA,MACV,KAAA,EAAO;AAAA,QACL,IAAA,EAAM,QAAA;AAAA,QACN,WAAA,EAAa;AAAA,OACf;AAAA,MACA,UAAA,EAAY;AAAA,QACV,IAAA,EAAM,QAAA;AAAA,QACN,WAAA,EACE,2DAAA;AAAA,QACF,OAAA,EAAS,CAAA;AAAA,QACT,OAAA,EAAS;AAAA,OACX;AAAA,MACA,WAAA,EAAa;AAAA,QACX,IAAA,EAAM,QAAA;AAAA,QACN,IAAA,EAAM,CAAC,OAAA,EAAS,UAAU,CAAA;AAAA,QAC1B,WAAA,EACE;AAAA;AACJ,KACF;AAAA,IACA,QAAA,EAAU,CAAC,OAAO;AAAA,GACpB;AAAA,EAEA,aAAA,EAAe,KAAA;AAAA;AAAA;AAAA,EAGf,cAAA,EAAgB,MAAA;AAAA,EAChB,SAAA,EAAW,CAAC,MAAA,EAAQ,IAAA,KAAS;AAC3B,IAAA,IAAI,CAAC,MAAA,CAAO,OAAA,EAAS,OAAO,CAAA,eAAA,EAAkB,OAAO,KAAK,CAAA,CAAA;AAC1D,IAAA,MAAM,OAAO,MAAA,CAAO,IAAA;AACpB,IAAA,OAAOC,2CAAyB,IAAI,CAAA;AAAA,EACtC;AACF,CAAC;AAoEM,SAAS,oBACd,MAAA,EACiC;AACjC,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,YAAA;AAAA,IACN,GAAG,aAAA;AAAA,IACH,OAAA,EAAS,OAAO,MAAA,KAA4B;AAC1C,MAAA,IAAI;AACF,QAAA,MAAM,WAAW,MAAMC,kCAAA;AAAA,UACrB;AAAA,YACE,OAAO,MAAA,CAAO,KAAA;AAAA,YACd,UAAA,EAAY,MAAA,CAAO,UAAA,IAAc,MAAA,CAAO,UAAA,IAAc,CAAA;AAAA,YACtD,WAAA,EAAa,MAAA,CAAO,WAAA,IAAe,MAAA,CAAO,WAAA,IAAe;AAAA,WAC3D;AAAA,UACA;AAAA,SACF;AAGA,QAAA,MAAM,SAAA,GAAYD,2CAAyB,QAAQ,CAAA;AAEnD,QAAA,OAAO;AAAA,UACL,OAAA,EAAS,IAAA;AAAA,UACT,OAAA,EAASE,yCAAuB,QAAQ,CAAA;AAAA,UACxC,IAAA,EAAM,QAAA;AAAA,UACN,UAAA,EAAY;AAAA,SACd;AAAA,MACF,SAAS,KAAA,EAAO;AACd,QAAA,MAAM,YAAA,GACJ,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,mBAAA;AAC3C,QAAA,OAAOC,0BAAQ,YAAY,CAAA;AAAA,MAC7B;AAAA,IACF;AAAA,GACF;AACF","file":"chunk-GSTTJ46F.cjs","sourcesContent":["/**\n * Built-in Web Search Tool\n *\n * A pre-configured tool for searching the web with multiple provider support.\n * Runs on the server to protect API keys.\n *\n * Supports tree-shaking - import providers directly for smaller bundles.\n *\n * @example\n * ```typescript\n * // Option 1: String provider (lazy loaded at runtime)\n * import { createWebSearchTool } from '@yourgpt/copilot-sdk';\n * const webSearch = createWebSearchTool({\n * provider: 'tavily',\n * apiKey: process.env.TAVILY_API_KEY,\n * });\n *\n * // Option 2: Direct provider import (best for tree-shaking)\n * import { createWebSearchTool, tavilyProvider } from '@yourgpt/copilot-sdk';\n * const webSearch = createWebSearchTool({\n * provider: tavilyProvider,\n * apiKey: process.env.TAVILY_API_KEY,\n * });\n *\n * // Add to your runtime\n * const runtime = createRuntime({\n * tools: [webSearch],\n * });\n * ```\n */\n\nimport { tool, success, failure } from \"../../types/tools\";\nimport type { ToolDefinition } from \"../../types/tools\";\nimport {\n executeWebSearch,\n formatSearchResultsForAI,\n summarizeSearchResults,\n type WebSearchConfigExtended,\n} from \"../webSearch\";\nimport type {\n WebSearchConfig,\n WebSearchParams,\n WebSearchResponse,\n WebSearchProviderInterface,\n} from \"../webSearch/types\";\n\n/**\n * Base web search tool definition\n *\n * This is the core tool definition. Use `createWebSearchTool()` to create\n * a configured instance with your provider settings.\n */\nexport const webSearchTool = tool<WebSearchParams>({\n description: `Search the web for current information. Use this when the user asks about:\n- Recent events, news, or current affairs\n- Real-time data (prices, weather, stocks, sports scores)\n- Information that might have changed after your training cutoff\n- Facts that need verification with current sources\n- Research topics that require up-to-date information`,\n\n location: \"server\", // Runs on server to protect API keys\n\n title: (args) => `Searching for \"${args.query}\"`,\n executingTitle: (args) => `Searching the web for \"${args.query}\"...`,\n completedTitle: (args) => `Found results for \"${args.query}\"`,\n\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"The search query to find relevant information\",\n },\n maxResults: {\n type: \"number\",\n description:\n \"Maximum number of results to return (default: 5, max: 10)\",\n minimum: 1,\n maximum: 10,\n },\n searchDepth: {\n type: \"string\",\n enum: [\"basic\", \"advanced\"],\n description:\n \"Search depth - 'advanced' provides more thorough results but may be slower\",\n },\n },\n required: [\"query\"],\n },\n\n needsApproval: false, // No user data exposed, just searching\n\n // Control what AI sees from results\n aiResponseMode: \"full\",\n aiContext: (result, args) => {\n if (!result.success) return `Search failed: ${result.error}`;\n const data = result.data as WebSearchResponse;\n return formatSearchResultsForAI(data);\n },\n});\n\n/**\n * Create a configured web search tool\n *\n * Supports both string provider names (lazy loaded) and direct provider imports (tree-shakeable).\n *\n * @param config - Web search configuration including provider and API key\n * @returns A configured tool definition ready to use\n *\n * @example\n * ```typescript\n * // ===== BEST FOR TREE-SHAKING: Direct provider import =====\n * import { createWebSearchTool, openaiProvider } from '@yourgpt/copilot-sdk/core';\n *\n * const webSearch = createWebSearchTool({\n * provider: openaiProvider, // Only this provider in bundle\n * apiKey: process.env.OPENAI_API_KEY,\n * });\n *\n * // ===== STRING PROVIDERS (Lazy loaded at runtime) =====\n *\n * // OpenAI (uses your OpenAI API key)\n * const webSearch = createWebSearchTool({\n * provider: 'openai',\n * apiKey: process.env.OPENAI_API_KEY,\n * });\n *\n * // Google (uses your Google/Gemini API key)\n * const webSearch = createWebSearchTool({\n * provider: 'google',\n * apiKey: process.env.GOOGLE_API_KEY,\n * });\n *\n * // Tavily (AI-optimized search with answer generation)\n * const webSearch = createWebSearchTool({\n * provider: 'tavily',\n * apiKey: process.env.TAVILY_API_KEY,\n * includeAnswer: true,\n * maxResults: 5,\n * });\n *\n * // Serper (Google results)\n * const webSearch = createWebSearchTool({\n * provider: 'serper',\n * apiKey: process.env.SERPER_API_KEY,\n * });\n *\n * // Brave Search (privacy-focused)\n * const webSearch = createWebSearchTool({\n * provider: 'brave',\n * apiKey: process.env.BRAVE_API_KEY,\n * });\n *\n * // Self-hosted SearXNG (no API key needed)\n * const webSearch = createWebSearchTool({\n * provider: 'searxng',\n * baseUrl: 'https://your-searxng-instance.com',\n * });\n *\n * // Exa (AI-optimized semantic search)\n * const webSearch = createWebSearchTool({\n * provider: 'exa',\n * apiKey: process.env.EXA_API_KEY,\n * searchDepth: 'advanced',\n * });\n * ```\n */\nexport function createWebSearchTool(\n config: WebSearchConfigExtended,\n): ToolDefinition<WebSearchParams> {\n return {\n name: \"web_search\",\n ...webSearchTool,\n handler: async (params: WebSearchParams) => {\n try {\n const response = await executeWebSearch(\n {\n query: params.query,\n maxResults: params.maxResults ?? config.maxResults ?? 5,\n searchDepth: params.searchDepth ?? config.searchDepth ?? \"basic\",\n },\n config,\n );\n\n // Build the AI context string\n const aiContext = formatSearchResultsForAI(response);\n\n return {\n success: true,\n message: summarizeSearchResults(response),\n data: response,\n _aiContext: aiContext,\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : \"Web search failed\";\n return failure(errorMessage);\n }\n },\n };\n}\n\n/**\n * Utility types for web search tool configuration\n */\nexport type {\n WebSearchConfig,\n WebSearchParams,\n WebSearchResponse,\n WebSearchProviderInterface,\n};\nexport type { WebSearchConfigExtended };\n"]}
@@ -1,4 +1,4 @@
1
- import { tool, failure } from './chunk-BRUDSHCV.js';
1
+ import { tool, failure } from './chunk-BMYNG3WM.js';
2
2
  import { formatSearchResultsForAI, executeWebSearch, summarizeSearchResults } from './chunk-XGITAEXU.js';
3
3
 
4
4
  // src/core/tools/builtin/webSearch.ts
@@ -75,5 +75,5 @@ function createWebSearchTool(config) {
75
75
  }
76
76
 
77
77
  export { createWebSearchTool, webSearchTool };
78
- //# sourceMappingURL=chunk-7YZVSG62.js.map
79
- //# sourceMappingURL=chunk-7YZVSG62.js.map
78
+ //# sourceMappingURL=chunk-VUHP6TAN.js.map
79
+ //# sourceMappingURL=chunk-VUHP6TAN.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/tools/builtin/webSearch.ts"],"names":[],"mappings":";;;;AAoDO,IAAM,gBAAgB,IAAA,CAAsB;AAAA,EACjD,WAAA,EAAa,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qDAAA,CAAA;AAAA,EAOb,QAAA,EAAU,QAAA;AAAA;AAAA,EAEV,KAAA,EAAO,CAAC,IAAA,KAAS,CAAA,eAAA,EAAkB,KAAK,KAAK,CAAA,CAAA,CAAA;AAAA,EAC7C,cAAA,EAAgB,CAAC,IAAA,KAAS,CAAA,uBAAA,EAA0B,KAAK,KAAK,CAAA,IAAA,CAAA;AAAA,EAC9D,cAAA,EAAgB,CAAC,IAAA,KAAS,CAAA,mBAAA,EAAsB,KAAK,KAAK,CAAA,CAAA,CAAA;AAAA,EAE1D,WAAA,EAAa;AAAA,IACX,IAAA,EAAM,QAAA;AAAA,IACN,UAAA,EAAY;AAAA,MACV,KAAA,EAAO;AAAA,QACL,IAAA,EAAM,QAAA;AAAA,QACN,WAAA,EAAa;AAAA,OACf;AAAA,MACA,UAAA,EAAY;AAAA,QACV,IAAA,EAAM,QAAA;AAAA,QACN,WAAA,EACE,2DAAA;AAAA,QACF,OAAA,EAAS,CAAA;AAAA,QACT,OAAA,EAAS;AAAA,OACX;AAAA,MACA,WAAA,EAAa;AAAA,QACX,IAAA,EAAM,QAAA;AAAA,QACN,IAAA,EAAM,CAAC,OAAA,EAAS,UAAU,CAAA;AAAA,QAC1B,WAAA,EACE;AAAA;AACJ,KACF;AAAA,IACA,QAAA,EAAU,CAAC,OAAO;AAAA,GACpB;AAAA,EAEA,aAAA,EAAe,KAAA;AAAA;AAAA;AAAA,EAGf,cAAA,EAAgB,MAAA;AAAA,EAChB,SAAA,EAAW,CAAC,MAAA,EAAQ,IAAA,KAAS;AAC3B,IAAA,IAAI,CAAC,MAAA,CAAO,OAAA,EAAS,OAAO,CAAA,eAAA,EAAkB,OAAO,KAAK,CAAA,CAAA;AAC1D,IAAA,MAAM,OAAO,MAAA,CAAO,IAAA;AACpB,IAAA,OAAO,yBAAyB,IAAI,CAAA;AAAA,EACtC;AACF,CAAC;AAoEM,SAAS,oBACd,MAAA,EACiC;AACjC,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,YAAA;AAAA,IACN,GAAG,aAAA;AAAA,IACH,OAAA,EAAS,OAAO,MAAA,KAA4B;AAC1C,MAAA,IAAI;AACF,QAAA,MAAM,WAAW,MAAM,gBAAA;AAAA,UACrB;AAAA,YACE,OAAO,MAAA,CAAO,KAAA;AAAA,YACd,UAAA,EAAY,MAAA,CAAO,UAAA,IAAc,MAAA,CAAO,UAAA,IAAc,CAAA;AAAA,YACtD,WAAA,EAAa,MAAA,CAAO,WAAA,IAAe,MAAA,CAAO,WAAA,IAAe;AAAA,WAC3D;AAAA,UACA;AAAA,SACF;AAGA,QAAA,MAAM,SAAA,GAAY,yBAAyB,QAAQ,CAAA;AAEnD,QAAA,OAAO;AAAA,UACL,OAAA,EAAS,IAAA;AAAA,UACT,OAAA,EAAS,uBAAuB,QAAQ,CAAA;AAAA,UACxC,IAAA,EAAM,QAAA;AAAA,UACN,UAAA,EAAY;AAAA,SACd;AAAA,MACF,SAAS,KAAA,EAAO;AACd,QAAA,MAAM,YAAA,GACJ,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,mBAAA;AAC3C,QAAA,OAAO,QAAQ,YAAY,CAAA;AAAA,MAC7B;AAAA,IACF;AAAA,GACF;AACF","file":"chunk-7YZVSG62.js","sourcesContent":["/**\n * Built-in Web Search Tool\n *\n * A pre-configured tool for searching the web with multiple provider support.\n * Runs on the server to protect API keys.\n *\n * Supports tree-shaking - import providers directly for smaller bundles.\n *\n * @example\n * ```typescript\n * // Option 1: String provider (lazy loaded at runtime)\n * import { createWebSearchTool } from '@yourgpt/copilot-sdk';\n * const webSearch = createWebSearchTool({\n * provider: 'tavily',\n * apiKey: process.env.TAVILY_API_KEY,\n * });\n *\n * // Option 2: Direct provider import (best for tree-shaking)\n * import { createWebSearchTool, tavilyProvider } from '@yourgpt/copilot-sdk';\n * const webSearch = createWebSearchTool({\n * provider: tavilyProvider,\n * apiKey: process.env.TAVILY_API_KEY,\n * });\n *\n * // Add to your runtime\n * const runtime = createRuntime({\n * tools: [webSearch],\n * });\n * ```\n */\n\nimport { tool, success, failure } from \"../../types/tools\";\nimport type { ToolDefinition } from \"../../types/tools\";\nimport {\n executeWebSearch,\n formatSearchResultsForAI,\n summarizeSearchResults,\n type WebSearchConfigExtended,\n} from \"../webSearch\";\nimport type {\n WebSearchConfig,\n WebSearchParams,\n WebSearchResponse,\n WebSearchProviderInterface,\n} from \"../webSearch/types\";\n\n/**\n * Base web search tool definition\n *\n * This is the core tool definition. Use `createWebSearchTool()` to create\n * a configured instance with your provider settings.\n */\nexport const webSearchTool = tool<WebSearchParams>({\n description: `Search the web for current information. Use this when the user asks about:\n- Recent events, news, or current affairs\n- Real-time data (prices, weather, stocks, sports scores)\n- Information that might have changed after your training cutoff\n- Facts that need verification with current sources\n- Research topics that require up-to-date information`,\n\n location: \"server\", // Runs on server to protect API keys\n\n title: (args) => `Searching for \"${args.query}\"`,\n executingTitle: (args) => `Searching the web for \"${args.query}\"...`,\n completedTitle: (args) => `Found results for \"${args.query}\"`,\n\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"The search query to find relevant information\",\n },\n maxResults: {\n type: \"number\",\n description:\n \"Maximum number of results to return (default: 5, max: 10)\",\n minimum: 1,\n maximum: 10,\n },\n searchDepth: {\n type: \"string\",\n enum: [\"basic\", \"advanced\"],\n description:\n \"Search depth - 'advanced' provides more thorough results but may be slower\",\n },\n },\n required: [\"query\"],\n },\n\n needsApproval: false, // No user data exposed, just searching\n\n // Control what AI sees from results\n aiResponseMode: \"full\",\n aiContext: (result, args) => {\n if (!result.success) return `Search failed: ${result.error}`;\n const data = result.data as WebSearchResponse;\n return formatSearchResultsForAI(data);\n },\n});\n\n/**\n * Create a configured web search tool\n *\n * Supports both string provider names (lazy loaded) and direct provider imports (tree-shakeable).\n *\n * @param config - Web search configuration including provider and API key\n * @returns A configured tool definition ready to use\n *\n * @example\n * ```typescript\n * // ===== BEST FOR TREE-SHAKING: Direct provider import =====\n * import { createWebSearchTool, openaiProvider } from '@yourgpt/copilot-sdk/core';\n *\n * const webSearch = createWebSearchTool({\n * provider: openaiProvider, // Only this provider in bundle\n * apiKey: process.env.OPENAI_API_KEY,\n * });\n *\n * // ===== STRING PROVIDERS (Lazy loaded at runtime) =====\n *\n * // OpenAI (uses your OpenAI API key)\n * const webSearch = createWebSearchTool({\n * provider: 'openai',\n * apiKey: process.env.OPENAI_API_KEY,\n * });\n *\n * // Google (uses your Google/Gemini API key)\n * const webSearch = createWebSearchTool({\n * provider: 'google',\n * apiKey: process.env.GOOGLE_API_KEY,\n * });\n *\n * // Tavily (AI-optimized search with answer generation)\n * const webSearch = createWebSearchTool({\n * provider: 'tavily',\n * apiKey: process.env.TAVILY_API_KEY,\n * includeAnswer: true,\n * maxResults: 5,\n * });\n *\n * // Serper (Google results)\n * const webSearch = createWebSearchTool({\n * provider: 'serper',\n * apiKey: process.env.SERPER_API_KEY,\n * });\n *\n * // Brave Search (privacy-focused)\n * const webSearch = createWebSearchTool({\n * provider: 'brave',\n * apiKey: process.env.BRAVE_API_KEY,\n * });\n *\n * // Self-hosted SearXNG (no API key needed)\n * const webSearch = createWebSearchTool({\n * provider: 'searxng',\n * baseUrl: 'https://your-searxng-instance.com',\n * });\n *\n * // Exa (AI-optimized semantic search)\n * const webSearch = createWebSearchTool({\n * provider: 'exa',\n * apiKey: process.env.EXA_API_KEY,\n * searchDepth: 'advanced',\n * });\n * ```\n */\nexport function createWebSearchTool(\n config: WebSearchConfigExtended,\n): ToolDefinition<WebSearchParams> {\n return {\n name: \"web_search\",\n ...webSearchTool,\n handler: async (params: WebSearchParams) => {\n try {\n const response = await executeWebSearch(\n {\n query: params.query,\n maxResults: params.maxResults ?? config.maxResults ?? 5,\n searchDepth: params.searchDepth ?? config.searchDepth ?? \"basic\",\n },\n config,\n );\n\n // Build the AI context string\n const aiContext = formatSearchResultsForAI(response);\n\n return {\n success: true,\n message: summarizeSearchResults(response),\n data: response,\n _aiContext: aiContext,\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : \"Web search failed\";\n return failure(errorMessage);\n }\n },\n };\n}\n\n/**\n * Utility types for web search tool configuration\n */\nexport type {\n WebSearchConfig,\n WebSearchParams,\n WebSearchResponse,\n WebSearchProviderInterface,\n};\nexport type { WebSearchConfigExtended };\n"]}
1
+ {"version":3,"sources":["../src/core/tools/builtin/webSearch.ts"],"names":[],"mappings":";;;;AAoDO,IAAM,gBAAgB,IAAA,CAAsB;AAAA,EACjD,WAAA,EAAa,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qDAAA,CAAA;AAAA,EAOb,QAAA,EAAU,QAAA;AAAA;AAAA,EAEV,KAAA,EAAO,CAAC,IAAA,KAAS,CAAA,eAAA,EAAkB,KAAK,KAAK,CAAA,CAAA,CAAA;AAAA,EAC7C,cAAA,EAAgB,CAAC,IAAA,KAAS,CAAA,uBAAA,EAA0B,KAAK,KAAK,CAAA,IAAA,CAAA;AAAA,EAC9D,cAAA,EAAgB,CAAC,IAAA,KAAS,CAAA,mBAAA,EAAsB,KAAK,KAAK,CAAA,CAAA,CAAA;AAAA,EAE1D,WAAA,EAAa;AAAA,IACX,IAAA,EAAM,QAAA;AAAA,IACN,UAAA,EAAY;AAAA,MACV,KAAA,EAAO;AAAA,QACL,IAAA,EAAM,QAAA;AAAA,QACN,WAAA,EAAa;AAAA,OACf;AAAA,MACA,UAAA,EAAY;AAAA,QACV,IAAA,EAAM,QAAA;AAAA,QACN,WAAA,EACE,2DAAA;AAAA,QACF,OAAA,EAAS,CAAA;AAAA,QACT,OAAA,EAAS;AAAA,OACX;AAAA,MACA,WAAA,EAAa;AAAA,QACX,IAAA,EAAM,QAAA;AAAA,QACN,IAAA,EAAM,CAAC,OAAA,EAAS,UAAU,CAAA;AAAA,QAC1B,WAAA,EACE;AAAA;AACJ,KACF;AAAA,IACA,QAAA,EAAU,CAAC,OAAO;AAAA,GACpB;AAAA,EAEA,aAAA,EAAe,KAAA;AAAA;AAAA;AAAA,EAGf,cAAA,EAAgB,MAAA;AAAA,EAChB,SAAA,EAAW,CAAC,MAAA,EAAQ,IAAA,KAAS;AAC3B,IAAA,IAAI,CAAC,MAAA,CAAO,OAAA,EAAS,OAAO,CAAA,eAAA,EAAkB,OAAO,KAAK,CAAA,CAAA;AAC1D,IAAA,MAAM,OAAO,MAAA,CAAO,IAAA;AACpB,IAAA,OAAO,yBAAyB,IAAI,CAAA;AAAA,EACtC;AACF,CAAC;AAoEM,SAAS,oBACd,MAAA,EACiC;AACjC,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,YAAA;AAAA,IACN,GAAG,aAAA;AAAA,IACH,OAAA,EAAS,OAAO,MAAA,KAA4B;AAC1C,MAAA,IAAI;AACF,QAAA,MAAM,WAAW,MAAM,gBAAA;AAAA,UACrB;AAAA,YACE,OAAO,MAAA,CAAO,KAAA;AAAA,YACd,UAAA,EAAY,MAAA,CAAO,UAAA,IAAc,MAAA,CAAO,UAAA,IAAc,CAAA;AAAA,YACtD,WAAA,EAAa,MAAA,CAAO,WAAA,IAAe,MAAA,CAAO,WAAA,IAAe;AAAA,WAC3D;AAAA,UACA;AAAA,SACF;AAGA,QAAA,MAAM,SAAA,GAAY,yBAAyB,QAAQ,CAAA;AAEnD,QAAA,OAAO;AAAA,UACL,OAAA,EAAS,IAAA;AAAA,UACT,OAAA,EAAS,uBAAuB,QAAQ,CAAA;AAAA,UACxC,IAAA,EAAM,QAAA;AAAA,UACN,UAAA,EAAY;AAAA,SACd;AAAA,MACF,SAAS,KAAA,EAAO;AACd,QAAA,MAAM,YAAA,GACJ,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,mBAAA;AAC3C,QAAA,OAAO,QAAQ,YAAY,CAAA;AAAA,MAC7B;AAAA,IACF;AAAA,GACF;AACF","file":"chunk-VUHP6TAN.js","sourcesContent":["/**\n * Built-in Web Search Tool\n *\n * A pre-configured tool for searching the web with multiple provider support.\n * Runs on the server to protect API keys.\n *\n * Supports tree-shaking - import providers directly for smaller bundles.\n *\n * @example\n * ```typescript\n * // Option 1: String provider (lazy loaded at runtime)\n * import { createWebSearchTool } from '@yourgpt/copilot-sdk';\n * const webSearch = createWebSearchTool({\n * provider: 'tavily',\n * apiKey: process.env.TAVILY_API_KEY,\n * });\n *\n * // Option 2: Direct provider import (best for tree-shaking)\n * import { createWebSearchTool, tavilyProvider } from '@yourgpt/copilot-sdk';\n * const webSearch = createWebSearchTool({\n * provider: tavilyProvider,\n * apiKey: process.env.TAVILY_API_KEY,\n * });\n *\n * // Add to your runtime\n * const runtime = createRuntime({\n * tools: [webSearch],\n * });\n * ```\n */\n\nimport { tool, success, failure } from \"../../types/tools\";\nimport type { ToolDefinition } from \"../../types/tools\";\nimport {\n executeWebSearch,\n formatSearchResultsForAI,\n summarizeSearchResults,\n type WebSearchConfigExtended,\n} from \"../webSearch\";\nimport type {\n WebSearchConfig,\n WebSearchParams,\n WebSearchResponse,\n WebSearchProviderInterface,\n} from \"../webSearch/types\";\n\n/**\n * Base web search tool definition\n *\n * This is the core tool definition. Use `createWebSearchTool()` to create\n * a configured instance with your provider settings.\n */\nexport const webSearchTool = tool<WebSearchParams>({\n description: `Search the web for current information. Use this when the user asks about:\n- Recent events, news, or current affairs\n- Real-time data (prices, weather, stocks, sports scores)\n- Information that might have changed after your training cutoff\n- Facts that need verification with current sources\n- Research topics that require up-to-date information`,\n\n location: \"server\", // Runs on server to protect API keys\n\n title: (args) => `Searching for \"${args.query}\"`,\n executingTitle: (args) => `Searching the web for \"${args.query}\"...`,\n completedTitle: (args) => `Found results for \"${args.query}\"`,\n\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"The search query to find relevant information\",\n },\n maxResults: {\n type: \"number\",\n description:\n \"Maximum number of results to return (default: 5, max: 10)\",\n minimum: 1,\n maximum: 10,\n },\n searchDepth: {\n type: \"string\",\n enum: [\"basic\", \"advanced\"],\n description:\n \"Search depth - 'advanced' provides more thorough results but may be slower\",\n },\n },\n required: [\"query\"],\n },\n\n needsApproval: false, // No user data exposed, just searching\n\n // Control what AI sees from results\n aiResponseMode: \"full\",\n aiContext: (result, args) => {\n if (!result.success) return `Search failed: ${result.error}`;\n const data = result.data as WebSearchResponse;\n return formatSearchResultsForAI(data);\n },\n});\n\n/**\n * Create a configured web search tool\n *\n * Supports both string provider names (lazy loaded) and direct provider imports (tree-shakeable).\n *\n * @param config - Web search configuration including provider and API key\n * @returns A configured tool definition ready to use\n *\n * @example\n * ```typescript\n * // ===== BEST FOR TREE-SHAKING: Direct provider import =====\n * import { createWebSearchTool, openaiProvider } from '@yourgpt/copilot-sdk/core';\n *\n * const webSearch = createWebSearchTool({\n * provider: openaiProvider, // Only this provider in bundle\n * apiKey: process.env.OPENAI_API_KEY,\n * });\n *\n * // ===== STRING PROVIDERS (Lazy loaded at runtime) =====\n *\n * // OpenAI (uses your OpenAI API key)\n * const webSearch = createWebSearchTool({\n * provider: 'openai',\n * apiKey: process.env.OPENAI_API_KEY,\n * });\n *\n * // Google (uses your Google/Gemini API key)\n * const webSearch = createWebSearchTool({\n * provider: 'google',\n * apiKey: process.env.GOOGLE_API_KEY,\n * });\n *\n * // Tavily (AI-optimized search with answer generation)\n * const webSearch = createWebSearchTool({\n * provider: 'tavily',\n * apiKey: process.env.TAVILY_API_KEY,\n * includeAnswer: true,\n * maxResults: 5,\n * });\n *\n * // Serper (Google results)\n * const webSearch = createWebSearchTool({\n * provider: 'serper',\n * apiKey: process.env.SERPER_API_KEY,\n * });\n *\n * // Brave Search (privacy-focused)\n * const webSearch = createWebSearchTool({\n * provider: 'brave',\n * apiKey: process.env.BRAVE_API_KEY,\n * });\n *\n * // Self-hosted SearXNG (no API key needed)\n * const webSearch = createWebSearchTool({\n * provider: 'searxng',\n * baseUrl: 'https://your-searxng-instance.com',\n * });\n *\n * // Exa (AI-optimized semantic search)\n * const webSearch = createWebSearchTool({\n * provider: 'exa',\n * apiKey: process.env.EXA_API_KEY,\n * searchDepth: 'advanced',\n * });\n * ```\n */\nexport function createWebSearchTool(\n config: WebSearchConfigExtended,\n): ToolDefinition<WebSearchParams> {\n return {\n name: \"web_search\",\n ...webSearchTool,\n handler: async (params: WebSearchParams) => {\n try {\n const response = await executeWebSearch(\n {\n query: params.query,\n maxResults: params.maxResults ?? config.maxResults ?? 5,\n searchDepth: params.searchDepth ?? config.searchDepth ?? \"basic\",\n },\n config,\n );\n\n // Build the AI context string\n const aiContext = formatSearchResultsForAI(response);\n\n return {\n success: true,\n message: summarizeSearchResults(response),\n data: response,\n _aiContext: aiContext,\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : \"Web search failed\";\n return failure(errorMessage);\n }\n },\n };\n}\n\n/**\n * Utility types for web search tool configuration\n */\nexport type {\n WebSearchConfig,\n WebSearchParams,\n WebSearchResponse,\n WebSearchProviderInterface,\n};\nexport type { WebSearchConfigExtended };\n"]}
@@ -1,4 +1,4 @@
1
- import { ThreadManager, isConsoleCaptureActive, startConsoleCapture, isNetworkCaptureActive, startNetworkCapture, stopConsoleCapture, stopNetworkCapture, isScreenshotSupported, captureScreenshot, getConsoleLogs, getNetworkRequests, clearConsoleLogs, clearNetworkRequests, formatLogsForAI, formatRequestsForAI, detectIntent, streamSSE, zodObjectToInputSchema } from './chunk-7PJ4GAJR.js';
1
+ import { ThreadManager, isConsoleCaptureActive, startConsoleCapture, isNetworkCaptureActive, startNetworkCapture, stopConsoleCapture, stopNetworkCapture, isScreenshotSupported, captureScreenshot, getConsoleLogs, getNetworkRequests, clearConsoleLogs, clearNetworkRequests, formatLogsForAI, formatRequestsForAI, detectIntent, streamSSE, zodObjectToInputSchema } from './chunk-XAC7NTIO.js';
2
2
  import { createMCPClient, MCPToolAdapter } from './chunk-EWVQWTNV.js';
3
3
  import { createContext, useRef, useState, useCallback, useEffect, useMemo, useContext, useSyncExternalStore } from 'react';
4
4
  import { jsxs, jsx } from 'react/jsx-runtime';
@@ -161,7 +161,8 @@ function processStreamChunk(chunk, state) {
161
161
  newResults.set(chunk.id, {
162
162
  id: chunk.id,
163
163
  name: chunk.name,
164
- status: "executing"
164
+ status: "executing",
165
+ hidden: chunk.hidden
165
166
  });
166
167
  return { ...state, toolResults: newResults };
167
168
  }
@@ -315,6 +316,33 @@ function createEmptyAssistantMessage(id) {
315
316
  };
316
317
  }
317
318
 
319
+ // src/core/utils/resolvable.ts
320
+ function isGetter(value) {
321
+ return typeof value === "function";
322
+ }
323
+ async function resolveValue(value) {
324
+ if (!isGetter(value)) {
325
+ return value;
326
+ }
327
+ try {
328
+ return await value();
329
+ } catch (error) {
330
+ console.error("[Copilot SDK] Error resolving dynamic config value:", error);
331
+ throw error;
332
+ }
333
+ }
334
+ async function resolveValues(values) {
335
+ const entries = Object.entries(values);
336
+ const hasGetters = entries.some(([, v]) => isGetter(v));
337
+ if (!hasGetters) {
338
+ return values;
339
+ }
340
+ const resolved = await Promise.all(
341
+ entries.map(async ([key, val]) => [key, await resolveValue(val)])
342
+ );
343
+ return Object.fromEntries(resolved);
344
+ }
345
+
318
346
  // src/chat/adapters/HttpTransport.ts
319
347
  var HttpTransport = class {
320
348
  constructor(config) {
@@ -328,16 +356,28 @@ var HttpTransport = class {
328
356
  }
329
357
  /**
330
358
  * Send a chat request
359
+ * Resolves dynamic config values (url, headers, body) fresh at request time
331
360
  */
332
361
  async send(request) {
333
362
  this.abortController = new AbortController();
334
363
  this.streaming = true;
335
364
  try {
336
- const response = await fetch(this.config.url, {
365
+ console.log(
366
+ "[HttpTransport] Config headers type:",
367
+ typeof this.config.headers
368
+ );
369
+ console.log("[HttpTransport] Config headers:", this.config.headers);
370
+ const resolved = await resolveValues({
371
+ url: this.config.url,
372
+ headers: this.config.headers ?? {},
373
+ configBody: this.config.body ?? {}
374
+ });
375
+ console.log("[HttpTransport] Resolved headers:", resolved.headers);
376
+ const response = await fetch(resolved.url, {
337
377
  method: "POST",
338
378
  headers: {
339
379
  "Content-Type": "application/json",
340
- ...this.config.headers
380
+ ...resolved.headers
341
381
  },
342
382
  body: JSON.stringify({
343
383
  messages: request.messages,
@@ -347,6 +387,7 @@ var HttpTransport = class {
347
387
  tools: request.tools,
348
388
  actions: request.actions,
349
389
  streaming: this.config.streaming,
390
+ ...resolved.configBody,
350
391
  ...request.body
351
392
  }),
352
393
  signal: this.abortController.signal
@@ -388,6 +429,36 @@ var HttpTransport = class {
388
429
  isStreaming() {
389
430
  return this.streaming;
390
431
  }
432
+ /**
433
+ * Update headers configuration
434
+ * Can be static headers or a getter function for dynamic resolution
435
+ *
436
+ * @example
437
+ * ```typescript
438
+ * // Static
439
+ * transport.setHeaders({ "x-api-key": "new-key" });
440
+ *
441
+ * // Dynamic (resolved fresh on each request)
442
+ * transport.setHeaders(() => ({ Authorization: `Bearer ${getToken()}` }));
443
+ * ```
444
+ */
445
+ setHeaders(headers) {
446
+ this.config.headers = headers;
447
+ }
448
+ /**
449
+ * Update URL configuration
450
+ * Can be static URL or a getter function for dynamic resolution
451
+ */
452
+ setUrl(url) {
453
+ this.config.url = url;
454
+ }
455
+ /**
456
+ * Update body configuration
457
+ * Additional properties merged into every request body
458
+ */
459
+ setBody(body) {
460
+ this.config.body = body;
461
+ }
391
462
  /**
392
463
  * Create an async iterable from a ReadableStream
393
464
  */
@@ -511,6 +582,7 @@ var AbstractChat = class {
511
582
  systemPrompt: init.systemPrompt,
512
583
  streaming: init.streaming ?? true,
513
584
  headers: init.headers,
585
+ body: init.body,
514
586
  threadId: init.threadId,
515
587
  debug: init.debug
516
588
  };
@@ -518,6 +590,7 @@ var AbstractChat = class {
518
590
  this.transport = init.transport ?? new HttpTransport({
519
591
  url: init.runtimeUrl,
520
592
  headers: init.headers,
593
+ body: init.body,
521
594
  streaming: init.streaming ?? true
522
595
  });
523
596
  this.callbacks = init.callbacks ?? {};
@@ -783,6 +856,39 @@ var AbstractChat = class {
783
856
  this.config.systemPrompt = prompt;
784
857
  this.debug("System prompt updated", { length: prompt.length });
785
858
  }
859
+ /**
860
+ * Set headers configuration
861
+ * Can be static headers or a getter function for dynamic resolution
862
+ */
863
+ setHeaders(headers) {
864
+ this.config.headers = headers;
865
+ if (this.transport.setHeaders && headers !== void 0) {
866
+ this.transport.setHeaders(headers);
867
+ }
868
+ this.debug("Headers config updated");
869
+ }
870
+ /**
871
+ * Set URL configuration
872
+ * Can be static URL or a getter function for dynamic resolution
873
+ */
874
+ setUrl(url) {
875
+ this.config.runtimeUrl = url;
876
+ if (this.transport.setUrl) {
877
+ this.transport.setUrl(url);
878
+ }
879
+ this.debug("URL config updated");
880
+ }
881
+ /**
882
+ * Set body configuration
883
+ * Additional properties merged into every request body
884
+ */
885
+ setBody(body) {
886
+ this.config.body = body;
887
+ if (this.transport.setBody && body !== void 0) {
888
+ this.transport.setBody(body);
889
+ }
890
+ this.debug("Body config updated");
891
+ }
786
892
  /**
787
893
  * Build the request payload
788
894
  */
@@ -899,6 +1005,25 @@ ${this.dynamicContext}`.trim() : this.config.systemPrompt,
899
1005
  }
900
1006
  if (isStreamDone(chunk)) {
901
1007
  this.debug("streamDone", { chunk });
1008
+ if (chunk.type === "done" && chunk.messages?.length) {
1009
+ this.debug("processDoneMessages", {
1010
+ count: chunk.messages.length
1011
+ });
1012
+ for (const msg of chunk.messages) {
1013
+ if (msg.role === "assistant" && !msg.tool_calls?.length && msg.content) {
1014
+ continue;
1015
+ }
1016
+ const message = {
1017
+ id: generateMessageId(),
1018
+ role: msg.role,
1019
+ content: msg.content ?? "",
1020
+ toolCalls: msg.tool_calls,
1021
+ toolCallId: msg.tool_call_id,
1022
+ createdAt: /* @__PURE__ */ new Date()
1023
+ };
1024
+ this.state.pushMessage(message);
1025
+ }
1026
+ }
902
1027
  break;
903
1028
  }
904
1029
  }
@@ -925,13 +1050,37 @@ ${this.dynamicContext}`.trim() : this.config.systemPrompt,
925
1050
  * Handle JSON (non-streaming) response
926
1051
  */
927
1052
  handleJsonResponse(response) {
1053
+ const toolCallHiddenMap = /* @__PURE__ */ new Map();
1054
+ if (response.toolCalls) {
1055
+ for (const tc of response.toolCalls) {
1056
+ if (tc.hidden !== void 0) {
1057
+ toolCallHiddenMap.set(tc.id, tc.hidden);
1058
+ }
1059
+ }
1060
+ }
928
1061
  for (const msg of response.messages ?? []) {
1062
+ let metadata;
1063
+ if (msg.role === "assistant" && msg.tool_calls && toolCallHiddenMap.size > 0) {
1064
+ const toolCallsHidden = {};
1065
+ for (const tc of msg.tool_calls) {
1066
+ const hidden = toolCallHiddenMap.get(tc.id);
1067
+ if (hidden !== void 0) {
1068
+ toolCallsHidden[tc.id] = hidden;
1069
+ }
1070
+ }
1071
+ if (Object.keys(toolCallsHidden).length > 0) {
1072
+ metadata = { toolCallsHidden };
1073
+ }
1074
+ }
929
1075
  const message = {
930
1076
  id: generateMessageId(),
931
1077
  role: msg.role,
932
1078
  content: msg.content ?? "",
933
1079
  toolCalls: msg.tool_calls,
934
- createdAt: /* @__PURE__ */ new Date()
1080
+ // CRITICAL: Preserve toolCallId for tool messages (fixes Anthropic API errors)
1081
+ toolCallId: msg.tool_call_id,
1082
+ createdAt: /* @__PURE__ */ new Date(),
1083
+ metadata
935
1084
  };
936
1085
  this.state.pushMessage(message);
937
1086
  }
@@ -1195,7 +1344,8 @@ var AbstractAgentLoop = class {
1195
1344
  args: toolCall.args,
1196
1345
  status: "pending",
1197
1346
  approvalStatus: "none",
1198
- startedAt: /* @__PURE__ */ new Date()
1347
+ startedAt: /* @__PURE__ */ new Date(),
1348
+ hidden: tool?.hidden
1199
1349
  };
1200
1350
  this.addToolExecution(execution);
1201
1351
  this.callbacks.onToolStart?.(execution);
@@ -1458,6 +1608,7 @@ var ChatWithTools = class {
1458
1608
  systemPrompt: config.systemPrompt,
1459
1609
  streaming: config.streaming,
1460
1610
  headers: config.headers,
1611
+ body: config.body,
1461
1612
  threadId: config.threadId,
1462
1613
  debug: config.debug,
1463
1614
  initialMessages: config.initialMessages,
@@ -1641,6 +1792,27 @@ var ChatWithTools = class {
1641
1792
  setSystemPrompt(prompt) {
1642
1793
  this.chat.setSystemPrompt(prompt);
1643
1794
  }
1795
+ /**
1796
+ * Set headers configuration
1797
+ * Can be static headers or a getter function for dynamic resolution
1798
+ */
1799
+ setHeaders(headers) {
1800
+ this.chat.setHeaders(headers);
1801
+ }
1802
+ /**
1803
+ * Set URL configuration
1804
+ * Can be static URL or a getter function for dynamic resolution
1805
+ */
1806
+ setUrl(url) {
1807
+ this.chat.setUrl(url);
1808
+ }
1809
+ /**
1810
+ * Set body configuration
1811
+ * Additional properties merged into every request body
1812
+ */
1813
+ setBody(body) {
1814
+ this.chat.setBody(body);
1815
+ }
1644
1816
  // ============================================
1645
1817
  // Tool Registration
1646
1818
  // ============================================
@@ -2199,6 +2371,7 @@ function CopilotProvider({
2199
2371
  onError,
2200
2372
  streaming,
2201
2373
  headers,
2374
+ body,
2202
2375
  debug = false,
2203
2376
  maxIterations,
2204
2377
  maxIterationsMessage,
@@ -2243,6 +2416,7 @@ function CopilotProvider({
2243
2416
  initialMessages: uiInitialMessages,
2244
2417
  streaming,
2245
2418
  headers,
2419
+ body,
2246
2420
  debug,
2247
2421
  maxIterations,
2248
2422
  maxIterationsMessage
@@ -2267,6 +2441,24 @@ function CopilotProvider({
2267
2441
  debugLog("System prompt updated from prop");
2268
2442
  }
2269
2443
  }, [systemPrompt, debugLog]);
2444
+ useEffect(() => {
2445
+ if (chatRef.current && headers !== void 0) {
2446
+ chatRef.current.setHeaders(headers);
2447
+ debugLog("Headers config updated from prop");
2448
+ }
2449
+ }, [headers, debugLog]);
2450
+ useEffect(() => {
2451
+ if (chatRef.current && body !== void 0) {
2452
+ chatRef.current.setBody(body);
2453
+ debugLog("Body config updated from prop");
2454
+ }
2455
+ }, [body, debugLog]);
2456
+ useEffect(() => {
2457
+ if (chatRef.current && runtimeUrl !== void 0) {
2458
+ chatRef.current.setUrl(runtimeUrl);
2459
+ debugLog("URL config updated from prop");
2460
+ }
2461
+ }, [runtimeUrl, debugLog]);
2270
2462
  const messages = useSyncExternalStore(
2271
2463
  chatRef.current.subscribe,
2272
2464
  () => chatRef.current.messages,
@@ -2973,7 +3165,8 @@ function useToolExecutor() {
2973
3165
  args: toolCall.input,
2974
3166
  status: "executing",
2975
3167
  timestamp: Date.now(),
2976
- approvalStatus: "none"
3168
+ approvalStatus: "none",
3169
+ hidden: tool.hidden
2977
3170
  };
2978
3171
  addToolExecution?.(execution);
2979
3172
  try {
@@ -4280,5 +4473,5 @@ function useChat(config) {
4280
4473
  }
4281
4474
 
4282
4475
  export { AbstractAgentLoop, AbstractChat, CopilotProvider, ReactChat, ReactChatState, ReactThreadManager, ReactThreadManagerState, createMessageIntentHandler, createPermissionStorage, createReactChat, createReactChatState, createReactThreadManager, createReactThreadManagerState, createSessionPermissionCache, createToolIntentHandler, formatKnowledgeResultsForAI, initialAgentLoopState, searchKnowledgeBase, useAIAction, useAIActions, useAIContext, useAIContexts, useAITools, useAgent, useCapabilities, useChat, useCopilot, useDevLogger, useFeatureSupport, useKnowledgeBase, useMCPClient, useMCPTools, useMCPUIIntents, useSuggestions, useSupportedMediaTypes, useThreadManager, useTool, useToolExecutor, useToolWithSchema, useTools, useToolsWithSchema };
4283
- //# sourceMappingURL=chunk-3SP6V22Y.js.map
4284
- //# sourceMappingURL=chunk-3SP6V22Y.js.map
4476
+ //# sourceMappingURL=chunk-VXT2O6R6.js.map
4477
+ //# sourceMappingURL=chunk-VXT2O6R6.js.map