@cloudflare/codemode 0.3.4 → 0.3.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -2
- package/dist/ai.d.ts +7 -7
- package/dist/ai.js +2 -2
- package/dist/ai.js.map +1 -1
- package/dist/browser.d.ts +149 -0
- package/dist/browser.js +521 -0
- package/dist/browser.js.map +1 -0
- package/dist/{executor-wZjYdqEX.d.ts → executor-C-DgAHLS.d.ts} +13 -44
- package/dist/executor-types-CJ06IBzw.d.ts +36 -0
- package/dist/index.d.ts +15 -37
- package/dist/index.js +13 -3
- package/dist/index.js.map +1 -1
- package/dist/json-schema-types-1OL3uao0.d.ts +38 -0
- package/dist/{json-schema-types-DoQ0VISs.js → json-schema-types-CVt4X9cw.js} +43 -2
- package/dist/json-schema-types-CVt4X9cw.js.map +1 -0
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +72 -39
- package/dist/mcp.js.map +1 -1
- package/dist/resolve-BU1FGVYs.js +44 -0
- package/dist/resolve-BU1FGVYs.js.map +1 -0
- package/dist/{resolve-DULSpsq2.d.ts → resolve-E1SKV37h.d.ts} +3 -5
- package/dist/{shared-Hnh_Idta.d.ts → shared-C3CDOc8T.d.ts} +5 -5
- package/dist/shared-ra3HW2ti.js.map +1 -1
- package/dist/tanstack-ai.d.ts +3 -3
- package/dist/tanstack-ai.js +3 -3
- package/dist/tanstack-ai.js.map +1 -1
- package/package.json +14 -8
- package/dist/json-schema-types-DoQ0VISs.js.map +0 -1
- package/dist/resolve-DIQRkRqQ.js +0 -85
- package/dist/resolve-DIQRkRqQ.js.map +0 -1
package/dist/mcp.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp.js","names":[],"sources":["../src/mcp.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { InMemoryTransport } from \"@modelcontextprotocol/sdk/inMemory.js\";\nimport { z } from \"zod\";\nimport {\n generateTypesFromJsonSchema,\n type JsonSchemaToolDescriptors\n} from \"./json-schema-types\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { Executor } from \"./executor\";\n\nimport type { JSONSchema7 } from \"json-schema\";\n\n// -- Shared utilities --\n\nconst CHARS_PER_TOKEN = 4;\nconst MAX_TOKENS = 6000;\nconst MAX_CHARS = MAX_TOKENS * CHARS_PER_TOKEN;\n\nfunction truncateResponse(content: unknown): string {\n const text =\n typeof content === \"string\"\n ? content\n : (JSON.stringify(content, null, 2) ?? \"undefined\");\n\n if (text.length <= MAX_CHARS) {\n return text;\n }\n\n const truncated = text.slice(0, MAX_CHARS);\n const estimatedTokens = Math.ceil(text.length / CHARS_PER_TOKEN);\n\n return `${truncated}\\n\\n--- TRUNCATED ---\\nResponse was ~${estimatedTokens.toLocaleString()} tokens (limit: ${MAX_TOKENS.toLocaleString()}). Use more specific queries to reduce response size.`;\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\ntype CallToolResult = Awaited<ReturnType<Client[\"callTool\"]>>;\n\n/**\n * Unwrap an MCP CallToolResult so sandbox code sees plain values,\n * consistent with how createCodeTool exposes tool results.\n *\n * Priority:\n * 1. Compat `toolResult` → return directly\n * 2. `isError` → throw so sandbox gets a proper exception\n * 3. `structuredContent` → authoritative typed value when present\n * 4. All-text content → JSON.parse or raw string\n * 5. Mixed content (text + images/audio/resources) → return as-is,\n * since binary content has no clean plain-value representation\n */\nfunction unwrapMcpResult(result: CallToolResult): unknown {\n if (\"toolResult\" in result) {\n return result.toolResult;\n }\n\n if (result.isError) {\n const msg =\n result.content\n .filter((c) => c.type === \"text\")\n .map((c) => (\"text\" in c ? c.text : \"\"))\n .join(\"\\n\") || \"Tool call failed\";\n throw new Error(msg);\n }\n\n if (result.structuredContent != null) {\n return result.structuredContent;\n }\n\n const allText =\n result.content.length > 0 && result.content.every((c) => c.type === \"text\");\n if (allText) {\n const text = result.content\n .map((c) => (\"text\" in c ? c.text : \"\"))\n .join(\"\\n\");\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n\n return result;\n}\n\n// -- codeMcpServer --\n\nconst CODE_DESCRIPTION = `Execute code to achieve a goal.\n\nAvailable:\n{{types}}\n\nWrite an async arrow function in JavaScript that returns the result.\nDo NOT use TypeScript syntax — no type annotations, interfaces, or generics.\nDo NOT define named functions then call them — just write the arrow function body directly.\n\n{{example}}`;\n\n/**\n * Wrap an existing MCP server with a single codemode `code` tool.\n *\n * Connects to the upstream server via in-memory transport, discovers its\n * tools, and returns a new MCP server with a `code` tool that exposes\n * all upstream tools as typed methods.\n */\nexport interface CodeMcpServerOptions {\n server: McpServer;\n executor: Executor;\n /**\n * Custom tool description. Use `{{types}}` as a placeholder for the\n * auto-generated type definitions and `{{example}}` for the example snippet.\n * Falls back to a generic default when omitted.\n */\n description?: string;\n}\n\nexport async function codeMcpServer(\n options: CodeMcpServerOptions\n): Promise<McpServer> {\n const { server, executor, description } = options;\n const [clientTransport, serverTransport] =\n InMemoryTransport.createLinkedPair();\n\n await server.connect(serverTransport);\n\n const client = new Client({ name: \"codemode-proxy\", version: \"1.0.0\" });\n await client.connect(clientTransport);\n\n const { tools } = await client.listTools();\n\n // Build type hints\n const toolDescriptors: JsonSchemaToolDescriptors = {};\n for (const tool of tools) {\n toolDescriptors[tool.name] = {\n description: tool.description,\n inputSchema: tool.inputSchema as JSONSchema7\n };\n }\n const types = generateTypesFromJsonSchema(toolDescriptors);\n\n // Build executor fns — each upstream tool is a direct method.\n // Unwrap MCP content wrappers so sandbox code sees plain values,\n // consistent with how createCodeTool returns results.\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n for (const tool of tools) {\n const toolName = tool.name;\n fns[toolName] = async (args: unknown) => {\n const result = await client.callTool({\n name: toolName,\n arguments: args as Record<string, unknown>\n });\n return unwrapMcpResult(result);\n };\n }\n\n // Build example from first upstream tool with placeholder args\n const firstTool = tools[0];\n let example = \"\";\n if (firstTool) {\n const schema = firstTool.inputSchema as {\n properties?: Record<string, { type?: string; description?: string }>;\n required?: string[];\n };\n const props = schema.properties ?? {};\n const parts: string[] = [];\n for (const [key, prop] of Object.entries(props)) {\n if (prop.type === \"number\" || prop.type === \"integer\") {\n parts.push(`${key}: 0`);\n } else if (prop.type === \"boolean\") {\n parts.push(`${key}: true`);\n } else {\n parts.push(`${key}: \"...\"`);\n }\n }\n const args = parts.length > 0 ? `{ ${parts.join(\", \")} }` : \"{}\";\n example = `Example: async () => { const r = await codemode.${sanitizeToolName(firstTool.name)}(${args}); return r; }`;\n }\n\n const codeDescription = (description ?? CODE_DESCRIPTION)\n .replace(\"{{types}}\", types)\n .replace(\"{{example}}\", example);\n\n const codemodeServer = new McpServer({\n name: \"codemode\",\n version: \"1.0.0\"\n });\n\n codemodeServer.registerTool(\n \"code\",\n {\n description: codeDescription,\n inputSchema: {\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n }\n },\n async ({ code }) => {\n try {\n const result = await executor.execute(code, [\n { name: \"codemode\", fns }\n ]);\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: truncateResponse(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n return codemodeServer;\n}\n\n// -- openApiMcpServer --\n\nexport interface RequestOptions {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n contentType?: string;\n rawBody?: boolean;\n}\n\nexport interface OpenApiMcpServerOptions {\n spec: Record<string, unknown>;\n executor: Executor;\n request: (options: RequestOptions) => Promise<unknown>;\n name?: string;\n version?: string;\n description?: string;\n}\n\n/**\n * Resolve internal $ref pointers in a JSON object against the root document.\n * Only handles `#/` internal refs. External file refs are left as-is.\n */\nfunction resolveRefs(\n obj: unknown,\n root: Record<string, unknown>,\n seen = new Set<string>()\n): unknown {\n if (obj === null || obj === undefined) return obj;\n if (typeof obj !== \"object\") return obj;\n if (Array.isArray(obj))\n return obj.map((item) => resolveRefs(item, root, seen));\n\n const record = obj as Record<string, unknown>;\n\n if (\"$ref\" in record && typeof record.$ref === \"string\") {\n const ref = record.$ref;\n if (seen.has(ref)) return { $circular: ref };\n if (!ref.startsWith(\"#/\")) return record;\n seen.add(ref);\n\n const parts = ref\n .slice(2)\n .split(\"/\")\n .map((s) => s.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n let resolved: unknown = root;\n for (const part of parts) {\n resolved = (resolved as Record<string, unknown>)?.[part];\n }\n const result = resolveRefs(resolved, root, seen);\n seen.delete(ref);\n return result;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(record)) {\n result[key] = resolveRefs(value, root, seen);\n }\n return result;\n}\n\nconst SPEC_TYPES = `\n// OpenAPI 3.x spec with $refs resolved inline.\n// The spec object follows the standard OpenAPI 3.x structure.\n\ninterface OperationObject {\n summary?: string;\n description?: string;\n operationId?: string;\n tags?: string[];\n parameters?: Array<{\n name: string;\n in: \"query\" | \"header\" | \"path\" | \"cookie\";\n required?: boolean;\n schema?: unknown;\n description?: string;\n }>;\n requestBody?: {\n required?: boolean;\n description?: string;\n content?: Record<string, { schema?: unknown }>;\n };\n responses?: Record<string, {\n description?: string;\n content?: Record<string, { schema?: unknown }>;\n }>;\n security?: Array<Record<string, string[]>>;\n deprecated?: boolean;\n}\n\ninterface PathItem {\n summary?: string;\n description?: string;\n get?: OperationObject;\n post?: OperationObject;\n put?: OperationObject;\n patch?: OperationObject;\n delete?: OperationObject;\n head?: OperationObject;\n options?: OperationObject;\n trace?: OperationObject;\n parameters?: OperationObject[\"parameters\"];\n}\n\ninterface OpenApiSpec {\n openapi: string;\n info: { title: string; version: string; description?: string };\n paths: Record<string, PathItem>;\n servers?: Array<{ url: string; description?: string }>;\n components?: Record<string, unknown>;\n tags?: Array<{ name: string; description?: string }>;\n}\n\ndeclare const codemode: {\n spec(): Promise<OpenApiSpec>;\n};\n`;\n\nconst REQUEST_TYPES = `\ninterface RequestOptions {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n contentType?: string;\n rawBody?: boolean;\n}\n\ndeclare const codemode: {\n request(options: RequestOptions): Promise<unknown>;\n};\n`;\n\n/**\n * Create an MCP server with search + execute tools from an OpenAPI spec.\n *\n * The search tool lets the LLM query the spec to find endpoints.\n * The execute tool lets the LLM call the API via a user-provided\n * request function that runs on the host (auth never enters the sandbox).\n */\nexport function openApiMcpServer(options: OpenApiMcpServerOptions): McpServer {\n const {\n executor,\n request: requestFn,\n name = \"openapi\",\n version = \"1.0.0\",\n description\n } = options;\n\n const resolved = resolveRefs(options.spec, options.spec);\n\n const server = new McpServer({ name, version });\n\n // --- search tool ---\n server.registerTool(\n \"search\",\n {\n description: `Search the OpenAPI spec. All $refs are pre-resolved inline.\n\nTypes:\n${SPEC_TYPES}\n\nYour code must be an async arrow function that returns the result.\n\nExamples:\n\n// List all paths\nasync () => {\n const spec = await codemode.spec();\n return Object.keys(spec.paths);\n}\n\n// Find endpoints by tag\nasync () => {\n const spec = await codemode.spec();\n const results = [];\n for (const [path, methods] of Object.entries(spec.paths)) {\n for (const [method, op] of Object.entries(methods)) {\n if (op.tags?.some(t => t.toLowerCase() === 'your_tag')) {\n results.push({ method: method.toUpperCase(), path, summary: op.summary });\n }\n }\n }\n return results;\n}`,\n inputSchema: {\n code: z\n .string()\n .describe(\"JavaScript async arrow function to search the spec\")\n }\n },\n async ({ code }) => {\n try {\n const result = await executor.execute(code, [\n { name: \"codemode\", fns: { spec: async () => resolved } }\n ]);\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: truncateResponse(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n // --- execute tool ---\n const executeDescription = `Execute API calls using JavaScript code. First use 'search' to find the right endpoints.\n\nAvailable in your code:\n${REQUEST_TYPES}\n\nYour code must be an async arrow function that returns the result.\n\nExample:\nasync () => {\n return await codemode.request({ method: \"GET\", path: \"/your/endpoint\" });\n}${description ? `\\n\\n${description}` : \"\"}`;\n\n server.registerTool(\n \"execute\",\n {\n description: executeDescription,\n inputSchema: {\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n }\n },\n async ({ code }) => {\n try {\n const result = await executor.execute(code, [\n {\n name: \"codemode\",\n fns: {\n request: (args: unknown) => requestFn(args as RequestOptions)\n }\n }\n ]);\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: truncateResponse(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n return server;\n}\n"],"mappings":";;;;;;AAeA,MAAM,kBAAkB;AACxB,MAAM,aAAa;AACnB,MAAM,YAAY,aAAa;AAE/B,SAAS,iBAAiB,SAA0B;CAClD,MAAM,OACJ,OAAO,YAAY,WACf,UACC,KAAK,UAAU,SAAS,MAAM,EAAE,IAAI;AAE3C,KAAI,KAAK,UAAU,UACjB,QAAO;AAMT,QAAO,GAHW,KAAK,MAAM,GAAG,UAAU,CAGtB,uCAFI,KAAK,KAAK,KAAK,SAAS,gBAAgB,CAEW,gBAAgB,CAAC,kBAAkB,WAAW,gBAAgB,CAAC;;AAG5I,SAAS,YAAY,OAAwB;AAC3C,QAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;;;;;;;;;;;;;;AAiB/D,SAAS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../src/mcp.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { InMemoryTransport } from \"@modelcontextprotocol/sdk/inMemory.js\";\nimport { z } from \"zod\";\nimport {\n generateTypesFromJsonSchema,\n type JsonSchemaToolDescriptors\n} from \"./json-schema-types\";\nimport { normalizeCode } from \"./normalize\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { Executor } from \"./executor\";\n\nimport type { JSONSchema7 } from \"json-schema\";\n\n// -- Shared utilities --\n\nconst CHARS_PER_TOKEN = 4;\nconst MAX_TOKENS = 6000;\nconst MAX_CHARS = MAX_TOKENS * CHARS_PER_TOKEN;\nconst TRUNCATION_MARKER = \"--- TRUNCATED ---\";\nconst TRUNCATION_FOOTER_PREFIX = `\\n\\n${TRUNCATION_MARKER}\\nResponse was ~`;\nconst MAX_SANDBOX_TRUNCATED_CHARS = MAX_CHARS + 512;\n\nfunction truncateResponse(content: unknown): string {\n const text =\n typeof content === \"string\"\n ? content\n : (JSON.stringify(content, null, 2) ?? \"undefined\");\n\n if (text.length <= MAX_CHARS) {\n return text;\n }\n\n const truncated = text.slice(0, MAX_CHARS);\n const estimatedTokens = Math.ceil(text.length / CHARS_PER_TOKEN);\n\n return `${truncated}\\n\\n${TRUNCATION_MARKER}\\nResponse was ~${estimatedTokens.toLocaleString()} tokens (limit: ${MAX_TOKENS.toLocaleString()}). Use more specific queries to reduce response size.`;\n}\n\nfunction sandboxResponseText(content: unknown): string {\n if (\n typeof content === \"string\" &&\n content.length <= MAX_SANDBOX_TRUNCATED_CHARS &&\n content.slice(MAX_CHARS).startsWith(TRUNCATION_FOOTER_PREFIX)\n ) {\n return content;\n }\n return truncateResponse(content);\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\ntype CallToolResult = Awaited<ReturnType<Client[\"callTool\"]>>;\n\n/**\n * Unwrap an MCP CallToolResult so sandbox code sees plain values,\n * consistent with how createCodeTool exposes tool results.\n *\n * Priority:\n * 1. Compat `toolResult` → return directly\n * 2. `isError` → throw so sandbox gets a proper exception\n * 3. `structuredContent` → authoritative typed value when present\n * 4. All-text content → JSON.parse or raw string\n * 5. Mixed content (text + images/audio/resources) → return as-is,\n * since binary content has no clean plain-value representation\n */\nfunction unwrapMcpResult(result: CallToolResult): unknown {\n if (\"toolResult\" in result) {\n return result.toolResult;\n }\n\n if (result.isError) {\n const msg =\n result.content\n .filter((c) => c.type === \"text\")\n .map((c) => (\"text\" in c ? c.text : \"\"))\n .join(\"\\n\") || \"Tool call failed\";\n throw new Error(msg);\n }\n\n if (result.structuredContent != null) {\n return result.structuredContent;\n }\n\n const allText =\n result.content.length > 0 && result.content.every((c) => c.type === \"text\");\n if (allText) {\n const text = result.content\n .map((c) => (\"text\" in c ? c.text : \"\"))\n .join(\"\\n\");\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n\n return result;\n}\n\n// -- codeMcpServer --\n\nconst CODE_DESCRIPTION = `Execute code to achieve a goal.\n\nAvailable:\n{{types}}\n\nWrite an async arrow function in JavaScript that returns the result.\nDo NOT use TypeScript syntax — no type annotations, interfaces, or generics.\nDo NOT define named functions then call them — just write the arrow function body directly.\n\n{{example}}`;\n\n/**\n * Wrap an existing MCP server with a single codemode `code` tool.\n *\n * Connects to the upstream server via in-memory transport, discovers its\n * tools, and returns a new MCP server with a `code` tool that exposes\n * all upstream tools as typed methods.\n */\nexport interface CodeMcpServerOptions {\n server: McpServer;\n executor: Executor;\n /**\n * Custom tool description. Use `{{types}}` as a placeholder for the\n * auto-generated type definitions and `{{example}}` for the example snippet.\n * Falls back to a generic default when omitted.\n */\n description?: string;\n}\n\nexport async function codeMcpServer(\n options: CodeMcpServerOptions\n): Promise<McpServer> {\n const { server, executor, description } = options;\n const [clientTransport, serverTransport] =\n InMemoryTransport.createLinkedPair();\n\n await server.connect(serverTransport);\n\n const client = new Client({ name: \"codemode-proxy\", version: \"1.0.0\" });\n await client.connect(clientTransport);\n\n const { tools } = await client.listTools();\n\n // Build type hints\n const toolDescriptors: JsonSchemaToolDescriptors = {};\n for (const tool of tools) {\n toolDescriptors[tool.name] = {\n description: tool.description,\n inputSchema: tool.inputSchema as JSONSchema7\n };\n }\n const types = generateTypesFromJsonSchema(toolDescriptors);\n\n // Build executor fns — each upstream tool is a direct method.\n // Unwrap MCP content wrappers so sandbox code sees plain values,\n // consistent with how createCodeTool returns results.\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n for (const tool of tools) {\n const toolName = tool.name;\n fns[toolName] = async (args: unknown) => {\n const result = await client.callTool({\n name: toolName,\n arguments: args as Record<string, unknown>\n });\n return unwrapMcpResult(result);\n };\n }\n\n // Build example from first upstream tool with placeholder args\n const firstTool = tools[0];\n let example = \"\";\n if (firstTool) {\n const schema = firstTool.inputSchema as {\n properties?: Record<string, { type?: string; description?: string }>;\n required?: string[];\n };\n const props = schema.properties ?? {};\n const parts: string[] = [];\n for (const [key, prop] of Object.entries(props)) {\n if (prop.type === \"number\" || prop.type === \"integer\") {\n parts.push(`${key}: 0`);\n } else if (prop.type === \"boolean\") {\n parts.push(`${key}: true`);\n } else {\n parts.push(`${key}: \"...\"`);\n }\n }\n const args = parts.length > 0 ? `{ ${parts.join(\", \")} }` : \"{}\";\n example = `Example: async () => { const r = await codemode.${sanitizeToolName(firstTool.name)}(${args}); return r; }`;\n }\n\n const codeDescription = (description ?? CODE_DESCRIPTION)\n .replace(\"{{types}}\", types)\n .replace(\"{{example}}\", example);\n\n const codemodeServer = new McpServer({\n name: \"codemode\",\n version: \"1.0.0\"\n });\n\n codemodeServer.registerTool(\n \"code\",\n {\n description: codeDescription,\n inputSchema: {\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n }\n },\n async ({ code }) => {\n try {\n const result = await executor.execute(code, [\n { name: \"codemode\", fns }\n ]);\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: truncateResponse(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n return codemodeServer;\n}\n\n// -- openApiMcpServer --\n\nexport interface RequestOptions {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n contentType?: string;\n rawBody?: boolean;\n}\n\nexport interface OpenApiMcpServerOptions {\n spec: Record<string, unknown>;\n executor: Executor;\n request: (options: RequestOptions) => Promise<unknown>;\n name?: string;\n version?: string;\n description?: string;\n}\n\nconst SPEC_TYPES = `\n// OpenAPI 3.x spec with $refs resolved inline.\n// The spec object follows the standard OpenAPI 3.x structure.\n\ninterface OperationObject {\n summary?: string;\n description?: string;\n operationId?: string;\n tags?: string[];\n parameters?: Array<{\n name: string;\n in: \"query\" | \"header\" | \"path\" | \"cookie\";\n required?: boolean;\n schema?: unknown;\n description?: string;\n }>;\n requestBody?: {\n required?: boolean;\n description?: string;\n content?: Record<string, { schema?: unknown }>;\n };\n responses?: Record<string, {\n description?: string;\n content?: Record<string, { schema?: unknown }>;\n }>;\n security?: Array<Record<string, string[]>>;\n deprecated?: boolean;\n}\n\ninterface PathItem {\n summary?: string;\n description?: string;\n get?: OperationObject;\n post?: OperationObject;\n put?: OperationObject;\n patch?: OperationObject;\n delete?: OperationObject;\n head?: OperationObject;\n options?: OperationObject;\n trace?: OperationObject;\n parameters?: OperationObject[\"parameters\"];\n}\n\ninterface OpenApiSpec {\n openapi: string;\n info: { title: string; version: string; description?: string };\n paths: Record<string, PathItem>;\n servers?: Array<{ url: string; description?: string }>;\n components?: Record<string, unknown>;\n tags?: Array<{ name: string; description?: string }>;\n}\n`;\n\nconst SEARCH_TYPES = `${SPEC_TYPES}\ndeclare const codemode: {\n spec(): Promise<OpenApiSpec>;\n};\n`;\n\nconst REQUEST_TYPES = `\ninterface RequestOptions {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n contentType?: string;\n rawBody?: boolean;\n}\n\n${SPEC_TYPES}\n\ndeclare const codemode: {\n spec(): Promise<OpenApiSpec>;\n request(options: RequestOptions): Promise<unknown>;\n};\n`;\n\nfunction createOpenApiSandboxCode(\n code: string,\n spec: Record<string, unknown>,\n includeRequest: boolean\n): string {\n const normalized = normalizeCode(code);\n const specJson = JSON.stringify(spec).replace(/</g, \"\\\\u003c\");\n const requestFn = includeRequest\n ? `request: async (options) => await __openapiHost.request(options)`\n : \"\";\n\n return `async () => {\nconst __rawSpec = ${specJson};\nconst __refCache = new Map();\nconst __cloneResolvedRef = (value) => structuredClone(value);\nconst __resolveRefs = (obj, root, seen = new Set()) => {\n if (obj === null || obj === undefined) return obj;\n if (typeof obj !== \"object\") return obj;\n if (Array.isArray(obj)) return obj.map((item) => __resolveRefs(item, root, seen));\n\n if (Object.prototype.hasOwnProperty.call(obj, \"$ref\") && typeof obj.$ref === \"string\") {\n const ref = obj.$ref;\n if (seen.has(ref)) return { $circular: ref };\n if (!ref.startsWith(\"#/\")) return obj;\n if (__refCache.has(ref)) return __cloneResolvedRef(__refCache.get(ref));\n seen.add(ref);\n\n const parts = ref\n .slice(2)\n .split(\"/\")\n .map((s) => s.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n let resolved = root;\n for (const part of parts) resolved = resolved?.[part];\n const result = __resolveRefs(resolved, root, seen);\n seen.delete(ref);\n __refCache.set(ref, result);\n return __cloneResolvedRef(result);\n }\n\n const result = {};\n for (const [key, value] of Object.entries(obj)) result[key] = __resolveRefs(value, root, seen);\n return result;\n};\nlet __resolvedSpec;\nconst __truncateResponse = (content) => {\n const text = typeof content === \"string\" ? content : (JSON.stringify(content, null, 2) ?? \"undefined\");\n if (text.length <= ${MAX_CHARS}) return text;\n const truncated = text.slice(0, ${MAX_CHARS});\n const estimatedTokens = Math.ceil(text.length / ${CHARS_PER_TOKEN});\n return truncated + \"\\\\n\\\\n${TRUNCATION_MARKER}\\\\nResponse was ~\" + estimatedTokens.toLocaleString() + \" tokens (limit: ${MAX_TOKENS.toLocaleString()}). Use more specific queries to reduce response size.\";\n};\nconst codemode = {\n spec: async () => (__resolvedSpec ??= __resolveRefs(__rawSpec, __rawSpec))${requestFn ? `,\\n ${requestFn}` : \"\"}\n};\nreturn __truncateResponse(await (${normalized})());\n}`;\n}\n\n/**\n * Create an MCP server with search + execute tools from an OpenAPI spec.\n *\n * The search tool lets the LLM query the spec to find endpoints.\n * The execute tool lets the LLM call the API via a user-provided\n * request function that runs on the host (auth never enters the sandbox).\n */\nexport function openApiMcpServer(options: OpenApiMcpServerOptions): McpServer {\n const {\n executor,\n request: requestFn,\n name = \"openapi\",\n version = \"1.0.0\",\n description\n } = options;\n\n const spec = options.spec;\n\n const server = new McpServer({ name, version });\n\n // --- search tool ---\n server.registerTool(\n \"search\",\n {\n description: `Search the OpenAPI spec. codemode.spec() returns $refs resolved inline.\n\nTypes:\n${SEARCH_TYPES}\n\nYour code must be an async arrow function that returns the result.\n\nExamples:\n\n// List all paths\nasync () => {\n const spec = await codemode.spec();\n return Object.keys(spec.paths);\n}\n\n// Find endpoints by tag\nasync () => {\n const spec = await codemode.spec();\n const results = [];\n for (const [path, methods] of Object.entries(spec.paths)) {\n for (const [method, op] of Object.entries(methods)) {\n if (op.tags?.some(t => t.toLowerCase() === 'your_tag')) {\n results.push({ method: method.toUpperCase(), path, summary: op.summary });\n }\n }\n }\n return results;\n}`,\n inputSchema: {\n code: z\n .string()\n .describe(\"JavaScript async arrow function to search the spec\")\n }\n },\n async ({ code }) => {\n try {\n const result = await executor.execute(\n createOpenApiSandboxCode(code, spec, false),\n []\n );\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: sandboxResponseText(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n // --- execute tool ---\n const executeDescription = `Execute API calls using JavaScript code. First use 'search' to find the right endpoints.\n\nAvailable in your code:\n${REQUEST_TYPES}\n\nYour code must be an async arrow function that returns the result.\n\nExample:\nasync () => {\n return await codemode.request({ method: \"GET\", path: \"/your/endpoint\" });\n}${description ? `\\n\\n${description}` : \"\"}`;\n\n server.registerTool(\n \"execute\",\n {\n description: executeDescription,\n inputSchema: {\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n }\n },\n async ({ code }) => {\n try {\n const result = await executor.execute(\n createOpenApiSandboxCode(code, spec, true),\n [\n {\n name: \"__openapiHost\",\n fns: {\n request: (args: unknown) => requestFn(args as RequestOptions)\n }\n }\n ]\n );\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: sandboxResponseText(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n return server;\n}\n"],"mappings":";;;;;;AAgBA,MAAM,kBAAkB;AACxB,MAAM,aAAa;AACnB,MAAM,YAAY,aAAa;AAC/B,MAAM,oBAAoB;AAC1B,MAAM,2BAA2B,OAAO,kBAAkB;AAC1D,MAAM,8BAA8B,YAAY;AAEhD,SAAS,iBAAiB,SAA0B;CAClD,MAAM,OACJ,OAAO,YAAY,WACf,UACC,KAAK,UAAU,SAAS,MAAM,EAAE,IAAI;CAE3C,IAAI,KAAK,UAAU,WACjB,OAAO;CAMT,OAAO,GAHW,KAAK,MAAM,GAAG,UAGb,CAAC,MAAM,kBAAkB,kBAFpB,KAAK,KAAK,KAAK,SAAS,gBAE6B,CAAC,gBAAgB,CAAC,kBAAkB,WAAW,gBAAgB,CAAC;;A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S,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,OAAO;KAAS,CAC1D;IACD,SAAS;IACV;GAEH,OAAO,EACL,SAAS,CACP;IAAE,MAAM;IAAiB,MAAM,oBAAoB,OAAO,OAAO;IAAE,CACpE,EACF;WACM,OAAO;GACd,OAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,YAAY,MAAM;KAAI,CAChE;IACD,SAAS;IACV;;GAGN;CAGD,MAAM,qBAAqB;;;EAG3B,cAAc;;;;;;;GAOb,cAAc,OAAO,gBAAgB;CAEtC,OAAO,aACL,WACA;EACE,aAAa;EACb,aAAa,EACX,MAAM,EAAE,QAAQ,CAAC,SAAS,6CAA6C,EACxE;EACF,EACD,OAAO,EAAE,WAAW;EAClB,IAAI;GACF,MAAM,SAAS,MAAM,SAAS,QAC5B,yBAAyB,MAAM,MAAM,KAAK,EAC1C,CACE;IACE,MAAM;IACN,KAAK,EACH,UAAU,SAAkB,UAAU,KAAuB,EAC9D;IACF,CACF,CACF;GACD,IAAI,OAAO,OACT,OAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,OAAO;KAAS,CAC1D;IACD,SAAS;IACV;GAEH,OAAO,EACL,SAAS,CACP;IAAE,MAAM;IAAiB,MAAM,oBAAoB,OAAO,OAAO;IAAE,CACpE,EACF;WACM,OAAO;GACd,OAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,YAAY,MAAM;KAAI,CAChE;IACD,SAAS;IACV;;GAGN;CAED,OAAO"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
//#region src/resolve.ts
|
|
2
|
+
function hasNeedsApproval(t) {
|
|
3
|
+
return t.needsApproval === true || typeof t.needsApproval === "function";
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Filter out tools with needsApproval and return a clean copy.
|
|
7
|
+
*/
|
|
8
|
+
function filterTools(tools) {
|
|
9
|
+
const filtered = {};
|
|
10
|
+
for (const [name, t] of Object.entries(tools)) if (!hasNeedsApproval(t)) filtered[name] = t;
|
|
11
|
+
return filtered;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Extract execute functions from tools, keyed by name.
|
|
15
|
+
* This is the base version — no schema validation.
|
|
16
|
+
* The AI SDK entry point overrides this with `asSchema`-based validation.
|
|
17
|
+
*/
|
|
18
|
+
function extractFns(tools) {
|
|
19
|
+
const fns = {};
|
|
20
|
+
for (const [name, t] of Object.entries(tools)) {
|
|
21
|
+
const execute = "execute" in t ? t.execute : void 0;
|
|
22
|
+
if (execute) fns[name] = execute;
|
|
23
|
+
}
|
|
24
|
+
return fns;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Resolve a ToolProvider into a ResolvedProvider ready for execution.
|
|
28
|
+
* Filters out tools with `needsApproval`.
|
|
29
|
+
*
|
|
30
|
+
* This version does NOT perform schema validation on inputs.
|
|
31
|
+
* Import from `@cloudflare/codemode/ai` for the schema-validating version.
|
|
32
|
+
*/
|
|
33
|
+
function resolveProvider(provider) {
|
|
34
|
+
const resolved = {
|
|
35
|
+
name: provider.name ?? "codemode",
|
|
36
|
+
fns: extractFns(filterTools(provider.tools))
|
|
37
|
+
};
|
|
38
|
+
if (provider.positionalArgs) resolved.positionalArgs = true;
|
|
39
|
+
return resolved;
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
export { filterTools as n, resolveProvider as r, extractFns as t };
|
|
43
|
+
|
|
44
|
+
//# sourceMappingURL=resolve-BU1FGVYs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolve-BU1FGVYs.js","names":[],"sources":["../src/resolve.ts"],"sourcesContent":["/**\n * Framework-agnostic tool resolution.\n *\n * Extracts execute functions from tool records and resolves ToolProviders\n * into ResolvedProviders — no dependency on the AI SDK or Zod.\n *\n * The AI SDK entry point (`./ai`) layers on schema validation via `asSchema`.\n */\n\nimport type {\n ToolProvider,\n ToolProviderTools,\n ResolvedProvider\n} from \"./executor\";\n\nfunction hasNeedsApproval(t: Record<string, unknown>): boolean {\n return t.needsApproval === true || typeof t.needsApproval === \"function\";\n}\n\n/**\n * Filter out tools with needsApproval and return a clean copy.\n */\nexport function filterTools(tools: ToolProviderTools): ToolProviderTools {\n const filtered: Record<string, unknown> = {};\n for (const [name, t] of Object.entries(tools)) {\n if (!hasNeedsApproval(t as Record<string, unknown>)) {\n filtered[name] = t;\n }\n }\n return filtered as ToolProviderTools;\n}\n\n/**\n * Extract execute functions from tools, keyed by name.\n * This is the base version — no schema validation.\n * The AI SDK entry point overrides this with `asSchema`-based validation.\n */\nexport function extractFns(\n tools: ToolProviderTools\n): Record<string, (...args: unknown[]) => Promise<unknown>> {\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n\n for (const [name, t] of Object.entries(tools)) {\n const execute =\n \"execute\" in t\n ? (t.execute as (args: unknown) => Promise<unknown>)\n : undefined;\n if (execute) {\n fns[name] = execute;\n }\n }\n\n return fns;\n}\n\n/**\n * Resolve a ToolProvider into a ResolvedProvider ready for execution.\n * Filters out tools with `needsApproval`.\n *\n * This version does NOT perform schema validation on inputs.\n * Import from `@cloudflare/codemode/ai` for the schema-validating version.\n */\nexport function resolveProvider(provider: ToolProvider): ResolvedProvider {\n const name = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n const resolved: ResolvedProvider = { name, fns: extractFns(filtered) };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n return resolved;\n}\n"],"mappings":";AAeA,SAAS,iBAAiB,GAAqC;CAC7D,OAAO,EAAE,kBAAkB,QAAQ,OAAO,EAAE,kBAAkB;;;;;AAMhE,SAAgB,YAAY,OAA6C;CACvE,MAAM,WAAoC,EAAE;CAC5C,KAAK,MAAM,CAAC,MAAM,MAAM,OAAO,QAAQ,MAAM,EAC3C,IAAI,CAAC,iBAAiB,EAA6B,EACjD,SAAS,QAAQ;CAGrB,OAAO;;;;;;;AAQT,SAAgB,WACd,OAC0D;CAC1D,MAAM,MAAgE,EAAE;CAExE,KAAK,MAAM,CAAC,MAAM,MAAM,OAAO,QAAQ,MAAM,EAAE;EAC7C,MAAM,UACJ,aAAa,IACR,EAAE,UACH,KAAA;EACN,IAAI,SACF,IAAI,QAAQ;;CAIhB,OAAO;;;;;;;;;AAUT,SAAgB,gBAAgB,UAA0C;CAGxE,MAAM,WAA6B;EAAE,MAFxB,SAAS,QAAQ;EAEa,KAAK,WAD/B,YAAY,SAAS,MAC6B,CAAC;EAAE;CACtE,IAAI,SAAS,gBAAgB,SAAS,iBAAiB;CACvD,OAAO"}
|
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
s as ToolProvider
|
|
4
|
-
} from "./executor-wZjYdqEX.js";
|
|
1
|
+
import { i as ToolProvider } from "./executor-C-DgAHLS.js";
|
|
2
|
+
import { r as ResolvedProvider } from "./executor-types-CJ06IBzw.js";
|
|
5
3
|
|
|
6
4
|
//#region src/resolve.d.ts
|
|
7
5
|
/**
|
|
@@ -14,4 +12,4 @@ import {
|
|
|
14
12
|
declare function resolveProvider(provider: ToolProvider): ResolvedProvider;
|
|
15
13
|
//#endregion
|
|
16
14
|
export { resolveProvider as t };
|
|
17
|
-
//# sourceMappingURL=resolve-
|
|
15
|
+
//# sourceMappingURL=resolve-E1SKV37h.d.ts.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
i as
|
|
4
|
-
|
|
5
|
-
} from "./executor-
|
|
2
|
+
a as ToolProviderTools,
|
|
3
|
+
i as ToolProvider
|
|
4
|
+
} from "./executor-C-DgAHLS.js";
|
|
5
|
+
import { n as Executor } from "./executor-types-CJ06IBzw.js";
|
|
6
6
|
|
|
7
7
|
//#region src/shared.d.ts
|
|
8
8
|
declare const DEFAULT_DESCRIPTION =
|
|
@@ -38,4 +38,4 @@ export {
|
|
|
38
38
|
CreateCodeToolOptions as r,
|
|
39
39
|
CodeInput as t
|
|
40
40
|
};
|
|
41
|
-
//# sourceMappingURL=shared-
|
|
41
|
+
//# sourceMappingURL=shared-C3CDOc8T.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shared-ra3HW2ti.js","names":[],"sources":["../src/shared.ts"],"sourcesContent":["/**\n * Shared constants and types used by both the AI SDK (`./ai`) and\n * TanStack AI (`./tanstack-ai`) entry points.\n *\n * No dependency on `ai`, `@tanstack/ai`, or `zod`.\n */\n\nimport type { Executor, ToolProvider, ToolProviderTools } from \"./executor\";\n\nexport const DEFAULT_DESCRIPTION = `Execute code to achieve a goal.\n\nAvailable:\n{{types}}\n\nWrite an async arrow function in JavaScript that returns the result.\nDo NOT use TypeScript syntax — no type annotations, interfaces, or generics.\nDo NOT define named functions then call them — just write the arrow function body directly.\n\nExample: async () => { const r = await codemode.searchWeb({ query: \"test\" }); return r; }`;\n\nexport interface CreateCodeToolOptions {\n tools: ToolProviderTools | ToolProvider[];\n executor: Executor;\n /**\n * Custom tool description. Use {{types}} as a placeholder for the generated type definitions.\n */\n description?: string;\n}\n\nexport type CodeInput = { code: string };\nexport type CodeOutput = { code: string; result: unknown; logs?: string[] };\n\n/**\n * Check if the tools option is an array of ToolProviders.\n * A plain ToolSet/ToolDescriptors is a Record (not an array).\n */\nfunction isToolProviderArray(\n tools: ToolProviderTools | ToolProvider[]\n): tools is ToolProvider[] {\n return Array.isArray(tools);\n}\n\n/**\n * Normalize the tools option into a list of ToolProviders.\n * Raw ToolSet/ToolDescriptors are wrapped as a single default provider.\n */\nexport function normalizeProviders(\n tools: ToolProviderTools | ToolProvider[]\n): ToolProvider[] {\n if (isToolProviderArray(tools)) {\n return tools;\n }\n return [{ tools }];\n}\n"],"mappings":";AASA,MAAa,sBAAsB;;;;;;;;;;;;;;AA2BnC,SAAS,oBACP,OACyB;
|
|
1
|
+
{"version":3,"file":"shared-ra3HW2ti.js","names":[],"sources":["../src/shared.ts"],"sourcesContent":["/**\n * Shared constants and types used by both the AI SDK (`./ai`) and\n * TanStack AI (`./tanstack-ai`) entry points.\n *\n * No dependency on `ai`, `@tanstack/ai`, or `zod`.\n */\n\nimport type { Executor, ToolProvider, ToolProviderTools } from \"./executor\";\n\nexport const DEFAULT_DESCRIPTION = `Execute code to achieve a goal.\n\nAvailable:\n{{types}}\n\nWrite an async arrow function in JavaScript that returns the result.\nDo NOT use TypeScript syntax — no type annotations, interfaces, or generics.\nDo NOT define named functions then call them — just write the arrow function body directly.\n\nExample: async () => { const r = await codemode.searchWeb({ query: \"test\" }); return r; }`;\n\nexport interface CreateCodeToolOptions {\n tools: ToolProviderTools | ToolProvider[];\n executor: Executor;\n /**\n * Custom tool description. Use {{types}} as a placeholder for the generated type definitions.\n */\n description?: string;\n}\n\nexport type CodeInput = { code: string };\nexport type CodeOutput = { code: string; result: unknown; logs?: string[] };\n\n/**\n * Check if the tools option is an array of ToolProviders.\n * A plain ToolSet/ToolDescriptors is a Record (not an array).\n */\nfunction isToolProviderArray(\n tools: ToolProviderTools | ToolProvider[]\n): tools is ToolProvider[] {\n return Array.isArray(tools);\n}\n\n/**\n * Normalize the tools option into a list of ToolProviders.\n * Raw ToolSet/ToolDescriptors are wrapped as a single default provider.\n */\nexport function normalizeProviders(\n tools: ToolProviderTools | ToolProvider[]\n): ToolProvider[] {\n if (isToolProviderArray(tools)) {\n return tools;\n }\n return [{ tools }];\n}\n"],"mappings":";AASA,MAAa,sBAAsB;;;;;;;;;;;;;;AA2BnC,SAAS,oBACP,OACyB;CACzB,OAAO,MAAM,QAAQ,MAAM;;;;;;AAO7B,SAAgB,mBACd,OACgB;CAChB,IAAI,oBAAoB,MAAM,EAC5B,OAAO;CAET,OAAO,CAAC,EAAE,OAAO,CAAC"}
|
package/dist/tanstack-ai.d.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { i as ToolProvider } from "./executor-C-DgAHLS.js";
|
|
2
2
|
import {
|
|
3
3
|
a as normalizeProviders,
|
|
4
4
|
i as DEFAULT_DESCRIPTION,
|
|
5
5
|
n as CodeOutput,
|
|
6
6
|
r as CreateCodeToolOptions,
|
|
7
7
|
t as CodeInput
|
|
8
|
-
} from "./shared-
|
|
9
|
-
import { t as resolveProvider } from "./resolve-
|
|
8
|
+
} from "./shared-C3CDOc8T.js";
|
|
9
|
+
import { t as resolveProvider } from "./resolve-E1SKV37h.js";
|
|
10
10
|
import { ServerTool, Tool } from "@tanstack/ai";
|
|
11
11
|
|
|
12
12
|
//#region src/tanstack-ai.d.ts
|
package/dist/tanstack-ai.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { i as
|
|
2
|
-
import {
|
|
1
|
+
import { a as sanitizeToolName, i as escapeJsDoc, n as jsonSchemaToType, o as toPascalCase, s as normalizeCode } from "./json-schema-types-CVt4X9cw.js";
|
|
2
|
+
import { n as filterTools, r as resolveProvider, t as extractFns } from "./resolve-BU1FGVYs.js";
|
|
3
3
|
import { n as normalizeProviders, t as DEFAULT_DESCRIPTION } from "./shared-ra3HW2ti.js";
|
|
4
4
|
import { z } from "zod";
|
|
5
5
|
import { convertSchemaToJsonSchema, toolDefinition } from "@tanstack/ai";
|
|
@@ -106,7 +106,7 @@ ${availableTools}
|
|
|
106
106
|
* ```
|
|
107
107
|
*/
|
|
108
108
|
function tanstackTools(tools, name) {
|
|
109
|
-
const filtered = tools.filter((t) =>
|
|
109
|
+
const filtered = tools.filter((t) => t.needsApproval !== true && typeof t.needsApproval !== "function");
|
|
110
110
|
const toolRecord = {};
|
|
111
111
|
for (const tool of filtered) if (tool.execute) toolRecord[tool.name] = {
|
|
112
112
|
description: tool.description,
|
package/dist/tanstack-ai.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tanstack-ai.js","names":[],"sources":["../src/tanstack-ai.ts"],"sourcesContent":["/**\n * TanStack AI integration for codemode.\n *\n * Provides the same capabilities as `@cloudflare/codemode/ai` but returns\n * TanStack AI-compatible tools for use with `chat()` from `@tanstack/ai`.\n *\n * @example\n * ```ts\n * import { createCodeTool, tanstackTools } from \"@cloudflare/codemode/tanstack-ai\";\n * import { chat } from \"@tanstack/ai\";\n *\n * const codeTool = createCodeTool({\n * tools: [tanstackTools(myServerTools)],\n * executor,\n * });\n *\n * const stream = chat({\n * adapter: openaiText(\"gpt-4o\"),\n * tools: [codeTool],\n * messages,\n * });\n * ```\n */\n\nimport { toolDefinition, convertSchemaToJsonSchema } from \"@tanstack/ai\";\nimport type {\n Tool as TanStackTool,\n ServerTool,\n JSONSchema as TanStackJSONSchema\n} from \"@tanstack/ai\";\nimport { z } from \"zod\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport type {\n ToolProvider,\n ToolProviderTools,\n ResolvedProvider,\n SimpleToolRecord\n} from \"./executor\";\nimport { normalizeCode } from \"./normalize\";\nimport { filterTools, extractFns } from \"./resolve\";\nimport {\n DEFAULT_DESCRIPTION,\n type CreateCodeToolOptions,\n type CodeOutput,\n normalizeProviders\n} from \"./shared\";\nimport { jsonSchemaToType } from \"./json-schema-types\";\nimport { sanitizeToolName, toPascalCase, escapeJsDoc } from \"./utils\";\n\nexport type { CreateCodeToolOptions, CodeInput, CodeOutput } from \"./shared\";\nexport { DEFAULT_DESCRIPTION, normalizeProviders } from \"./shared\";\nexport { resolveProvider } from \"./resolve\";\n\nconst codeSchema = z.object({\n code: z\n .string()\n .meta({ description: \"JavaScript async arrow function to execute\" })\n});\n\n/**\n * Convert a TanStack AI schema (StandardJSONSchema or plain JSONSchema) to\n * a JSON Schema 7 object usable by the core type generator.\n */\nfunction toJsonSchema7(schema: unknown): JSONSchema7 | null {\n const converted = convertSchemaToJsonSchema(schema as TanStackJSONSchema);\n if (!converted) return null;\n return converted as unknown as JSONSchema7;\n}\n\n/**\n * Generate TypeScript type definitions from an array of TanStack AI tools.\n *\n * Uses the tools' schemas (Zod, ArkType, JSON Schema, etc.) to produce type\n * declarations that the LLM sees in the code-tool description.\n */\nexport function generateTypes(\n tools: TanStackTool[],\n namespace = \"codemode\"\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const tool of tools) {\n const safeName = sanitizeToolName(tool.name);\n const typeName = toPascalCase(safeName);\n\n try {\n const inputJsonSchema = tool.inputSchema\n ? toJsonSchema7(tool.inputSchema)\n : null;\n const outputJsonSchema = tool.outputSchema\n ? toJsonSchema7(tool.outputSchema)\n : null;\n\n const inputType = inputJsonSchema\n ? jsonSchemaToType(inputJsonSchema, `${typeName}Input`)\n : `type ${typeName}Input = unknown`;\n\n const outputType = outputJsonSchema\n ? jsonSchemaToType(outputJsonSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramDescs = (() => {\n try {\n if (!inputJsonSchema?.properties) return [];\n return Object.entries(inputJsonSchema.properties)\n .filter(\n ([, propSchema]) =>\n propSchema &&\n typeof propSchema === \"object\" &&\n (propSchema as JSONSchema7).description\n )\n .map(\n ([fieldName, propSchema]) =>\n `@param input.${fieldName} - ${(propSchema as JSONSchema7).description}`\n );\n } catch {\n return [];\n }\n })();\n\n const jsdocLines: string[] = [];\n if (tool.description?.trim()) {\n jsdocLines.push(\n escapeJsDoc(tool.description.trim().replace(/\\r?\\n/g, \" \"))\n );\n } else {\n jsdocLines.push(escapeJsDoc(tool.name));\n }\n for (const pd of paramDescs) {\n jsdocLines.push(escapeJsDoc(pd.replace(/\\r?\\n/g, \" \")));\n }\n\n const jsdocBody = jsdocLines.map((l) => `\\t * ${l}`).join(\"\\n\");\n availableTools += `\\n\\t/**\\n${jsdocBody}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n } catch {\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n availableTools += `\\n\\t/**\\n\\t * ${escapeJsDoc(tool.name)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n\n/**\n * Wrap TanStack AI tools into a ToolProvider for use with `createCodeTool`.\n *\n * Converts the array-based TanStack tool format into the record-based\n * ToolProvider that the codemode executor expects.\n *\n * @example\n * ```ts\n * import { createCodeTool, tanstackTools } from \"@cloudflare/codemode/tanstack-ai\";\n *\n * const codeTool = createCodeTool({\n * tools: [\n * tanstackTools(myServerTools),\n * tanstackTools(otherTools, \"other\"),\n * ],\n * executor,\n * });\n * ```\n */\nexport function tanstackTools(\n tools: TanStackTool[],\n name?: string\n): ToolProvider {\n const filtered = tools.filter(\n (t) => !(\"needsApproval\" in t && t.needsApproval != null)\n );\n\n const toolRecord: SimpleToolRecord = {};\n for (const tool of filtered) {\n if (tool.execute) {\n toolRecord[tool.name] = {\n description: tool.description,\n execute: async (args: unknown) => tool.execute!(args)\n };\n }\n }\n\n const ns = name ?? \"codemode\";\n const types = generateTypes(filtered, ns);\n\n return { name: ns === \"codemode\" ? undefined : ns, tools: toolRecord, types };\n}\n\n/**\n * Create a codemode tool that allows LLMs to write and execute code\n * with access to your tools in a sandboxed environment.\n *\n * Returns a TanStack AI `ServerTool` compatible with `chat()` from `@tanstack/ai`.\n *\n * @example Basic usage\n * ```ts\n * const codeTool = createCodeTool({\n * tools: [tanstackTools(myTools)],\n * executor,\n * });\n *\n * const stream = chat({\n * adapter: openaiText(\"gpt-4o\"),\n * tools: [codeTool],\n * messages,\n * });\n * ```\n *\n * @example Multiple namespaces\n * ```ts\n * createCodeTool({\n * tools: [\n * tanstackTools(githubTools, \"github\"),\n * tanstackTools(dbTools, \"db\"),\n * ],\n * executor,\n * });\n * ```\n */\nexport function createCodeTool(options: CreateCodeToolOptions): ServerTool {\n const providers = normalizeProviders(options.tools);\n\n const typeBlocks: string[] = [];\n const resolvedProviders: ResolvedProvider[] = [];\n\n for (const provider of providers) {\n const providerName = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n\n const types =\n provider.types ?? generateTypesFromRecord(filtered, providerName);\n typeBlocks.push(types);\n\n const resolved: ResolvedProvider = {\n name: providerName,\n fns: extractFns(filtered)\n };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n resolvedProviders.push(resolved);\n }\n\n const typeBlock = typeBlocks.filter(Boolean).join(\"\\n\\n\");\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n typeBlock\n );\n\n const def = toolDefinition({\n name: \"codemode_execute\" as const,\n description,\n inputSchema: codeSchema\n });\n\n return def.server(async ({ code }) => {\n const normalizedCode = normalizeCode(code);\n\n const executeResult = await executor.execute(\n normalizedCode,\n resolvedProviders\n );\n\n if (executeResult.error) {\n const logCtx = executeResult.logs?.length\n ? `\\n\\nConsole output:\\n${executeResult.logs.join(\"\\n\")}`\n : \"\";\n throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`);\n }\n\n const output: CodeOutput = { code, result: executeResult.result };\n if (executeResult.logs) output.logs = executeResult.logs;\n return output;\n });\n}\n\n/**\n * Generate types from a ToolProviderTools record.\n * Falls back to the JSON Schema generator for SimpleToolRecord.\n */\nfunction generateTypesFromRecord(\n tools: ToolProviderTools,\n namespace: string\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const typeName = toPascalCase(safeName);\n const description =\n \"description\" in tool\n ? (tool as Record<string, unknown>).description\n : undefined;\n\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n const descStr =\n typeof description === \"string\" && description.trim()\n ? escapeJsDoc(description.trim().replace(/\\r?\\n/g, \" \"))\n : escapeJsDoc(toolName);\n\n availableTools += `\\n\\t/**\\n\\t * ${descStr}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,MAAM,aAAa,EAAE,OAAO,EAC1B,MAAM,EACH,QAAQ,CACR,KAAK,EAAE,aAAa,8CAA8C,CAAC,EACvE,CAAC;;;;;AAMF,SAAS,cAAc,QAAqC;CAC1D,MAAM,YAAY,0BAA0B,OAA6B;AACzE,KAAI,CAAC,UAAW,QAAO;AACvB,QAAO;;;;;;;;AAST,SAAgB,cACd,OACA,YAAY,YACJ;CACR,IAAI,iBAAiB;CACrB,IAAI,iBAAiB;AAErB,MAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,WAAW,iBAAiB,KAAK,KAAK;EAC5C,MAAM,WAAW,aAAa,SAAS;AAEvC,MAAI;GACF,MAAM,kBAAkB,KAAK,cACzB,cAAc,KAAK,YAAY,GAC/B;GACJ,MAAM,mBAAmB,KAAK,eAC1B,cAAc,KAAK,aAAa,GAChC;GAEJ,MAAM,YAAY,kBACd,iBAAiB,iBAAiB,GAAG,SAAS,OAAO,GACrD,QAAQ,SAAS;GAErB,MAAM,aAAa,mBACf,iBAAiB,kBAAkB,GAAG,SAAS,QAAQ,GACvD,QAAQ,SAAS;AAErB,qBAAkB,KAAK,UAAU,MAAM;AACvC,qBAAkB,KAAK,WAAW,MAAM;GAExC,MAAM,oBAAoB;AACxB,QAAI;AACF,SAAI,CAAC,iBAAiB,WAAY,QAAO,EAAE;AAC3C,YAAO,OAAO,QAAQ,gBAAgB,WAAW,CAC9C,QACE,GAAG,gBACF,cACA,OAAO,eAAe,YACrB,WAA2B,YAC/B,CACA,KACE,CAAC,WAAW,gBACX,gBAAgB,UAAU,KAAM,WAA2B,cAC9D;YACG;AACN,YAAO,EAAE;;OAET;G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O,gBAAgB,YAAY,YAAY,MAAM,GACjD,YAAY,YAAY,MAAM,CAAC,QAAQ,UAAU,IAAI,CAAC,GACtD,YAAY,SAAS;AAE3B,oBAAkB,iBAAiB,QAAQ;AAC3C,oBAAkB,OAAO,SAAS,YAAY,SAAS,oBAAoB,SAAS;AACpF,oBAAkB;;AAGpB,kBAAiB,mBAAmB,UAAU,KAAK,eAAe;AAElE,QAAO;EACP,eAAe;EACf,eAAe;IACb,MAAM"}
|
|
1
|
+
{"version":3,"file":"tanstack-ai.js","names":[],"sources":["../src/tanstack-ai.ts"],"sourcesContent":["/**\n * TanStack AI integration for codemode.\n *\n * Provides the same capabilities as `@cloudflare/codemode/ai` but returns\n * TanStack AI-compatible tools for use with `chat()` from `@tanstack/ai`.\n *\n * @example\n * ```ts\n * import { createCodeTool, tanstackTools } from \"@cloudflare/codemode/tanstack-ai\";\n * import { chat } from \"@tanstack/ai\";\n *\n * const codeTool = createCodeTool({\n * tools: [tanstackTools(myServerTools)],\n * executor,\n * });\n *\n * const stream = chat({\n * adapter: openaiText(\"gpt-4o\"),\n * tools: [codeTool],\n * messages,\n * });\n * ```\n */\n\nimport { toolDefinition, convertSchemaToJsonSchema } from \"@tanstack/ai\";\nimport type {\n Tool as TanStackTool,\n ServerTool,\n JSONSchema as TanStackJSONSchema\n} from \"@tanstack/ai\";\nimport { z } from \"zod\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport type {\n ToolProvider,\n ToolProviderTools,\n ResolvedProvider,\n SimpleToolRecord\n} from \"./executor\";\nimport { normalizeCode } from \"./normalize\";\nimport { filterTools, extractFns } from \"./resolve\";\nimport {\n DEFAULT_DESCRIPTION,\n type CreateCodeToolOptions,\n type CodeOutput,\n normalizeProviders\n} from \"./shared\";\nimport { jsonSchemaToType } from \"./json-schema-types\";\nimport { sanitizeToolName, toPascalCase, escapeJsDoc } from \"./utils\";\n\nexport type { CreateCodeToolOptions, CodeInput, CodeOutput } from \"./shared\";\nexport { DEFAULT_DESCRIPTION, normalizeProviders } from \"./shared\";\nexport { resolveProvider } from \"./resolve\";\n\nconst codeSchema = z.object({\n code: z\n .string()\n .meta({ description: \"JavaScript async arrow function to execute\" })\n});\n\n/**\n * Convert a TanStack AI schema (StandardJSONSchema or plain JSONSchema) to\n * a JSON Schema 7 object usable by the core type generator.\n */\nfunction toJsonSchema7(schema: unknown): JSONSchema7 | null {\n const converted = convertSchemaToJsonSchema(schema as TanStackJSONSchema);\n if (!converted) return null;\n return converted as unknown as JSONSchema7;\n}\n\n/**\n * Generate TypeScript type definitions from an array of TanStack AI tools.\n *\n * Uses the tools' schemas (Zod, ArkType, JSON Schema, etc.) to produce type\n * declarations that the LLM sees in the code-tool description.\n */\nexport function generateTypes(\n tools: TanStackTool[],\n namespace = \"codemode\"\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const tool of tools) {\n const safeName = sanitizeToolName(tool.name);\n const typeName = toPascalCase(safeName);\n\n try {\n const inputJsonSchema = tool.inputSchema\n ? toJsonSchema7(tool.inputSchema)\n : null;\n const outputJsonSchema = tool.outputSchema\n ? toJsonSchema7(tool.outputSchema)\n : null;\n\n const inputType = inputJsonSchema\n ? jsonSchemaToType(inputJsonSchema, `${typeName}Input`)\n : `type ${typeName}Input = unknown`;\n\n const outputType = outputJsonSchema\n ? jsonSchemaToType(outputJsonSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramDescs = (() => {\n try {\n if (!inputJsonSchema?.properties) return [];\n return Object.entries(inputJsonSchema.properties)\n .filter(\n ([, propSchema]) =>\n propSchema &&\n typeof propSchema === \"object\" &&\n (propSchema as JSONSchema7).description\n )\n .map(\n ([fieldName, propSchema]) =>\n `@param input.${fieldName} - ${(propSchema as JSONSchema7).description}`\n );\n } catch {\n return [];\n }\n })();\n\n const jsdocLines: string[] = [];\n if (tool.description?.trim()) {\n jsdocLines.push(\n escapeJsDoc(tool.description.trim().replace(/\\r?\\n/g, \" \"))\n );\n } else {\n jsdocLines.push(escapeJsDoc(tool.name));\n }\n for (const pd of paramDescs) {\n jsdocLines.push(escapeJsDoc(pd.replace(/\\r?\\n/g, \" \")));\n }\n\n const jsdocBody = jsdocLines.map((l) => `\\t * ${l}`).join(\"\\n\");\n availableTools += `\\n\\t/**\\n${jsdocBody}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n } catch {\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n availableTools += `\\n\\t/**\\n\\t * ${escapeJsDoc(tool.name)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n\n/**\n * Wrap TanStack AI tools into a ToolProvider for use with `createCodeTool`.\n *\n * Converts the array-based TanStack tool format into the record-based\n * ToolProvider that the codemode executor expects.\n *\n * @example\n * ```ts\n * import { createCodeTool, tanstackTools } from \"@cloudflare/codemode/tanstack-ai\";\n *\n * const codeTool = createCodeTool({\n * tools: [\n * tanstackTools(myServerTools),\n * tanstackTools(otherTools, \"other\"),\n * ],\n * executor,\n * });\n * ```\n */\nexport function tanstackTools(\n tools: TanStackTool[],\n name?: string\n): ToolProvider {\n const filtered = tools.filter(\n (t) => t.needsApproval !== true && typeof t.needsApproval !== \"function\"\n );\n\n const toolRecord: SimpleToolRecord = {};\n for (const tool of filtered) {\n if (tool.execute) {\n toolRecord[tool.name] = {\n description: tool.description,\n execute: async (args: unknown) => tool.execute!(args)\n };\n }\n }\n\n const ns = name ?? \"codemode\";\n const types = generateTypes(filtered, ns);\n\n return { name: ns === \"codemode\" ? undefined : ns, tools: toolRecord, types };\n}\n\n/**\n * Create a codemode tool that allows LLMs to write and execute code\n * with access to your tools in a sandboxed environment.\n *\n * Returns a TanStack AI `ServerTool` compatible with `chat()` from `@tanstack/ai`.\n *\n * @example Basic usage\n * ```ts\n * const codeTool = createCodeTool({\n * tools: [tanstackTools(myTools)],\n * executor,\n * });\n *\n * const stream = chat({\n * adapter: openaiText(\"gpt-4o\"),\n * tools: [codeTool],\n * messages,\n * });\n * ```\n *\n * @example Multiple namespaces\n * ```ts\n * createCodeTool({\n * tools: [\n * tanstackTools(githubTools, \"github\"),\n * tanstackTools(dbTools, \"db\"),\n * ],\n * executor,\n * });\n * ```\n */\nexport function createCodeTool(options: CreateCodeToolOptions): ServerTool {\n const providers = normalizeProviders(options.tools);\n\n const typeBlocks: string[] = [];\n const resolvedProviders: ResolvedProvider[] = [];\n\n for (const provider of providers) {\n const providerName = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n\n const types =\n provider.types ?? generateTypesFromRecord(filtered, providerName);\n typeBlocks.push(types);\n\n const resolved: ResolvedProvider = {\n name: providerName,\n fns: extractFns(filtered)\n };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n resolvedProviders.push(resolved);\n }\n\n const typeBlock = typeBlocks.filter(Boolean).join(\"\\n\\n\");\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n typeBlock\n );\n\n const def = toolDefinition({\n name: \"codemode_execute\" as const,\n description,\n inputSchema: codeSchema\n });\n\n return def.server(async ({ code }) => {\n const normalizedCode = normalizeCode(code);\n\n const executeResult = await executor.execute(\n normalizedCode,\n resolvedProviders\n );\n\n if (executeResult.error) {\n const logCtx = executeResult.logs?.length\n ? `\\n\\nConsole output:\\n${executeResult.logs.join(\"\\n\")}`\n : \"\";\n throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`);\n }\n\n const output: CodeOutput = { code, result: executeResult.result };\n if (executeResult.logs) output.logs = executeResult.logs;\n return output;\n });\n}\n\n/**\n * Generate types from a ToolProviderTools record.\n * Falls back to the JSON Schema generator for SimpleToolRecord.\n */\nfunction generateTypesFromRecord(\n tools: ToolProviderTools,\n namespace: string\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const typeName = toPascalCase(safeName);\n const description =\n \"description\" in tool\n ? (tool as Record<string, unknown>).description\n : undefined;\n\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n const descStr =\n typeof description === \"string\" && description.trim()\n ? escapeJsDoc(description.trim().replace(/\\r?\\n/g, \" \"))\n : escapeJsDoc(toolName);\n\n availableTools += `\\n\\t/**\\n\\t * ${descStr}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,MAAM,aAAa,EAAE,OAAO,EAC1B,MAAM,EACH,QAAQ,CACR,KAAK,EAAE,aAAa,8CAA8C,CAAC,EACvE,CAAC;;;;;AAMF,SAAS,cAAc,QAAqC;CAC1D,MAAM,YAAY,0BAA0B,OAA6B;CACzE,IAAI,CAAC,WAAW,OAAO;CACvB,OAAO;;;;;;;;AAST,SAAgB,cACd,OACA,YAAY,YACJ;CACR,IAAI,iBAAiB;CACrB,IAAI,iBAAiB;CAErB,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,WAAW,iBAAiB,KAAK,KAAK;EAC5C,MAAM,WAAW,aAAa,SAAS;EAEvC,IAAI;GACF,MAAM,kBAAkB,KAAK,cACzB,cAAc,KAAK,YAAY,GAC/B;GACJ,MAAM,mBAAmB,KAAK,eAC1B,cAAc,KAAK,aAAa,GAChC;GAEJ,MAAM,YAAY,kBACd,iBAAiB,iBA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AA0B,cAAc,QAAQ,SAAS;;EAG3E,MAAM,SAAqB;GAAE;GAAM,QAAQ,cAAc;GAAQ;EACjE,IAAI,cAAc,MAAM,OAAO,OAAO,cAAc;EACpD,OAAO;GACP;;;;;;AAOJ,SAAS,wBACP,OACA,WACQ;CACR,IAAI,iBAAiB;CACrB,IAAI,iBAAiB;CAErB,KAAK,MAAM,CAAC,UAAU,SAAS,OAAO,QAAQ,MAAM,EAAE;EACpD,MAAM,WAAW,iBAAiB,SAAS;EAC3C,MAAM,WAAW,aAAa,SAAS;EACvC,MAAM,cACJ,iBAAiB,OACZ,KAAiC,cAClC,KAAA;EAEN,kBAAkB,UAAU,SAAS;EACrC,kBAAkB,UAAU,SAAS;EAErC,MAAM,UACJ,OAAO,gBAAgB,YAAY,YAAY,MAAM,GACjD,YAAY,YAAY,MAAM,CAAC,QAAQ,UAAU,IAAI,CAAC,GACtD,YAAY,SAAS;EAE3B,kBAAkB,iBAAiB,QAAQ;EAC3C,kBAAkB,OAAO,SAAS,YAAY,SAAS,oBAAoB,SAAS;EACpF,kBAAkB;;CAGpB,iBAAiB,mBAAmB,UAAU,KAAK,eAAe;CAElE,OAAO;EACP,eAAe;EACf,eAAe;IACb,MAAM"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cloudflare/codemode",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.5",
|
|
4
4
|
"description": "Code Mode: use LLMs to generate executable code that performs tool calls",
|
|
5
5
|
"repository": {
|
|
6
6
|
"directory": "packages/codemode",
|
|
@@ -16,11 +16,11 @@
|
|
|
16
16
|
},
|
|
17
17
|
"devDependencies": {
|
|
18
18
|
"@modelcontextprotocol/sdk": "1.29.0",
|
|
19
|
-
"@playwright/test": "^1.
|
|
20
|
-
"@tanstack/ai": "^0.
|
|
21
|
-
"ai": "^6.0.
|
|
22
|
-
"vitest": "4.1.
|
|
23
|
-
"zod": "^4.3
|
|
19
|
+
"@playwright/test": "^1.60.0",
|
|
20
|
+
"@tanstack/ai": "^0.16.0",
|
|
21
|
+
"ai": "^6.0.180",
|
|
22
|
+
"vitest": "4.1.6",
|
|
23
|
+
"zod": "^4.4.3"
|
|
24
24
|
},
|
|
25
25
|
"peerDependencies": {
|
|
26
26
|
"@modelcontextprotocol/sdk": "^1.25.0",
|
|
@@ -63,13 +63,19 @@
|
|
|
63
63
|
"types": "./dist/tanstack-ai.d.ts",
|
|
64
64
|
"import": "./dist/tanstack-ai.js",
|
|
65
65
|
"require": "./dist/tanstack-ai.js"
|
|
66
|
+
},
|
|
67
|
+
"./browser": {
|
|
68
|
+
"types": "./dist/browser.d.ts",
|
|
69
|
+
"import": "./dist/browser.js",
|
|
70
|
+
"require": "./dist/browser.js"
|
|
66
71
|
}
|
|
67
72
|
},
|
|
68
73
|
"scripts": {
|
|
69
74
|
"build": "tsx ./scripts/build.ts",
|
|
70
|
-
"test": "vitest run",
|
|
75
|
+
"test": "vitest run && vitest run --config vitest.browser.config.ts",
|
|
71
76
|
"test:e2e": "npx playwright test --config e2e/playwright.config.ts",
|
|
72
|
-
"test:watch": "vitest"
|
|
77
|
+
"test:watch": "vitest",
|
|
78
|
+
"test:browser": "vitest run --config vitest.browser.config.ts"
|
|
73
79
|
},
|
|
74
80
|
"keywords": [
|
|
75
81
|
"cloudflare",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"json-schema-types-DoQ0VISs.js","names":[],"sources":["../src/utils.ts","../src/json-schema-types.ts"],"sourcesContent":["const JS_RESERVED = new Set([\n \"abstract\",\n \"arguments\",\n \"await\",\n \"boolean\",\n \"break\",\n \"byte\",\n \"case\",\n \"catch\",\n \"char\",\n \"class\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"delete\",\n \"do\",\n \"double\",\n \"else\",\n \"enum\",\n \"eval\",\n \"export\",\n \"extends\",\n \"false\",\n \"final\",\n \"finally\",\n \"float\",\n \"for\",\n \"function\",\n \"goto\",\n \"if\",\n \"implements\",\n \"import\",\n \"in\",\n \"instanceof\",\n \"int\",\n \"interface\",\n \"let\",\n \"long\",\n \"native\",\n \"new\",\n \"null\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"return\",\n \"short\",\n \"static\",\n \"super\",\n \"switch\",\n \"synchronized\",\n \"this\",\n \"throw\",\n \"throws\",\n \"transient\",\n \"true\",\n \"try\",\n \"typeof\",\n \"undefined\",\n \"var\",\n \"void\",\n \"volatile\",\n \"while\",\n \"with\",\n \"yield\"\n]);\n\n/**\n * Sanitize a tool name into a valid JavaScript identifier.\n * Replaces hyphens, dots, and spaces with `_`, strips other invalid chars,\n * prefixes digit-leading names with `_`, and appends `_` to JS reserved words.\n */\nexport function sanitizeToolName(name: string): string {\n if (!name) return \"_\";\n\n // Replace common separators with underscores\n let sanitized = name.replace(/[-.\\s]/g, \"_\");\n\n // Strip any remaining non-identifier characters\n sanitized = sanitized.replace(/[^a-zA-Z0-9_$]/g, \"\");\n\n if (!sanitized) return \"_\";\n\n // Prefix with _ if starts with a digit\n if (/^[0-9]/.test(sanitized)) {\n sanitized = \"_\" + sanitized;\n }\n\n // Append _ to reserved words\n if (JS_RESERVED.has(sanitized)) {\n sanitized = sanitized + \"_\";\n }\n\n return sanitized;\n}\n\nexport function toPascalCase(str: string) {\n return str\n .replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())\n .replace(/^[a-z]/, (letter) => letter.toUpperCase());\n}\n\n/**\n * Escape a character as a unicode escape sequence if it is a control character.\n */\nfunction escapeControlChar(ch: string): string {\n const code = ch.charCodeAt(0);\n if (code <= 0x1f || code === 0x7f) {\n return \"\\\\u\" + code.toString(16).padStart(4, \"0\");\n }\n return ch;\n}\n\n/**\n * Quote a property name if needed.\n * Escapes backslashes, quotes, and control characters.\n */\nexport function quoteProp(name: string): string {\n if (!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)) {\n let escaped = \"\";\n for (const ch of name) {\n if (ch === \"\\\\\") escaped += \"\\\\\\\\\";\n else if (ch === '\"') escaped += '\\\\\"';\n else if (ch === \"\\n\") escaped += \"\\\\n\";\n else if (ch === \"\\r\") escaped += \"\\\\r\";\n else if (ch === \"\\t\") escaped += \"\\\\t\";\n else if (ch === \"\\u2028\") escaped += \"\\\\u2028\";\n else if (ch === \"\\u2029\") escaped += \"\\\\u2029\";\n else escaped += escapeControlChar(ch);\n }\n return `\"${escaped}\"`;\n }\n return name;\n}\n\n/**\n * Escape a string for use inside a double-quoted TypeScript string literal.\n */\nexport function escapeStringLiteral(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (ch === \"\\\\\") out += \"\\\\\\\\\";\n else if (ch === '\"') out += '\\\\\"';\n else if (ch === \"\\n\") out += \"\\\\n\";\n else if (ch === \"\\r\") out += \"\\\\r\";\n else if (ch === \"\\t\") out += \"\\\\t\";\n else if (ch === \"\\u2028\") out += \"\\\\u2028\";\n else if (ch === \"\\u2029\") out += \"\\\\u2029\";\n else out += escapeControlChar(ch);\n }\n return out;\n}\n\n/**\n * Escape a string for use inside a JSDoc comment.\n * Prevents premature comment closure from star-slash sequences.\n */\nexport function escapeJsDoc(text: string): string {\n return text.replace(/\\*\\//g, \"*\\\\/\");\n}\n","import type { JSONSchema7, JSONSchema7Definition } from \"json-schema\";\nimport {\n sanitizeToolName,\n toPascalCase,\n escapeJsDoc,\n escapeStringLiteral,\n quoteProp\n} from \"./utils\";\n\nexport interface ConversionContext {\n root: JSONSchema7;\n depth: number;\n seen: Set<unknown>;\n maxDepth: number;\n}\n\n/**\n * Resolve an internal JSON Pointer $ref (e.g. #/definitions/Foo) against the root schema.\n * Returns null for external URLs or unresolvable paths.\n */\nfunction resolveRef(\n ref: string,\n root: JSONSchema7\n): JSONSchema7Definition | null {\n // \"#\" is a valid self-reference to the root schema\n if (ref === \"#\") return root;\n\n if (!ref.startsWith(\"#/\")) return null;\n\n const segments = ref\n .slice(2)\n .split(\"/\")\n .map((s) => s.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n\n let current: unknown = root;\n for (const seg of segments) {\n if (current === null || typeof current !== \"object\") return null;\n current = (current as Record<string, unknown>)[seg];\n if (current === undefined) return null;\n }\n\n // Allow both object schemas and boolean schemas (true = any, false = never)\n if (typeof current === \"boolean\") return current;\n if (current === null || typeof current !== \"object\") return null;\n return current as JSONSchema7;\n}\n\n/**\n * Apply OpenAPI 3.0 `nullable: true` to a type result.\n */\nfunction applyNullable(result: string, schema: unknown): string {\n if (\n result !== \"unknown\" &&\n result !== \"never\" &&\n (schema as Record<string, unknown>)?.nullable === true\n ) {\n return `${result} | null`;\n }\n return result;\n}\n\n/**\n * Convert a JSON Schema to a TypeScript type string.\n * This is a direct conversion without going through Zod.\n */\nexport function jsonSchemaToTypeString(\n schema: JSONSchema7Definition,\n indent: string,\n ctx: ConversionContext\n): string {\n // Handle boolean schemas\n if (typeof schema === \"boolean\") {\n return schema ? \"unknown\" : \"never\";\n }\n\n // Depth guard\n if (ctx.depth >= ctx.maxDepth) return \"unknown\";\n\n // Circular reference guard\n if (ctx.seen.has(schema)) return \"unknown\";\n\n ctx.seen.add(schema);\n const nextCtx: ConversionContext = {\n ...ctx,\n depth: ctx.depth + 1\n };\n\n try {\n // Handle $ref\n if (schema.$ref) {\n const resolved = resolveRef(schema.$ref, ctx.root);\n if (!resolved) return \"unknown\";\n return applyNullable(\n jsonSchemaToTypeString(resolved, indent, nextCtx),\n schema\n );\n }\n\n // Handle anyOf/oneOf (union types)\n if (schema.anyOf) {\n const types = schema.anyOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" | \"), schema);\n }\n if (schema.oneOf) {\n const types = schema.oneOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" | \"), schema);\n }\n\n // Handle allOf (intersection types)\n if (schema.allOf) {\n const types = schema.allOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" & \"), schema);\n }\n\n // Handle enum\n if (schema.enum) {\n if (schema.enum.length === 0) return \"never\";\n const result = schema.enum\n .map((v) => {\n if (v === null) return \"null\";\n if (typeof v === \"string\") return '\"' + escapeStringLiteral(v) + '\"';\n if (typeof v === \"object\") return JSON.stringify(v) ?? \"unknown\";\n return String(v);\n })\n .join(\" | \");\n return applyNullable(result, schema);\n }\n\n // Handle const\n if (schema.const !== undefined) {\n const result =\n schema.const === null\n ? \"null\"\n : typeof schema.const === \"string\"\n ? '\"' + escapeStringLiteral(schema.const) + '\"'\n : typeof schema.const === \"object\"\n ? (JSON.stringify(schema.const) ?? \"unknown\")\n : String(schema.const);\n return applyNullable(result, schema);\n }\n\n // Handle type\n const type = schema.type;\n\n if (type === \"string\") return applyNullable(\"string\", schema);\n if (type === \"number\" || type === \"integer\")\n return applyNullable(\"number\", schema);\n if (type === \"boolean\") return applyNullable(\"boolean\", schema);\n if (type === \"null\") return \"null\";\n\n if (type === \"array\") {\n // Tuple support: prefixItems (JSON Schema 2020-12)\n const prefixItems = (schema as Record<string, unknown>)\n .prefixItems as JSONSchema7Definition[];\n if (Array.isArray(prefixItems)) {\n const types = prefixItems.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(`[${types.join(\", \")}]`, schema);\n }\n\n // Tuple support: items as array (draft-07)\n if (Array.isArray(schema.items)) {\n const types = schema.items.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(`[${types.join(\", \")}]`, schema);\n }\n\n if (schema.items) {\n const itemType = jsonSchemaToTypeString(schema.items, indent, nextCtx);\n return applyNullable(`${itemType}[]`, schema);\n }\n return applyNullable(\"unknown[]\", schema);\n }\n\n if (type === \"object\" || schema.properties) {\n const props = schema.properties || {};\n const required = new Set(schema.required || []);\n const lines: string[] = [];\n\n for (const [propName, propSchema] of Object.entries(props)) {\n if (typeof propSchema === \"boolean\") {\n const boolType = propSchema ? \"unknown\" : \"never\";\n const optionalMark = required.has(propName) ? \"\" : \"?\";\n lines.push(\n `${indent} ${quoteProp(propName)}${optionalMark}: ${boolType};`\n );\n continue;\n }\n\n const isRequired = required.has(propName);\n const propType = jsonSchemaToTypeString(\n propSchema,\n indent + \" \",\n nextCtx\n );\n const desc = propSchema.description;\n const format = propSchema.format;\n\n if (desc || format) {\n const descText = desc\n ? escapeJsDoc(desc.replace(/\\r?\\n/g, \" \"))\n : undefined;\n const formatTag = format\n ? `@format ${escapeJsDoc(format)}`\n : undefined;\n\n if (descText && formatTag) {\n lines.push(`${indent} /**`);\n lines.push(`${indent} * ${descText}`);\n lines.push(`${indent} * ${formatTag}`);\n lines.push(`${indent} */`);\n } else {\n lines.push(`${indent} /** ${descText ?? formatTag} */`);\n }\n }\n\n const quotedName = quoteProp(propName);\n const optionalMark = isRequired ? \"\" : \"?\";\n lines.push(`${indent} ${quotedName}${optionalMark}: ${propType};`);\n }\n\n // Handle additionalProperties\n if (schema.additionalProperties) {\n const valueType =\n schema.additionalProperties === true\n ? \"unknown\"\n : jsonSchemaToTypeString(\n schema.additionalProperties,\n indent + \" \",\n nextCtx\n );\n lines.push(`${indent} [key: string]: ${valueType};`);\n }\n\n if (lines.length === 0) {\n if (schema.additionalProperties === false) {\n return applyNullable(\"{}\", schema);\n }\n return applyNullable(\"Record<string, unknown>\", schema);\n }\n\n const result = `{\\n${lines.join(\"\\n\")}\\n${indent}}`;\n return applyNullable(result, schema);\n }\n\n // Handle array of types (e.g., [\"string\", \"null\"])\n if (Array.isArray(type)) {\n const types = type.map((t) => {\n if (t === \"string\") return \"string\";\n if (t === \"number\" || t === \"integer\") return \"number\";\n if (t === \"boolean\") return \"boolean\";\n if (t === \"null\") return \"null\";\n if (t === \"array\") return \"unknown[]\";\n if (t === \"object\") return \"Record<string, unknown>\";\n return \"unknown\";\n });\n return applyNullable(types.join(\" | \"), schema);\n }\n\n return \"unknown\";\n } finally {\n ctx.seen.delete(schema);\n }\n}\n\n/**\n * Convert a JSON Schema to a TypeScript type declaration.\n */\nexport function jsonSchemaToType(\n schema: JSONSchema7,\n typeName: string\n): string {\n const ctx: ConversionContext = {\n root: schema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(schema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n}\n\n/**\n * Extract field descriptions from a JSON Schema's properties.\n */\nfunction extractJsonSchemaDescriptions(\n schema: JSONSchema7\n): Record<string, string> {\n const descriptions: Record<string, string> = {};\n if (schema.properties) {\n for (const [fieldName, propSchema] of Object.entries(schema.properties)) {\n if (\n propSchema &&\n typeof propSchema === \"object\" &&\n propSchema.description\n ) {\n descriptions[fieldName] = propSchema.description;\n }\n }\n }\n return descriptions;\n}\n\n/**\n * A tool descriptor using plain JSON Schema (no Zod or AI SDK dependency).\n */\nexport interface JsonSchemaToolDescriptor {\n description?: string;\n inputSchema: JSONSchema7;\n outputSchema?: JSONSchema7;\n}\n\nexport type JsonSchemaToolDescriptors = Record<\n string,\n JsonSchemaToolDescriptor\n>;\n\n/**\n * Generate TypeScript type definitions from tool descriptors with JSON Schema.\n * This function has NO dependency on the AI SDK or Zod — it works purely with\n * JSON Schema objects.\n *\n * Use this when you have raw JSON Schema (e.g. from OpenAPI specs, MCP tool\n * definitions, etc.) and don't need the AI SDK.\n */\nexport function generateTypesFromJsonSchema(\n tools: JsonSchemaToolDescriptors\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const typeName = toPascalCase(safeName);\n\n try {\n const inputType = jsonSchemaToType(tool.inputSchema, `${typeName}Input`);\n\n const outputType = tool.outputSchema\n ? jsonSchemaToType(tool.outputSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramLines = (() => {\n try {\n const paramDescs = extractJsonSchemaDescriptions(tool.inputSchema);\n return Object.entries(paramDescs).map(\n ([fieldName, desc]) => `@param input.${fieldName} - ${desc}`\n );\n } catch {\n return [];\n }\n })();\n const jsdocLines: string[] = [];\n if (tool.description?.trim()) {\n jsdocLines.push(\n escapeJsDoc(tool.description.trim().replace(/\\r?\\n/g, \" \"))\n );\n } else {\n jsdocLines.push(escapeJsDoc(toolName));\n }\n for (const pd of paramLines) {\n jsdocLines.push(escapeJsDoc(pd.replace(/\\r?\\n/g, \" \")));\n }\n\n const jsdocBody = jsdocLines.map((l) => `\\t * ${l}`).join(\"\\n\");\n availableTools += `\\n\\t/**\\n${jsdocBody}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n } catch {\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n availableTools += `\\n\\t/**\\n\\t * ${escapeJsDoc(toolName)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const codemode: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n"],"mappings":";AAAA,MAAM,cAAc,IAAI,IAAI;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;;;;;;AAOF,SAAgB,iBAAiB,MAAsB;AACrD,KAAI,CAAC,KAAM,QAAO;CAGlB,IAAI,YAAY,KAAK,QAAQ,WAAW,IAAI;AAG5C,aAAY,UAA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|
-
import * as acorn from "acorn";
|
|
2
|
-
//#region src/normalize.ts
|
|
3
|
-
/**
|
|
4
|
-
* Strip markdown code fences that LLMs commonly wrap code in.
|
|
5
|
-
* Handles ```js, ```javascript, ```typescript, ```ts, or bare ```.
|
|
6
|
-
*/
|
|
7
|
-
function stripCodeFences(code) {
|
|
8
|
-
const match = code.match(/^```(?:js|javascript|typescript|ts|tsx|jsx)?\s*\n([\s\S]*?)```\s*$/);
|
|
9
|
-
return match ? match[1] : code;
|
|
10
|
-
}
|
|
11
|
-
function normalizeCode(code) {
|
|
12
|
-
const trimmed = stripCodeFences(code.trim());
|
|
13
|
-
if (!trimmed.trim()) return "async () => {}";
|
|
14
|
-
const source = trimmed.trim();
|
|
15
|
-
try {
|
|
16
|
-
const ast = acorn.parse(source, {
|
|
17
|
-
ecmaVersion: "latest",
|
|
18
|
-
sourceType: "module"
|
|
19
|
-
});
|
|
20
|
-
if (ast.body.length === 1 && ast.body[0].type === "ExpressionStatement") {
|
|
21
|
-
if (ast.body[0].expression.type === "ArrowFunctionExpression") return source;
|
|
22
|
-
}
|
|
23
|
-
if (ast.body.length === 1 && ast.body[0].type === "ExportDefaultDeclaration") {
|
|
24
|
-
const decl = ast.body[0].declaration;
|
|
25
|
-
const inner = source.slice(decl.start, decl.end);
|
|
26
|
-
if (decl.type === "FunctionDeclaration" && !decl.id) return `async () => {\nreturn (${inner})();\n}`;
|
|
27
|
-
if (decl.type === "ClassDeclaration" && !decl.id) return `async () => {\nreturn (${inner});\n}`;
|
|
28
|
-
return normalizeCode(inner);
|
|
29
|
-
}
|
|
30
|
-
if (ast.body.length === 1 && ast.body[0].type === "FunctionDeclaration") return `async () => {\n${source}\nreturn ${ast.body[0].id?.name ?? "fn"}();\n}`;
|
|
31
|
-
const last = ast.body[ast.body.length - 1];
|
|
32
|
-
if (last?.type === "ExpressionStatement") {
|
|
33
|
-
const exprStmt = last;
|
|
34
|
-
return `async () => {\n${source.slice(0, last.start)}return (${source.slice(exprStmt.expression.start, exprStmt.expression.end)})\n}`;
|
|
35
|
-
}
|
|
36
|
-
return `async () => {\n${source}\n}`;
|
|
37
|
-
} catch {
|
|
38
|
-
return `async () => {\n${source}\n}`;
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
//#endregion
|
|
42
|
-
//#region src/resolve.ts
|
|
43
|
-
function hasNeedsApproval(t) {
|
|
44
|
-
return "needsApproval" in t && t.needsApproval != null;
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* Filter out tools with needsApproval and return a clean copy.
|
|
48
|
-
*/
|
|
49
|
-
function filterTools(tools) {
|
|
50
|
-
const filtered = {};
|
|
51
|
-
for (const [name, t] of Object.entries(tools)) if (!hasNeedsApproval(t)) filtered[name] = t;
|
|
52
|
-
return filtered;
|
|
53
|
-
}
|
|
54
|
-
/**
|
|
55
|
-
* Extract execute functions from tools, keyed by name.
|
|
56
|
-
* This is the base version — no schema validation.
|
|
57
|
-
* The AI SDK entry point overrides this with `asSchema`-based validation.
|
|
58
|
-
*/
|
|
59
|
-
function extractFns(tools) {
|
|
60
|
-
const fns = {};
|
|
61
|
-
for (const [name, t] of Object.entries(tools)) {
|
|
62
|
-
const execute = "execute" in t ? t.execute : void 0;
|
|
63
|
-
if (execute) fns[name] = execute;
|
|
64
|
-
}
|
|
65
|
-
return fns;
|
|
66
|
-
}
|
|
67
|
-
/**
|
|
68
|
-
* Resolve a ToolProvider into a ResolvedProvider ready for execution.
|
|
69
|
-
* Filters out tools with `needsApproval`.
|
|
70
|
-
*
|
|
71
|
-
* This version does NOT perform schema validation on inputs.
|
|
72
|
-
* Import from `@cloudflare/codemode/ai` for the schema-validating version.
|
|
73
|
-
*/
|
|
74
|
-
function resolveProvider(provider) {
|
|
75
|
-
const resolved = {
|
|
76
|
-
name: provider.name ?? "codemode",
|
|
77
|
-
fns: extractFns(filterTools(provider.tools))
|
|
78
|
-
};
|
|
79
|
-
if (provider.positionalArgs) resolved.positionalArgs = true;
|
|
80
|
-
return resolved;
|
|
81
|
-
}
|
|
82
|
-
//#endregion
|
|
83
|
-
export { normalizeCode as i, filterTools as n, resolveProvider as r, extractFns as t };
|
|
84
|
-
|
|
85
|
-
//# sourceMappingURL=resolve-DIQRkRqQ.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"resolve-DIQRkRqQ.js","names":[],"sources":["../src/normalize.ts","../src/resolve.ts"],"sourcesContent":["import * as acorn from \"acorn\";\n\n/**\n * Strip markdown code fences that LLMs commonly wrap code in.\n * Handles ```js, ```javascript, ```typescript, ```ts, or bare ```.\n */\nfunction stripCodeFences(code: string): string {\n const fenced =\n /^```(?:js|javascript|typescript|ts|tsx|jsx)?\\s*\\n([\\s\\S]*?)```\\s*$/;\n const match = code.match(fenced);\n return match ? match[1] : code;\n}\n\nexport function normalizeCode(code: string): string {\n const trimmed = stripCodeFences(code.trim());\n if (!trimmed.trim()) return \"async () => {}\";\n\n const source = trimmed.trim();\n\n try {\n const ast = acorn.parse(source, {\n ecmaVersion: \"latest\",\n sourceType: \"module\"\n });\n\n // Already an arrow function — pass through\n if (ast.body.length === 1 && ast.body[0].type === \"ExpressionStatement\") {\n const expr = (ast.body[0] as acorn.ExpressionStatement).expression;\n if (expr.type === \"ArrowFunctionExpression\") return source;\n }\n\n // export default <expression> → unwrap to just the expression\n if (\n ast.body.length === 1 &&\n ast.body[0].type === \"ExportDefaultDeclaration\"\n ) {\n const decl = (ast.body[0] as acorn.ExportDefaultDeclaration).declaration;\n const inner = source.slice(decl.start, decl.end);\n\n // Anonymous function/class declarations aren't valid as standalone\n // statements — wrap them as expressions directly.\n if (\n decl.type === \"FunctionDeclaration\" &&\n !(decl as acorn.FunctionDeclaration).id\n ) {\n return `async () => {\\nreturn (${inner})();\\n}`;\n }\n if (\n decl.type === \"ClassDeclaration\" &&\n !(decl as acorn.ClassDeclaration).id\n ) {\n return `async () => {\\nreturn (${inner});\\n}`;\n }\n\n return normalizeCode(inner);\n }\n\n // Single named function declaration → wrap and call it\n if (ast.body.length === 1 && ast.body[0].type === \"FunctionDeclaration\") {\n const fn = ast.body[0] as acorn.FunctionDeclaration;\n const name = fn.id?.name ?? \"fn\";\n return `async () => {\\n${source}\\nreturn ${name}();\\n}`;\n }\n\n // Last statement is expression → splice in return\n const last = ast.body[ast.body.length - 1];\n if (last?.type === \"ExpressionStatement\") {\n const exprStmt = last as acorn.ExpressionStatement;\n const before = source.slice(0, last.start);\n const exprText = source.slice(\n exprStmt.expression.start,\n exprStmt.expression.end\n );\n return `async () => {\\n${before}return (${exprText})\\n}`;\n }\n\n return `async () => {\\n${source}\\n}`;\n } catch {\n return `async () => {\\n${source}\\n}`;\n }\n}\n","/**\n * Framework-agnostic tool resolution.\n *\n * Extracts execute functions from tool records and resolves ToolProviders\n * into ResolvedProviders — no dependency on the AI SDK or Zod.\n *\n * The AI SDK entry point (`./ai`) layers on schema validation via `asSchema`.\n */\n\nimport type {\n ToolProvider,\n ToolProviderTools,\n ResolvedProvider\n} from \"./executor\";\n\nfunction hasNeedsApproval(t: Record<string, unknown>): boolean {\n return \"needsApproval\" in t && t.needsApproval != null;\n}\n\n/**\n * Filter out tools with needsApproval and return a clean copy.\n */\nexport function filterTools(tools: ToolProviderTools): ToolProviderTools {\n const filtered: Record<string, unknown> = {};\n for (const [name, t] of Object.entries(tools)) {\n if (!hasNeedsApproval(t as Record<string, unknown>)) {\n filtered[name] = t;\n }\n }\n return filtered as ToolProviderTools;\n}\n\n/**\n * Extract execute functions from tools, keyed by name.\n * This is the base version — no schema validation.\n * The AI SDK entry point overrides this with `asSchema`-based validation.\n */\nexport function extractFns(\n tools: ToolProviderTools\n): Record<string, (...args: unknown[]) => Promise<unknown>> {\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n\n for (const [name, t] of Object.entries(tools)) {\n const execute =\n \"execute\" in t\n ? (t.execute as (args: unknown) => Promise<unknown>)\n : undefined;\n if (execute) {\n fns[name] = execute;\n }\n }\n\n return fns;\n}\n\n/**\n * Resolve a ToolProvider into a ResolvedProvider ready for execution.\n * Filters out tools with `needsApproval`.\n *\n * This version does NOT perform schema validation on inputs.\n * Import from `@cloudflare/codemode/ai` for the schema-validating version.\n */\nexport function resolveProvider(provider: ToolProvider): ResolvedProvider {\n const name = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n const resolved: ResolvedProvider = { name, fns: extractFns(filtered) };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n return resolved;\n}\n"],"mappings":";;;;;;AAMA,SAAS,gBAAgB,MAAsB;CAG7C,MAAM,QAAQ,KAAK,MADjB,qEAC8B;AAChC,QAAO,QAAQ,MAAM,KAAK;;AAG5B,SAAgB,cAAc,MAAsB;CAClD,MAAM,UAAU,gBAAgB,KAAK,MAAM,CAAC;AAC5C,KAAI,CAAC,QAAQ,MAAM,CAAE,QAAO;CAE5B,MAAM,SAAS,QAAQ,MAAM;AAE7B,KAAI;EACF,MAAM,MAAM,MAAM,MAAM,QAAQ;GAC9B,aAAa;GACb,YAAY;GACb,CAAC;AAGF,MAAI,IAAI,KAAK,WAAW,KAAK,IAAI,KAAK,GAAG,SAAS;OAClC,IAAI,KAAK,GAAiC,WAC/C,SAAS,0BAA2B,QAAO;;AAItD,MACE,IAAI,KAAK,WAAW,KACpB,IAAI,KAAK,GAAG,SAAS,4BACrB;GACA,MAAM,OAAQ,IAAI,KAAK,GAAsC;GAC7D,MAAM,QAAQ,OAAO,MAAM,KAAK,OAAO,KAAK,IAAI;AAIhD,OACE,KAAK,SAAS,yBACd,CAAE,KAAmC,GAErC,QAAO,0BAA0B,MAAM;AAEzC,OACE,KAAK,SAAS,sBACd,CAAE,KAAgC,GAElC,QAAO,0BAA0B,MAAM;AAGzC,UAAO,cAAc,MAAM;;AAI7B,MAAI,IAAI,KAAK,WAAW,KAAK,IAAI,KAAK,GAAG,SAAS,sBAGhD,QAAO,kBAAkB,OAAO,WAFrB,IAAI,KAAK,GACJ,IAAI,QAAQ,KACoB;EAIlD,MAAM,OAAO,IA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