@cloudflare/codemode 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.js ADDED
@@ -0,0 +1,314 @@
1
+ import { a as sanitizeToolName, t as generateTypesFromJsonSchema } from "./json-schema-types-DoQ0VISs.js";
2
+ import { z } from "zod";
3
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
5
+ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
6
+ //#region src/mcp.ts
7
+ const CHARS_PER_TOKEN = 4;
8
+ const MAX_TOKENS = 6e3;
9
+ const MAX_CHARS = MAX_TOKENS * CHARS_PER_TOKEN;
10
+ function truncateResponse(content) {
11
+ const text = typeof content === "string" ? content : JSON.stringify(content, null, 2) ?? "undefined";
12
+ if (text.length <= MAX_CHARS) return text;
13
+ return `${text.slice(0, MAX_CHARS)}\n\n--- TRUNCATED ---\nResponse was ~${Math.ceil(text.length / CHARS_PER_TOKEN).toLocaleString()} tokens (limit: ${MAX_TOKENS.toLocaleString()}). Use more specific queries to reduce response size.`;
14
+ }
15
+ function formatError(error) {
16
+ return error instanceof Error ? error.message : String(error);
17
+ }
18
+ const CODE_DESCRIPTION = `Execute code to achieve a goal.
19
+
20
+ Available:
21
+ {{types}}
22
+
23
+ Write an async arrow function in JavaScript that returns the result.
24
+ Do NOT use TypeScript syntax — no type annotations, interfaces, or generics.
25
+ Do NOT define named functions then call them — just write the arrow function body directly.
26
+
27
+ {{example}}`;
28
+ async function codeMcpServer(options) {
29
+ const { server, executor } = options;
30
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
31
+ await server.connect(serverTransport);
32
+ const client = new Client({
33
+ name: "codemode-proxy",
34
+ version: "1.0.0"
35
+ });
36
+ await client.connect(clientTransport);
37
+ const { tools } = await client.listTools();
38
+ const toolDescriptors = {};
39
+ for (const tool of tools) toolDescriptors[tool.name] = {
40
+ description: tool.description,
41
+ inputSchema: tool.inputSchema
42
+ };
43
+ const types = generateTypesFromJsonSchema(toolDescriptors);
44
+ const fns = {};
45
+ for (const tool of tools) {
46
+ const toolName = tool.name;
47
+ fns[toolName] = async (args) => {
48
+ return await client.callTool({
49
+ name: toolName,
50
+ arguments: args
51
+ });
52
+ };
53
+ }
54
+ const firstTool = tools[0];
55
+ let example = "";
56
+ if (firstTool) {
57
+ const props = firstTool.inputSchema.properties ?? {};
58
+ const parts = [];
59
+ for (const [key, prop] of Object.entries(props)) if (prop.type === "number" || prop.type === "integer") parts.push(`${key}: 0`);
60
+ else if (prop.type === "boolean") parts.push(`${key}: true`);
61
+ else parts.push(`${key}: "..."`);
62
+ const args = parts.length > 0 ? `{ ${parts.join(", ")} }` : "{}";
63
+ example = `Example: async () => { const r = await codemode.${sanitizeToolName(firstTool.name)}(${args}); return r; }`;
64
+ }
65
+ const description = CODE_DESCRIPTION.replace("{{types}}", types).replace("{{example}}", example);
66
+ const codemodeServer = new McpServer({
67
+ name: "codemode",
68
+ version: "1.0.0"
69
+ });
70
+ codemodeServer.registerTool("code", {
71
+ description,
72
+ inputSchema: { code: z.string().describe("JavaScript async arrow function to execute") }
73
+ }, async ({ code }) => {
74
+ try {
75
+ const result = await executor.execute(code, [{
76
+ name: "codemode",
77
+ fns
78
+ }]);
79
+ if (result.error) return {
80
+ content: [{
81
+ type: "text",
82
+ text: `Error: ${result.error}`
83
+ }],
84
+ isError: true
85
+ };
86
+ return { content: [{
87
+ type: "text",
88
+ text: truncateResponse(result.result)
89
+ }] };
90
+ } catch (error) {
91
+ return {
92
+ content: [{
93
+ type: "text",
94
+ text: `Error: ${formatError(error)}`
95
+ }],
96
+ isError: true
97
+ };
98
+ }
99
+ });
100
+ return codemodeServer;
101
+ }
102
+ /**
103
+ * Resolve internal $ref pointers in a JSON object against the root document.
104
+ * Only handles `#/` internal refs. External file refs are left as-is.
105
+ */
106
+ function resolveRefs(obj, root, seen = /* @__PURE__ */ new Set()) {
107
+ if (obj === null || obj === void 0) return obj;
108
+ if (typeof obj !== "object") return obj;
109
+ if (Array.isArray(obj)) return obj.map((item) => resolveRefs(item, root, seen));
110
+ const record = obj;
111
+ if ("$ref" in record && typeof record.$ref === "string") {
112
+ const ref = record.$ref;
113
+ if (seen.has(ref)) return { $circular: ref };
114
+ if (!ref.startsWith("#/")) return record;
115
+ seen.add(ref);
116
+ const parts = ref.slice(2).split("/").map((s) => s.replace(/~1/g, "/").replace(/~0/g, "~"));
117
+ let resolved = root;
118
+ for (const part of parts) resolved = resolved?.[part];
119
+ const result = resolveRefs(resolved, root, seen);
120
+ seen.delete(ref);
121
+ return result;
122
+ }
123
+ const result = {};
124
+ for (const [key, value] of Object.entries(record)) result[key] = resolveRefs(value, root, seen);
125
+ return result;
126
+ }
127
+ const SPEC_TYPES = `
128
+ // OpenAPI 3.x spec with $refs resolved inline.
129
+ // The spec object follows the standard OpenAPI 3.x structure.
130
+
131
+ interface OperationObject {
132
+ summary?: string;
133
+ description?: string;
134
+ operationId?: string;
135
+ tags?: string[];
136
+ parameters?: Array<{
137
+ name: string;
138
+ in: "query" | "header" | "path" | "cookie";
139
+ required?: boolean;
140
+ schema?: unknown;
141
+ description?: string;
142
+ }>;
143
+ requestBody?: {
144
+ required?: boolean;
145
+ description?: string;
146
+ content?: Record<string, { schema?: unknown }>;
147
+ };
148
+ responses?: Record<string, {
149
+ description?: string;
150
+ content?: Record<string, { schema?: unknown }>;
151
+ }>;
152
+ security?: Array<Record<string, string[]>>;
153
+ deprecated?: boolean;
154
+ }
155
+
156
+ interface PathItem {
157
+ summary?: string;
158
+ description?: string;
159
+ get?: OperationObject;
160
+ post?: OperationObject;
161
+ put?: OperationObject;
162
+ patch?: OperationObject;
163
+ delete?: OperationObject;
164
+ head?: OperationObject;
165
+ options?: OperationObject;
166
+ trace?: OperationObject;
167
+ parameters?: OperationObject["parameters"];
168
+ }
169
+
170
+ interface OpenApiSpec {
171
+ openapi: string;
172
+ info: { title: string; version: string; description?: string };
173
+ paths: Record<string, PathItem>;
174
+ servers?: Array<{ url: string; description?: string }>;
175
+ components?: Record<string, unknown>;
176
+ tags?: Array<{ name: string; description?: string }>;
177
+ }
178
+
179
+ declare const codemode: {
180
+ spec(): Promise<OpenApiSpec>;
181
+ };
182
+ `;
183
+ const REQUEST_TYPES = `
184
+ interface RequestOptions {
185
+ method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
186
+ path: string;
187
+ query?: Record<string, string | number | boolean | undefined>;
188
+ body?: unknown;
189
+ contentType?: string;
190
+ rawBody?: boolean;
191
+ }
192
+
193
+ declare const codemode: {
194
+ request(options: RequestOptions): Promise<unknown>;
195
+ };
196
+ `;
197
+ /**
198
+ * Create an MCP server with search + execute tools from an OpenAPI spec.
199
+ *
200
+ * The search tool lets the LLM query the spec to find endpoints.
201
+ * The execute tool lets the LLM call the API via a user-provided
202
+ * request function that runs on the host (auth never enters the sandbox).
203
+ */
204
+ function openApiMcpServer(options) {
205
+ const { executor, request: requestFn, name = "openapi", version = "1.0.0", description } = options;
206
+ const resolved = resolveRefs(options.spec, options.spec);
207
+ const server = new McpServer({
208
+ name,
209
+ version
210
+ });
211
+ server.registerTool("search", {
212
+ description: `Search the OpenAPI spec. All $refs are pre-resolved inline.
213
+
214
+ Types:
215
+ ${SPEC_TYPES}
216
+
217
+ Your code must be an async arrow function that returns the result.
218
+
219
+ Examples:
220
+
221
+ // List all paths
222
+ async () => {
223
+ const spec = await codemode.spec();
224
+ return Object.keys(spec.paths);
225
+ }
226
+
227
+ // Find endpoints by tag
228
+ async () => {
229
+ const spec = await codemode.spec();
230
+ const results = [];
231
+ for (const [path, methods] of Object.entries(spec.paths)) {
232
+ for (const [method, op] of Object.entries(methods)) {
233
+ if (op.tags?.some(t => t.toLowerCase() === 'your_tag')) {
234
+ results.push({ method: method.toUpperCase(), path, summary: op.summary });
235
+ }
236
+ }
237
+ }
238
+ return results;
239
+ }`,
240
+ inputSchema: { code: z.string().describe("JavaScript async arrow function to search the spec") }
241
+ }, async ({ code }) => {
242
+ try {
243
+ const result = await executor.execute(code, [{
244
+ name: "codemode",
245
+ fns: { spec: async () => resolved }
246
+ }]);
247
+ if (result.error) return {
248
+ content: [{
249
+ type: "text",
250
+ text: `Error: ${result.error}`
251
+ }],
252
+ isError: true
253
+ };
254
+ return { content: [{
255
+ type: "text",
256
+ text: truncateResponse(result.result)
257
+ }] };
258
+ } catch (error) {
259
+ return {
260
+ content: [{
261
+ type: "text",
262
+ text: `Error: ${formatError(error)}`
263
+ }],
264
+ isError: true
265
+ };
266
+ }
267
+ });
268
+ const executeDescription = `Execute API calls using JavaScript code. First use 'search' to find the right endpoints.
269
+
270
+ Available in your code:
271
+ ${REQUEST_TYPES}
272
+
273
+ Your code must be an async arrow function that returns the result.
274
+
275
+ Example:
276
+ async () => {
277
+ return await codemode.request({ method: "GET", path: "/your/endpoint" });
278
+ }${description ? `\n\n${description}` : ""}`;
279
+ server.registerTool("execute", {
280
+ description: executeDescription,
281
+ inputSchema: { code: z.string().describe("JavaScript async arrow function to execute") }
282
+ }, async ({ code }) => {
283
+ try {
284
+ const result = await executor.execute(code, [{
285
+ name: "codemode",
286
+ fns: { request: (args) => requestFn(args) }
287
+ }]);
288
+ if (result.error) return {
289
+ content: [{
290
+ type: "text",
291
+ text: `Error: ${result.error}`
292
+ }],
293
+ isError: true
294
+ };
295
+ return { content: [{
296
+ type: "text",
297
+ text: truncateResponse(result.result)
298
+ }] };
299
+ } catch (error) {
300
+ return {
301
+ content: [{
302
+ type: "text",
303
+ text: `Error: ${formatError(error)}`
304
+ }],
305
+ isError: true
306
+ };
307
+ }
308
+ });
309
+ return server;
310
+ }
311
+ //#endregion
312
+ export { codeMcpServer, openApiMcpServer };
313
+
314
+ //# sourceMappingURL=mcp.js.map
@@ -0,0 +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\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\nexport async function codeMcpServer(\n options: CodeMcpServerOptions\n): Promise<McpServer> {\n const { server, executor } = 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 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 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 description = CODE_DESCRIPTION.replace(\"{{types}}\", types).replace(\n \"{{example}}\",\n example\n );\n\n const codemodeServer = new McpServer({\n name: \"codemode\",\n version: \"1.0.0\"\n });\n\n codemodeServer.registerTool(\n \"code\",\n {\n description,\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,MAA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Y,UAAU;IAAE,CAC1D,CAAC;AACF,OAAI,OAAO,MACT,QAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,OAAO;KAAS,CAC1D;IACD,SAAS;IACV;AAEH,UAAO,EACL,SAAS,CACP;IAAE,MAAM;IAAiB,MAAM,iBAAiB,OAAO,OAAO;IAAE,CACjE,EACF;WACM,OAAO;AACd,UAAO;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;AAEtC,QAAO,aACL,WACA;EACE,aAAa;EACb,aAAa,EACX,MAAM,EAAE,QAAQ,CAAC,SAAS,6CAA6C,EACxE;EACF,EACD,OAAO,EAAE,WAAW;AAClB,MAAI;GACF,MAAM,SAAS,MAAM,SAAS,QAAQ,MAAM,CAC1C;IACE,MAAM;IACN,KAAK,EACH,UAAU,SAAkB,UAAU,KAAuB,EAC9D;IACF,CACF,CAAC;AACF,OAAI,OAAO,MACT,QAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,OAAO;KAAS,CAC1D;IACD,SAAS;IACV;AAEH,UAAO,EACL,SAAS,CACP;IAAE,MAAM;IAAiB,MAAM,iBAAiB,OAAO,OAAO;IAAE,CACjE,EACF;WACM,OAAO;AACd,UAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,YAAY,MAAM;KAAI,CAChE;IACD,SAAS;IACV;;GAGN;AAED,QAAO"}
@@ -0,0 +1,342 @@
1
+ import { a as sanitizeToolName, i as escapeJsDoc, o as toPascalCase, r as jsonSchemaToTypeString } from "./json-schema-types-DoQ0VISs.js";
2
+ import * as acorn from "acorn";
3
+ import { asSchema, tool } from "ai";
4
+ import { z } from "zod";
5
+ //#region src/normalize.ts
6
+ /**
7
+ * Strip markdown code fences that LLMs commonly wrap code in.
8
+ * Handles ```js, ```javascript, ```typescript, ```ts, or bare ```.
9
+ */
10
+ function stripCodeFences(code) {
11
+ const match = code.match(/^```(?:js|javascript|typescript|ts|tsx|jsx)?\s*\n([\s\S]*?)```\s*$/);
12
+ return match ? match[1] : code;
13
+ }
14
+ function normalizeCode(code) {
15
+ const trimmed = stripCodeFences(code.trim());
16
+ if (!trimmed.trim()) return "async () => {}";
17
+ const source = trimmed.trim();
18
+ try {
19
+ const ast = acorn.parse(source, {
20
+ ecmaVersion: "latest",
21
+ sourceType: "module"
22
+ });
23
+ if (ast.body.length === 1 && ast.body[0].type === "ExpressionStatement") {
24
+ if (ast.body[0].expression.type === "ArrowFunctionExpression") return source;
25
+ }
26
+ if (ast.body.length === 1 && ast.body[0].type === "ExportDefaultDeclaration") {
27
+ const decl = ast.body[0].declaration;
28
+ const inner = source.slice(decl.start, decl.end);
29
+ if (decl.type === "FunctionDeclaration" && !decl.id) return `async () => {\nreturn (${inner})();\n}`;
30
+ if (decl.type === "ClassDeclaration" && !decl.id) return `async () => {\nreturn (${inner});\n}`;
31
+ return normalizeCode(inner);
32
+ }
33
+ if (ast.body.length === 1 && ast.body[0].type === "FunctionDeclaration") return `async () => {\n${source}\nreturn ${ast.body[0].id?.name ?? "fn"}();\n}`;
34
+ const last = ast.body[ast.body.length - 1];
35
+ if (last?.type === "ExpressionStatement") {
36
+ const exprStmt = last;
37
+ return `async () => {\n${source.slice(0, last.start)}return (${source.slice(exprStmt.expression.start, exprStmt.expression.end)})\n}`;
38
+ }
39
+ return `async () => {\n${source}\n}`;
40
+ } catch {
41
+ return `async () => {\n${source}\n}`;
42
+ }
43
+ }
44
+ //#endregion
45
+ //#region src/tool-types.ts
46
+ /**
47
+ * Check if a value is a Zod schema (has _zod property).
48
+ */
49
+ function isZodSchema(value) {
50
+ return value !== null && typeof value === "object" && "_zod" in value && value._zod !== void 0;
51
+ }
52
+ /**
53
+ * Check if a value conforms to the Standard Schema protocol (~standard).
54
+ * This catches Zod v3 schemas (which expose ~standard but not _zod).
55
+ */
56
+ function isStandardSchema(value) {
57
+ return value !== null && typeof value === "object" && "~standard" in value && value["~standard"] !== void 0;
58
+ }
59
+ /**
60
+ * Check if a value is an AI SDK jsonSchema wrapper.
61
+ * The jsonSchema wrapper has a [Symbol] with jsonSchema property.
62
+ */
63
+ function isJsonSchemaWrapper(value) {
64
+ if (value === null || typeof value !== "object") return false;
65
+ if ("jsonSchema" in value) return true;
66
+ const symbols = Object.getOwnPropertySymbols(value);
67
+ for (const sym of symbols) {
68
+ const symValue = value[sym];
69
+ if (symValue && typeof symValue === "object" && "jsonSchema" in symValue) return true;
70
+ }
71
+ return false;
72
+ }
73
+ /**
74
+ * Extract JSON schema from an AI SDK jsonSchema wrapper.
75
+ */
76
+ function extractJsonSchema(wrapper) {
77
+ if (wrapper === null || typeof wrapper !== "object") return null;
78
+ if ("jsonSchema" in wrapper) return wrapper.jsonSchema;
79
+ const symbols = Object.getOwnPropertySymbols(wrapper);
80
+ for (const sym of symbols) {
81
+ const symValue = wrapper[sym];
82
+ if (symValue && typeof symValue === "object" && "jsonSchema" in symValue) return symValue.jsonSchema;
83
+ }
84
+ return null;
85
+ }
86
+ /**
87
+ * Extract field descriptions from a schema.
88
+ * Works with Zod schemas (via .shape) and jsonSchema wrappers (via .properties).
89
+ */
90
+ function extractDescriptions(schema) {
91
+ const descriptions = {};
92
+ const shape = schema.shape;
93
+ if (shape && typeof shape === "object") {
94
+ for (const [fieldName, fieldSchema] of Object.entries(shape)) {
95
+ let s = fieldSchema;
96
+ while (!s.description && typeof s.unwrap === "function") s = s.unwrap();
97
+ if (s.description) descriptions[fieldName] = s.description;
98
+ }
99
+ return descriptions;
100
+ }
101
+ if (isJsonSchemaWrapper(schema)) {
102
+ const jsonSchema = extractJsonSchema(schema);
103
+ if (jsonSchema?.properties) {
104
+ for (const [fieldName, propSchema] of Object.entries(jsonSchema.properties)) if (propSchema && typeof propSchema === "object" && propSchema.description) descriptions[fieldName] = propSchema.description;
105
+ }
106
+ }
107
+ return descriptions;
108
+ }
109
+ /**
110
+ * Extract field descriptions from a schema and format as @param lines.
111
+ */
112
+ function extractParamDescriptions(schema) {
113
+ const descriptions = extractDescriptions(schema);
114
+ return Object.entries(descriptions).map(([fieldName, desc]) => `@param input.${fieldName} - ${desc}`);
115
+ }
116
+ /**
117
+ * Safely convert a schema to TypeScript type string.
118
+ * Handles Zod schemas (v3/v4) and AI SDK jsonSchema wrappers.
119
+ */
120
+ function safeSchemaToTs(schema, typeName) {
121
+ try {
122
+ if (isZodSchema(schema) || isStandardSchema(schema)) {
123
+ const jsonSchema = asSchema(schema).jsonSchema;
124
+ if (jsonSchema) return `type ${typeName} = ${jsonSchemaToTypeString(jsonSchema, "", {
125
+ root: jsonSchema,
126
+ depth: 0,
127
+ seen: /* @__PURE__ */ new Set(),
128
+ maxDepth: 20
129
+ })}`;
130
+ }
131
+ if (isJsonSchemaWrapper(schema)) {
132
+ const jsonSchema = extractJsonSchema(schema);
133
+ if (jsonSchema) return `type ${typeName} = ${jsonSchemaToTypeString(jsonSchema, "", {
134
+ root: jsonSchema,
135
+ depth: 0,
136
+ seen: /* @__PURE__ */ new Set(),
137
+ maxDepth: 20
138
+ })}`;
139
+ }
140
+ return `type ${typeName} = unknown`;
141
+ } catch {
142
+ return `type ${typeName} = unknown`;
143
+ }
144
+ }
145
+ /**
146
+ * Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.
147
+ * These types can be included in tool descriptions to help LLMs write correct code.
148
+ *
149
+ * Requires the `ai` peer dependency. For a version that works with plain JSON Schema
150
+ * objects (no AI SDK), use `generateTypesFromJsonSchema` from the main entry point.
151
+ */
152
+ function generateTypes(tools, namespace = "codemode") {
153
+ let availableTools = "";
154
+ let availableTypes = "";
155
+ for (const [toolName, tool] of Object.entries(tools)) {
156
+ const safeName = sanitizeToolName(toolName);
157
+ const typeName = toPascalCase(safeName);
158
+ try {
159
+ const inputSchema = "inputSchema" in tool ? tool.inputSchema : tool.parameters;
160
+ const outputSchema = "outputSchema" in tool ? tool.outputSchema : void 0;
161
+ const description = tool.description;
162
+ const inputType = safeSchemaToTs(inputSchema, `${typeName}Input`);
163
+ const outputType = outputSchema ? safeSchemaToTs(outputSchema, `${typeName}Output`) : `type ${typeName}Output = unknown`;
164
+ availableTypes += `\n${inputType.trim()}`;
165
+ availableTypes += `\n${outputType.trim()}`;
166
+ const paramDescs = (() => {
167
+ try {
168
+ return inputSchema ? extractParamDescriptions(inputSchema) : [];
169
+ } catch {
170
+ return [];
171
+ }
172
+ })();
173
+ const jsdocLines = [];
174
+ if (description?.trim()) jsdocLines.push(escapeJsDoc(description.trim().replace(/\r?\n/g, " ")));
175
+ else jsdocLines.push(escapeJsDoc(toolName));
176
+ for (const pd of paramDescs) jsdocLines.push(escapeJsDoc(pd.replace(/\r?\n/g, " ")));
177
+ const jsdocBody = jsdocLines.map((l) => `\t * ${l}`).join("\n");
178
+ availableTools += `\n\t/**\n${jsdocBody}\n\t */`;
179
+ availableTools += `\n\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;
180
+ availableTools += "\n";
181
+ } catch {
182
+ availableTypes += `\ntype ${typeName}Input = unknown`;
183
+ availableTypes += `\ntype ${typeName}Output = unknown`;
184
+ availableTools += `\n\t/**\n\t * ${escapeJsDoc(toolName)}\n\t */`;
185
+ availableTools += `\n\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;
186
+ availableTools += "\n";
187
+ }
188
+ }
189
+ availableTools = `\ndeclare const ${namespace}: {${availableTools}}`;
190
+ return `
191
+ ${availableTypes}
192
+ ${availableTools}
193
+ `.trim();
194
+ }
195
+ //#endregion
196
+ //#region src/tool.ts
197
+ const DEFAULT_DESCRIPTION = `Execute code to achieve a goal.
198
+
199
+ Available:
200
+ {{types}}
201
+
202
+ Write an async arrow function in JavaScript that returns the result.
203
+ Do NOT use TypeScript syntax — no type annotations, interfaces, or generics.
204
+ Do NOT define named functions then call them — just write the arrow function body directly.
205
+
206
+ Example: async () => { const r = await codemode.searchWeb({ query: "test" }); return r; }`;
207
+ const codeSchema = z.object({ code: z.string().describe("JavaScript async arrow function to execute") });
208
+ /**
209
+ * Create a codemode tool that allows LLMs to write and execute code
210
+ * with access to your tools in a sandboxed environment.
211
+ *
212
+ * Returns an AI SDK compatible tool.
213
+ *
214
+ * @example Raw tools (backwards compatible)
215
+ * ```ts
216
+ * createCodeTool({ tools: myToolSet, executor });
217
+ * ```
218
+ *
219
+ * @example ToolProvider array with namespaces
220
+ * ```ts
221
+ * createCodeTool({
222
+ * tools: [
223
+ * { name: "github", tools: githubTools },
224
+ * { name: "state", tools: stateTools },
225
+ * { tools: aiTools }, // default "codemode" namespace
226
+ * ],
227
+ * executor,
228
+ * });
229
+ * ```
230
+ */
231
+ function hasNeedsApproval(t) {
232
+ return "needsApproval" in t && t.needsApproval != null;
233
+ }
234
+ /**
235
+ * Check if the tools option is an array of ToolProviders.
236
+ * A plain ToolSet/ToolDescriptors is a Record (not an array).
237
+ */
238
+ function isToolProviderArray(tools) {
239
+ return Array.isArray(tools);
240
+ }
241
+ /**
242
+ * Normalize the tools option into a list of ToolProviders.
243
+ * Raw ToolSet/ToolDescriptors are wrapped as a single default provider.
244
+ */
245
+ function normalizeProviders(tools) {
246
+ if (isToolProviderArray(tools)) return tools;
247
+ return [{ tools }];
248
+ }
249
+ /**
250
+ * Filter out tools with needsApproval and return a clean copy.
251
+ */
252
+ function filterTools(tools) {
253
+ const filtered = {};
254
+ for (const [name, t] of Object.entries(tools)) if (!hasNeedsApproval(t)) filtered[name] = t;
255
+ return filtered;
256
+ }
257
+ /**
258
+ * Extract execute functions from tools, keyed by name.
259
+ * Wraps each with schema validation when available.
260
+ * Note: tool name sanitization happens in the executor, not here.
261
+ */
262
+ function extractFns(tools) {
263
+ const fns = {};
264
+ for (const [name, t] of Object.entries(tools)) {
265
+ const execute = "execute" in t ? t.execute : void 0;
266
+ if (execute) {
267
+ const rawSchema = "inputSchema" in t ? t.inputSchema : "parameters" in t ? t.parameters : void 0;
268
+ const schema = rawSchema != null ? asSchema(rawSchema) : void 0;
269
+ fns[name] = schema?.validate ? async (args) => {
270
+ const result = await schema.validate(args);
271
+ if (!result.success) throw result.error;
272
+ return execute(result.value);
273
+ } : execute;
274
+ }
275
+ }
276
+ return fns;
277
+ }
278
+ /**
279
+ * Resolve a ToolProvider into a ResolvedProvider ready for execution.
280
+ * Filters out tools with `needsApproval`, validates schemas, and sanitizes names.
281
+ */
282
+ /**
283
+ * Wrap raw AI SDK tools into a ToolProvider under the default "codemode" namespace.
284
+ *
285
+ * @example
286
+ * ```ts
287
+ * createCodeTool({
288
+ * tools: [stateTools(workspace), aiTools(myTools)],
289
+ * executor,
290
+ * });
291
+ * ```
292
+ */
293
+ function aiTools(tools) {
294
+ return { tools };
295
+ }
296
+ function resolveProvider(provider) {
297
+ const resolved = {
298
+ name: provider.name ?? "codemode",
299
+ fns: extractFns(filterTools(provider.tools))
300
+ };
301
+ if (provider.positionalArgs) resolved.positionalArgs = true;
302
+ return resolved;
303
+ }
304
+ function createCodeTool(options) {
305
+ const providers = normalizeProviders(options.tools);
306
+ const typeBlocks = [];
307
+ const resolvedProviders = [];
308
+ for (const provider of providers) {
309
+ const name = provider.name ?? "codemode";
310
+ const filtered = filterTools(provider.tools);
311
+ const types = provider.types ?? generateTypes(filtered, name);
312
+ typeBlocks.push(types);
313
+ resolvedProviders.push({
314
+ name,
315
+ fns: extractFns(filtered)
316
+ });
317
+ }
318
+ const typeBlock = typeBlocks.filter(Boolean).join("\n\n");
319
+ const executor = options.executor;
320
+ return tool({
321
+ description: (options.description ?? DEFAULT_DESCRIPTION).replace("{{types}}", typeBlock),
322
+ inputSchema: codeSchema,
323
+ execute: async ({ code }) => {
324
+ const normalizedCode = normalizeCode(code);
325
+ const executeResult = await executor.execute(normalizedCode, resolvedProviders);
326
+ if (executeResult.error) {
327
+ const logCtx = executeResult.logs?.length ? `\n\nConsole output:\n${executeResult.logs.join("\n")}` : "";
328
+ throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`);
329
+ }
330
+ const output = {
331
+ code,
332
+ result: executeResult.result
333
+ };
334
+ if (executeResult.logs) output.logs = executeResult.logs;
335
+ return output;
336
+ }
337
+ });
338
+ }
339
+ //#endregion
340
+ export { normalizeCode as a, generateTypes as i, createCodeTool as n, resolveProvider as r, aiTools as t };
341
+
342
+ //# sourceMappingURL=tool-B0ZYASro.js.map