@cloudflare/codemode 0.1.1 → 0.1.3

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/CHANGELOG.md DELETED
@@ -1,109 +0,0 @@
1
- # @cloudflare/codemode
2
-
3
- ## 0.1.1
4
-
5
- ### Patch Changes
6
-
7
- - [#962](https://github.com/cloudflare/agents/pull/962) [`ef46d68`](https://github.com/cloudflare/agents/commit/ef46d68e9c381b7541c4aa803014144abce4fb72) Thanks [@tumberger](https://github.com/tumberger)! - Validate tool arguments against Zod schema before execution in codemode sandbox
8
-
9
- - [#973](https://github.com/cloudflare/agents/pull/973) [`969fbff`](https://github.com/cloudflare/agents/commit/969fbff702d5702c1f0ea6faaecb3dfd0431a01b) Thanks [@threepointone](https://github.com/threepointone)! - Update dependencies
10
-
11
- - [#960](https://github.com/cloudflare/agents/pull/960) [`179b8cb`](https://github.com/cloudflare/agents/commit/179b8cbc60bc9e6ac0d2ee26c430d842950f5f08) Thanks [@mattzcarey](https://github.com/mattzcarey)! - Harden JSON Schema to TypeScript converter for production use
12
- - Add depth and circular reference guards to prevent stack overflows on recursive or deeply nested schemas
13
- - Add `$ref` resolution for internal JSON Pointers (`#/definitions/...`, `#/$defs/...`, `#`)
14
- - Add tuple support (`prefixItems` for JSON Schema 2020-12, array `items` for draft-07)
15
- - Add OpenAPI 3.0 `nullable: true` support across all schema branches
16
- - Fix string escaping in enum/const values, property names (control chars, U+2028/U+2029), and JSDoc comments (`*/`)
17
- - Add per-tool error isolation in `generateTypes()` so one malformed schema cannot crash the pipeline
18
- - Guard missing `inputSchema` in `getAITools()` with a fallback to `{ type: "object" }`
19
- - Add per-tool error isolation in `getAITools()` so one bad MCP tool does not break the entire tool set
20
-
21
- - [#961](https://github.com/cloudflare/agents/pull/961) [`f6aa79f`](https://github.com/cloudflare/agents/commit/f6aa79f3bf86922db73b4d33439262aefcbcf817) Thanks [@mattzcarey](https://github.com/mattzcarey)! - Updated default tool prompt to explicitly request JavaScript code from LLMs, preventing TypeScript syntax errors in the Dynamic Worker executor.
22
-
23
- ## 0.1.0
24
-
25
- ### Minor Changes
26
-
27
- - [#879](https://github.com/cloudflare/agents/pull/879) [`90e54da`](https://github.com/cloudflare/agents/commit/90e54dab21f7c2c783aac117693918765e8b254b) Thanks [@mattzcarey](https://github.com/mattzcarey)! - Remove experimental_codemode() and CodeModeProxy. Replace with createCodeTool() from @cloudflare/codemode/ai which returns a standard AI SDK Tool. The package no longer owns an LLM call or model choice. Users call streamText/generateText with their own model and pass the codemode tool.
28
-
29
- The AI-dependent export (createCodeTool) is now at @cloudflare/codemode/ai. The root export (@cloudflare/codemode) contains the executor, type generation, and utilities which do not require the ai peer dependency.
30
-
31
- ToolDispatcher (extends RpcTarget) replaces CodeModeProxy (extends WorkerEntrypoint) for dispatching tool calls from the sandbox back to the host. It is passed as a parameter to the dynamic worker's evaluate() method instead of being injected as an env binding, removing the need for CodeModeProxy and globalOutbound service bindings. Only a WorkerLoader binding is required now. globalOutbound on DynamicWorkerExecutor defaults to null which blocks fetch/connect at the runtime level. New Executor interface (execute(code, fns) => ExecuteResult) allows custom sandbox implementations. DynamicWorkerExecutor is the Cloudflare Workers implementation. Console output captured in ExecuteResult.logs. Configurable execution timeout.
32
-
33
- AST-based code normalization via acorn replaces regex. sanitizeToolName() exported for converting MCP-style tool names to valid JS identifiers.
34
-
35
- ### Patch Changes
36
-
37
- - [#954](https://github.com/cloudflare/agents/pull/954) [`943c407`](https://github.com/cloudflare/agents/commit/943c4070992bb836625abb5bf4e3271a6f52f7a2) Thanks [@threepointone](https://github.com/threepointone)! - update dependencies
38
-
39
- ## 0.0.8
40
-
41
- ### Patch Changes
42
-
43
- - [#916](https://github.com/cloudflare/agents/pull/916) [`24e16e0`](https://github.com/cloudflare/agents/commit/24e16e025b82dbd7b321339a18c6d440b2879136) Thanks [@threepointone](https://github.com/threepointone)! - Widen peer dependency ranges across packages to prevent cascading major bumps during 0.x minor releases. Mark `@cloudflare/ai-chat` and `@cloudflare/codemode` as optional peer dependencies of `agents` to fix unmet peer dependency warnings during installation.
44
-
45
- ## 0.0.7
46
-
47
- ### Patch Changes
48
-
49
- - [#849](https://github.com/cloudflare/agents/pull/849) [`21a7977`](https://github.com/cloudflare/agents/commit/21a79778f5150aecd890f55a164d397f70db681e) Thanks [@Muhammad-Bin-Ali](https://github.com/Muhammad-Bin-Ali)! - Allow configurable model in `experimental_codemode` instead of hardcoded `gpt-4.1`
50
-
51
- - [#859](https://github.com/cloudflare/agents/pull/859) [`3de98a3`](https://github.com/cloudflare/agents/commit/3de98a398d55aeca51c7b845ed4c5d6051887d6d) Thanks [@threepointone](https://github.com/threepointone)! - broaden peer deps
52
-
53
- - [#865](https://github.com/cloudflare/agents/pull/865) [`c3211d0`](https://github.com/cloudflare/agents/commit/c3211d0b0cc36aa294c15569ae650d3afeab9926) Thanks [@threepointone](https://github.com/threepointone)! - update dependencies
54
-
55
- ## 0.0.6
56
-
57
- ### Patch Changes
58
-
59
- - [#813](https://github.com/cloudflare/agents/pull/813) [`7aebab3`](https://github.com/cloudflare/agents/commit/7aebab369d1bef6c685e05a4a3bd6627edcb87db) Thanks [@threepointone](https://github.com/threepointone)! - update dependencies
60
-
61
- - [#800](https://github.com/cloudflare/agents/pull/800) [`a54edf5`](https://github.com/cloudflare/agents/commit/a54edf56b462856d1ef4f424c2363ac43a53c46e) Thanks [@threepointone](https://github.com/threepointone)! - Update dependencies
62
-
63
- - [#818](https://github.com/cloudflare/agents/pull/818) [`7c74336`](https://github.com/cloudflare/agents/commit/7c743360d7e3639e187725391b9d5c114838bd18) Thanks [@threepointone](https://github.com/threepointone)! - update dependencies
64
-
65
- - Updated dependencies [[`0c3c9bb`](https://github.com/cloudflare/agents/commit/0c3c9bb62ceff66ed38d3bbd90c767600f1f3453), [`0c3c9bb`](https://github.com/cloudflare/agents/commit/0c3c9bb62ceff66ed38d3bbd90c767600f1f3453), [`d1a0c2b`](https://github.com/cloudflare/agents/commit/d1a0c2b73b1119d71e120091753a6bcca0e2faa9), [`6218541`](https://github.com/cloudflare/agents/commit/6218541e9c1e40ccbaa25b2d9d93858c0ad81ffa), [`6218541`](https://github.com/cloudflare/agents/commit/6218541e9c1e40ccbaa25b2d9d93858c0ad81ffa), [`6218541`](https://github.com/cloudflare/agents/commit/6218541e9c1e40ccbaa25b2d9d93858c0ad81ffa), [`6218541`](https://github.com/cloudflare/agents/commit/6218541e9c1e40ccbaa25b2d9d93858c0ad81ffa), [`fd79481`](https://github.com/cloudflare/agents/commit/fd7948180abf066fa3d27911a83ffb4c91b3f099), [`6218541`](https://github.com/cloudflare/agents/commit/6218541e9c1e40ccbaa25b2d9d93858c0ad81ffa), [`0c3c9bb`](https://github.com/cloudflare/agents/commit/0c3c9bb62ceff66ed38d3bbd90c767600f1f3453), [`6218541`](https://github.com/cloudflare/agents/commit/6218541e9c1e40ccbaa25b2d9d93858c0ad81ffa), [`6218541`](https://github.com/cloudflare/agents/commit/6218541e9c1e40ccbaa25b2d9d93858c0ad81ffa), [`e20da53`](https://github.com/cloudflare/agents/commit/e20da5319eb46bac6ac580edf71836b00ac6f8bb), [`f604008`](https://github.com/cloudflare/agents/commit/f604008957f136241815909319a552bad6738b58), [`7aebab3`](https://github.com/cloudflare/agents/commit/7aebab369d1bef6c685e05a4a3bd6627edcb87db), [`a54edf5`](https://github.com/cloudflare/agents/commit/a54edf56b462856d1ef4f424c2363ac43a53c46e), [`7c74336`](https://github.com/cloudflare/agents/commit/7c743360d7e3639e187725391b9d5c114838bd18), [`6218541`](https://github.com/cloudflare/agents/commit/6218541e9c1e40ccbaa25b2d9d93858c0ad81ffa), [`ded8d3e`](https://github.com/cloudflare/agents/commit/ded8d3e8aeba0358ebd4aecb5ba15344b5a21db1)]:
66
- - agents@0.3.7
67
-
68
- ## 0.0.5
69
-
70
- ### Patch Changes
71
-
72
- - [#776](https://github.com/cloudflare/agents/pull/776) [`93c613e`](https://github.com/cloudflare/agents/commit/93c613e077e7aa16e78cf9b0b53e285577e92ce5) Thanks [@ShoeBoom](https://github.com/ShoeBoom)! - prepend custom prompt to default assistant text
73
-
74
- - Updated dependencies [[`395f461`](https://github.com/cloudflare/agents/commit/395f46105d3affb5a2e2ffd28c516a0eefe45bb4), [`f27e62c`](https://github.com/cloudflare/agents/commit/f27e62c24f586abb285843db183198230ddd47ca)]:
75
- - agents@0.3.6
76
-
77
- ## 0.0.4
78
-
79
- ### Patch Changes
80
-
81
- - [#771](https://github.com/cloudflare/agents/pull/771) [`87dc96d`](https://github.com/cloudflare/agents/commit/87dc96d19de1d26dbb2badecbb9955a4eb8e9e2e) Thanks [@threepointone](https://github.com/threepointone)! - update dependencies
82
-
83
- - Updated dependencies [[`cf8a1e7`](https://github.com/cloudflare/agents/commit/cf8a1e7a24ecaac62c2aefca7b0fd5bf1373e8bd), [`87dc96d`](https://github.com/cloudflare/agents/commit/87dc96d19de1d26dbb2badecbb9955a4eb8e9e2e)]:
84
- - agents@0.3.4
85
-
86
- ## 0.0.3
87
-
88
- ### Patch Changes
89
-
90
- - [`a5d0137`](https://github.com/cloudflare/agents/commit/a5d01379b9ad2d88bc028c50f1858b4e69f106c5) Thanks [@threepointone](https://github.com/threepointone)! - trigger a new release
91
-
92
- - Updated dependencies [[`a5d0137`](https://github.com/cloudflare/agents/commit/a5d01379b9ad2d88bc028c50f1858b4e69f106c5)]:
93
- - agents@0.3.3
94
-
95
- ## 0.0.2
96
-
97
- ### Patch Changes
98
-
99
- - [#756](https://github.com/cloudflare/agents/pull/756) [`0c4275f`](https://github.com/cloudflare/agents/commit/0c4275f8f4b71c264c32c3742d151ef705739c2f) Thanks [@threepointone](https://github.com/threepointone)! - feat: split ai-chat and codemode into separate packages
100
-
101
- Extract @cloudflare/ai-chat and @cloudflare/codemode into their own packages
102
- with comprehensive READMEs. Update agents README to remove chat-specific
103
- content and point to new packages. Fix documentation imports to reflect
104
- new package structure.
105
-
106
- Maintains backward compatibility, no breaking changes.
107
-
108
- - Updated dependencies [[`0c4275f`](https://github.com/cloudflare/agents/commit/0c4275f8f4b71c264c32c3742d151ef705739c2f), [`f12553f`](https://github.com/cloudflare/agents/commit/f12553f2fa65912c68d9a7620b9a11b70b8790a2)]:
109
- - agents@0.3.2
@@ -1 +0,0 @@
1
- {"version":3,"file":"types-CpkEgXwN.js","names":["printNodeZodToTs"],"sources":["../src/types.ts"],"sourcesContent":["import {\n zodToTs,\n printNode as printNodeZodToTs,\n createTypeAlias,\n createAuxiliaryTypeStore\n} from \"zod-to-ts\";\nimport type { ZodType } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport type { JSONSchema7, JSONSchema7Definition } from \"json-schema\";\n\ninterface ConversionContext {\n root: JSONSchema7;\n depth: number;\n seen: Set<unknown>;\n maxDepth: number;\n}\n\nconst 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\nfunction toCamelCase(str: string) {\n return str\n .replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())\n .replace(/^[a-z]/, (letter) => letter.toUpperCase());\n}\n\n/**\n * Extract field descriptions from a schema and format as @param lines.\n * Returns an array of `@param input.fieldName - description` lines.\n */\nfunction extractParamDescriptions(schema: unknown): string[] {\n const descriptions = extractDescriptions(schema);\n return Object.entries(descriptions).map(\n ([fieldName, desc]) => `@param input.${fieldName} - ${desc}`\n );\n}\n\nexport interface ToolDescriptor {\n description?: string;\n inputSchema: ZodType;\n outputSchema?: ZodType;\n execute?: (args: unknown) => Promise<unknown>;\n}\n\nexport type ToolDescriptors = Record<string, ToolDescriptor>;\n\n/**\n * Check if a value is a Zod schema (has _zod property).\n */\nfunction isZodSchema(value: unknown): value is ZodType {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"_zod\" in value &&\n (value as { _zod?: unknown })._zod !== undefined\n );\n}\n\n/**\n * Check if a value is an AI SDK jsonSchema wrapper.\n * The jsonSchema wrapper has a [Symbol] with jsonSchema property.\n */\nfunction isJsonSchemaWrapper(\n value: unknown\n): value is { jsonSchema: JSONSchema7 } {\n if (value === null || typeof value !== \"object\") return false;\n\n // AI SDK jsonSchema wrapper stores data in a symbol property\n // but also exposes jsonSchema directly in some versions\n if (\"jsonSchema\" in value) {\n return true;\n }\n\n // Check for symbol-based storage (AI SDK internal)\n const symbols = Object.getOwnPropertySymbols(value);\n for (const sym of symbols) {\n const symValue = (value as Record<symbol, unknown>)[sym];\n if (symValue && typeof symValue === \"object\" && \"jsonSchema\" in symValue) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Extract JSON schema from an AI SDK jsonSchema wrapper.\n */\nfunction extractJsonSchema(wrapper: unknown): JSONSchema7 | null {\n if (wrapper === null || typeof wrapper !== \"object\") return null;\n\n // Direct property access\n if (\"jsonSchema\" in wrapper) {\n return (wrapper as { jsonSchema: JSONSchema7 }).jsonSchema;\n }\n\n // Symbol-based storage\n const symbols = Object.getOwnPropertySymbols(wrapper);\n for (const sym of symbols) {\n const symValue = (wrapper as Record<symbol, unknown>)[sym];\n if (symValue && typeof symValue === \"object\" && \"jsonSchema\" in symValue) {\n return (symValue as { jsonSchema: JSONSchema7 }).jsonSchema;\n }\n }\n\n return null;\n}\n\n/**\n * Check if a property name needs quoting in TypeScript.\n */\nfunction needsQuotes(name: string): boolean {\n // Valid JS identifier: starts with letter, $, or _, followed by letters, digits, $, _\n return !/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);\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 */\nfunction quoteProp(name: string): string {\n if (needsQuotes(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 * Handles backslashes, quotes, newlines, control characters, and line/paragraph separators.\n */\nfunction 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 */\nfunction escapeJsDoc(text: string): string {\n return text.replace(/\\*\\//g, \"*\\\\/\");\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 * Convert a JSON Schema to a TypeScript type string.\n * This is a direct conversion without going through Zod.\n */\nfunction 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 const nextCtx: ConversionContext = {\n ...ctx,\n depth: ctx.depth + 1,\n seen: new Set([...ctx.seen, schema])\n };\n\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 ? `@format ${escapeJsDoc(format)}` : undefined;\n\n if (descText && formatTag) {\n // Multi-line JSDoc when both description and format are present\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 // NOTE: In TypeScript, an index signature [key: string]: T requires all\n // named properties to be assignable to T. If any named property has an\n // incompatible type, the generated type is invalid. We emit it anyway\n // since it's more informative for LLMs consuming these types.\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 // additionalProperties: false means no keys allowed → empty object\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}\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 * Extract field descriptions from a schema.\n * Works with Zod schemas (via .shape) and jsonSchema wrappers (via .properties).\n */\nfunction extractDescriptions(schema: unknown): Record<string, string> {\n const descriptions: Record<string, string> = {};\n\n // Try Zod schema shape\n const shape = (schema as { shape?: Record<string, ZodType> }).shape;\n if (shape && typeof shape === \"object\") {\n for (const [fieldName, fieldSchema] of Object.entries(shape)) {\n const desc = (fieldSchema as { description?: string }).description;\n if (desc) {\n descriptions[fieldName] = desc;\n }\n }\n return descriptions;\n }\n\n // Try JSON Schema properties (for jsonSchema wrapper)\n if (isJsonSchemaWrapper(schema)) {\n const jsonSchema = extractJsonSchema(schema);\n if (jsonSchema?.properties) {\n for (const [fieldName, propSchema] of Object.entries(\n jsonSchema.properties\n )) {\n if (\n propSchema &&\n typeof propSchema === \"object\" &&\n propSchema.description\n ) {\n descriptions[fieldName] = propSchema.description;\n }\n }\n }\n }\n\n return descriptions;\n}\n\n/**\n * Safely convert a schema to TypeScript type string.\n * Handles Zod schemas and AI SDK jsonSchema wrappers.\n * Returns \"unknown\" if the schema cannot be represented in TypeScript.\n */\nfunction safeSchemaToTs(\n schema: unknown,\n typeName: string,\n auxiliaryTypeStore: ReturnType<typeof createAuxiliaryTypeStore>\n): string {\n try {\n // For Zod schemas, use zod-to-ts\n if (isZodSchema(schema)) {\n const result = zodToTs(schema, { auxiliaryTypeStore });\n return printNodeZodToTs(createTypeAlias(result.node, typeName));\n }\n\n // For JSON Schema wrapper, convert directly to TypeScript\n if (isJsonSchemaWrapper(schema)) {\n const jsonSchema = extractJsonSchema(schema);\n if (jsonSchema) {\n const ctx: ConversionContext = {\n root: jsonSchema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(jsonSchema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n }\n }\n\n return `type ${typeName} = unknown`;\n } catch {\n // If the schema cannot be represented, fall back to unknown\n return `type ${typeName} = unknown`;\n }\n}\n\n/**\n * Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.\n * These types can be included in tool descriptions to help LLMs write correct code.\n */\nexport function generateTypes(tools: ToolDescriptors | ToolSet): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n const auxiliaryTypeStore = createAuxiliaryTypeStore();\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const camelName = toCamelCase(safeName);\n\n try {\n // Handle both our ToolDescriptor and AI SDK Tool types\n const inputSchema =\n \"inputSchema\" in tool ? tool.inputSchema : tool.parameters;\n const outputSchema =\n \"outputSchema\" in tool ? tool.outputSchema : undefined;\n const description = tool.description;\n\n const inputType = safeSchemaToTs(\n inputSchema,\n `${camelName}Input`,\n auxiliaryTypeStore\n );\n\n const outputType = outputSchema\n ? safeSchemaToTs(outputSchema, `${camelName}Output`, auxiliaryTypeStore)\n : `type ${camelName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n // Build JSDoc comment with description and param descriptions\n const paramDescs = inputSchema\n ? extractParamDescriptions(inputSchema)\n : [];\n const jsdocLines: string[] = [];\n if (description?.trim()) {\n jsdocLines.push(escapeJsDoc(description.trim().replace(/\\r?\\n/g, \" \")));\n } else {\n jsdocLines.push(escapeJsDoc(toolName));\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: ${camelName}Input) => Promise<${camelName}Output>;`;\n availableTools += \"\\n\";\n } catch {\n // One bad tool should not break the others — emit unknown types\n availableTypes += `\\ntype ${camelName}Input = unknown`;\n availableTypes += `\\ntype ${camelName}Output = unknown`;\n\n availableTools += `\\n\\t/**\\n\\t * ${escapeJsDoc(toolName)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${camelName}Input) => Promise<${camelName}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":";;;AAiBA,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;C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,KAAK;AAC/D,qBAAkB,YAAY,UAAU;AACxC,qBAAkB,OAAO,SAAS,YAAY,UAAU,oBAAoB,UAAU;AACtF,qBAAkB;UACZ;AAEN,qBAAkB,UAAU,UAAU;AACtC,qBAAkB,UAAU,UAAU;AAEtC,qBAAkB,iBAAiB,YAAY,SAAS,CAAC;AACzD,qBAAkB,OAAO,SAAS,YAAY,UAAU,oBAAoB,UAAU;AACtF,qBAAkB;;;AAItB,kBAAiB,8BAA8B,eAAe;AAE9D,QAAO;EACP,eAAe;EACf,eAAe;IACb,MAAM"}
@@ -1,124 +0,0 @@
1
- import { test, expect } from "@playwright/test";
2
-
3
- /**
4
- * E2E tests for @cloudflare/codemode with a real AI binding.
5
- *
6
- * These verify the full pipeline:
7
- * user prompt → LLM generates code via createCodeTool → DynamicWorkerExecutor
8
- * runs the code in an isolated Worker → tool functions called via RPC → result returned.
9
- *
10
- * Uses Workers AI (@cf/zai-org/glm-4.7-flash) — no API key needed.
11
- */
12
-
13
- async function runChat(
14
- request: import("@playwright/test").APIRequestContext,
15
- baseURL: string,
16
- userMessage: string
17
- ): Promise<string> {
18
- const res = await request.post(`${baseURL}/run`, {
19
- headers: { "Content-Type": "application/json" },
20
- data: {
21
- messages: [
22
- {
23
- id: `msg-${crypto.randomUUID()}`,
24
- role: "user",
25
- parts: [{ type: "text", text: userMessage }]
26
- }
27
- ]
28
- },
29
- timeout: 45_000
30
- });
31
- expect(res.ok()).toBe(true);
32
- return res.text();
33
- }
34
-
35
- test.describe("codemode e2e (Workers AI)", () => {
36
- test.setTimeout(45_000);
37
-
38
- test("LLM generates and executes code that calls addNumbers tool", async ({
39
- request,
40
- baseURL
41
- }) => {
42
- const response = await runChat(
43
- request,
44
- baseURL!,
45
- "What is 17 + 25? Use the codemode tool with the addNumbers function to calculate this."
46
- );
47
-
48
- // The response stream should contain the answer 42 somewhere
49
- // (either in the tool result or the LLM's text response)
50
- expect(response).toContain("42");
51
- });
52
-
53
- test("LLM generates and executes code that calls getWeather tool", async ({
54
- request,
55
- baseURL
56
- }) => {
57
- const response = await runChat(
58
- request,
59
- baseURL!,
60
- "What is the weather in London? Use the codemode tool with the getWeather function."
61
- );
62
-
63
- // The getWeather tool returns { city: "London", temperature: 22, condition: "Sunny" }
64
- // The LLM should mention London or the weather data in its response
65
- const lower = response.toLowerCase();
66
- expect(
67
- lower.includes("london") ||
68
- lower.includes("22") ||
69
- lower.includes("sunny")
70
- ).toBe(true);
71
- });
72
-
73
- test("LLM generates and executes code that calls listProjects tool", async ({
74
- request,
75
- baseURL
76
- }) => {
77
- const response = await runChat(
78
- request,
79
- baseURL!,
80
- "List all projects using the codemode tool with the listProjects function."
81
- );
82
-
83
- // listProjects returns Alpha and Beta
84
- const lower = response.toLowerCase();
85
- expect(lower.includes("alpha") || lower.includes("beta")).toBe(true);
86
- });
87
-
88
- test("LLM generates code with multiple tool calls", async ({
89
- request,
90
- baseURL
91
- }) => {
92
- const response = await runChat(
93
- request,
94
- baseURL!,
95
- "Using the codemode tool, first get the weather in Paris, then add the numbers 10 and 5. Return both results."
96
- );
97
-
98
- // Should contain evidence of both tool calls completing
99
- const lower = response.toLowerCase();
100
- expect(
101
- lower.includes("paris") ||
102
- lower.includes("22") ||
103
- lower.includes("15") ||
104
- lower.includes("sunny")
105
- ).toBe(true);
106
- });
107
-
108
- test("generateTypes returns valid type definitions", async ({
109
- request,
110
- baseURL
111
- }) => {
112
- const res = await request.get(`${baseURL}/types`);
113
- expect(res.ok()).toBe(true);
114
-
115
- const data = await res.json();
116
- const types = data.types as string;
117
-
118
- expect(types).toContain("declare const codemode");
119
- expect(types).toContain("addNumbers");
120
- expect(types).toContain("getWeather");
121
- expect(types).toContain("createProject");
122
- expect(types).toContain("listProjects");
123
- });
124
- });
@@ -1,24 +0,0 @@
1
- import { defineConfig } from "@playwright/test";
2
- import { dirname, join } from "node:path";
3
- import { fileURLToPath } from "node:url";
4
-
5
- const PORT = 8798;
6
- const e2eDir = dirname(fileURLToPath(import.meta.url));
7
- const configPath = join(e2eDir, "wrangler.jsonc");
8
-
9
- export default defineConfig({
10
- testDir: e2eDir,
11
- testMatch: "*.spec.ts",
12
- timeout: 60_000,
13
- retries: 2,
14
- workers: 1,
15
- use: {
16
- baseURL: `http://localhost:${PORT}`
17
- },
18
- webServer: {
19
- command: `lsof -ti tcp:${PORT} | xargs kill -9 2>/dev/null; npx wrangler dev --config ${configPath} --port ${PORT}`,
20
- port: PORT,
21
- reuseExistingServer: !process.env.CI,
22
- timeout: 30_000
23
- }
24
- });
package/e2e/worker.ts DELETED
@@ -1,144 +0,0 @@
1
- import { Agent, routeAgentRequest, getAgentByName } from "agents";
2
- import {
3
- streamText,
4
- convertToModelMessages,
5
- stepCountIs,
6
- tool,
7
- type UIMessage
8
- } from "ai";
9
- import { createWorkersAI } from "workers-ai-provider";
10
- import { z } from "zod";
11
- import { createCodeTool } from "../src/ai";
12
- import { DynamicWorkerExecutor, generateTypes } from "../src/index";
13
-
14
- type Env = {
15
- AI: Ai;
16
- LOADER: WorkerLoader;
17
- CodemodeAgent: DurableObjectNamespace<CodemodeAgent>;
18
- };
19
-
20
- const pmTools = {
21
- createProject: tool({
22
- description: "Create a new project",
23
- inputSchema: z.object({
24
- name: z.string().describe("Project name"),
25
- description: z.string().optional().describe("Project description")
26
- }),
27
- execute: async ({ name, description }) => ({
28
- id: crypto.randomUUID(),
29
- name,
30
- description: description ?? ""
31
- })
32
- }),
33
-
34
- listProjects: tool({
35
- description: "List all projects",
36
- inputSchema: z.object({}),
37
- execute: async () => [
38
- { id: "proj-1", name: "Alpha", description: "First project" },
39
- { id: "proj-2", name: "Beta", description: "Second project" }
40
- ]
41
- }),
42
-
43
- addNumbers: tool({
44
- description: "Add two numbers together",
45
- inputSchema: z.object({
46
- a: z.number().describe("First number"),
47
- b: z.number().describe("Second number")
48
- }),
49
- execute: async ({ a, b }) => ({ result: a + b })
50
- }),
51
-
52
- getWeather: tool({
53
- description: "Get the current weather for a city",
54
- inputSchema: z.object({
55
- city: z.string().describe("The city name")
56
- }),
57
- execute: async ({ city }) => ({
58
- city,
59
- temperature: 22,
60
- condition: "Sunny"
61
- })
62
- })
63
- };
64
-
65
- export class CodemodeAgent extends Agent<Env> {
66
- observability = undefined;
67
-
68
- async onRequest(request: Request): Promise<Response> {
69
- const url = new URL(request.url);
70
-
71
- if (url.pathname.endsWith("/chat") && request.method === "POST") {
72
- return this.handleChat(request);
73
- }
74
-
75
- if (url.pathname.endsWith("/generate-types")) {
76
- return Response.json({ types: generateTypes(pmTools) });
77
- }
78
-
79
- return new Response("Not found", { status: 404 });
80
- }
81
-
82
- async handleChat(request: Request): Promise<Response> {
83
- const body = (await request.json()) as { messages: UIMessage[] };
84
-
85
- const workersai = createWorkersAI({ binding: this.env.AI });
86
- const model = workersai("@cf/zai-org/glm-4.7-flash");
87
-
88
- const executor = new DynamicWorkerExecutor({
89
- loader: this.env.LOADER
90
- });
91
-
92
- const codemode = createCodeTool({
93
- tools: pmTools,
94
- executor
95
- });
96
-
97
- const result = streamText({
98
- model,
99
- system: `You are a helpful assistant with access to a codemode tool.
100
- When asked to perform operations, use the codemode tool to write JavaScript code that calls the available functions on the \`codemode\` object.
101
- Keep responses very short (1-2 sentences max).
102
- When asked to add numbers, use the addNumbers tool via codemode.
103
- When asked about weather, use the getWeather tool via codemode.
104
- When asked about projects, use createProject or listProjects via codemode.`,
105
- messages: await convertToModelMessages(body.messages),
106
- tools: { codemode },
107
- stopWhen: stepCountIs(5)
108
- });
109
-
110
- return result.toTextStreamResponse();
111
- }
112
- }
113
-
114
- export default {
115
- async fetch(request: Request, env: Env, _ctx: ExecutionContext) {
116
- const url = new URL(request.url);
117
-
118
- if (url.pathname.startsWith("/agents/")) {
119
- return (
120
- (await routeAgentRequest(request, env)) ||
121
- new Response("Not found", { status: 404 })
122
- );
123
- }
124
-
125
- if (url.pathname === "/run" && request.method === "POST") {
126
- const agent = await getAgentByName(env.CodemodeAgent, "e2e-test");
127
- const agentUrl = new URL(request.url);
128
- agentUrl.pathname = "/chat";
129
- return agent.fetch(
130
- new Request(agentUrl.toString(), {
131
- method: "POST",
132
- headers: request.headers,
133
- body: request.body
134
- })
135
- );
136
- }
137
-
138
- if (url.pathname === "/types") {
139
- return Response.json({ types: generateTypes(pmTools) });
140
- }
141
-
142
- return new Response("OK");
143
- }
144
- };
@@ -1,14 +0,0 @@
1
- {
2
- "ai": { "binding": "AI", "remote": true },
3
- "compatibility_date": "2026-01-28",
4
- "compatibility_flags": ["nodejs_compat"],
5
- "define": {
6
- "__filename": "'index.ts'"
7
- },
8
- "durable_objects": {
9
- "bindings": [{ "class_name": "CodemodeAgent", "name": "CodemodeAgent" }]
10
- },
11
- "main": "worker.ts",
12
- "migrations": [{ "new_sqlite_classes": ["CodemodeAgent"], "tag": "v1" }],
13
- "worker_loaders": [{ "binding": "LOADER" }]
14
- }
package/scripts/build.ts DELETED
@@ -1,25 +0,0 @@
1
- import { execSync } from "node:child_process";
2
- import { build } from "tsdown";
3
-
4
- async function main() {
5
- await build({
6
- clean: true,
7
- dts: true,
8
- entry: ["src/index.ts", "src/ai.ts"],
9
- skipNodeModulesBundle: true,
10
- external: ["cloudflare:workers"],
11
- format: "esm",
12
- sourcemap: true,
13
- fixedExtension: false
14
- });
15
-
16
- // then run oxfmt on the generated .d.ts files
17
- execSync("oxfmt --write ./dist/*.d.ts");
18
-
19
- process.exit(0);
20
- }
21
-
22
- main().catch((err) => {
23
- console.error(err);
24
- process.exit(1);
25
- });
package/src/ai.ts DELETED
@@ -1 +0,0 @@
1
- export { createCodeTool, type CreateCodeToolOptions } from "./tool";