@cloudflare/codemode 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/ai.js +13 -4
- package/dist/ai.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/types-CpkEgXwN.js +392 -0
- package/dist/types-CpkEgXwN.js.map +1 -0
- package/package.json +7 -3
- package/CHANGELOG.md +0 -89
- package/dist/types-B9g5T2nd.js +0 -138
- package/dist/types-B9g5T2nd.js.map +0 -1
- package/e2e/codemode.spec.ts +0 -124
- package/e2e/playwright.config.ts +0 -24
- package/e2e/worker.ts +0 -144
- package/e2e/wrangler.jsonc +0 -14
- package/scripts/build.ts +0 -25
- package/src/ai.ts +0 -1
- package/src/executor.ts +0 -170
- package/src/index.ts +0 -13
- package/src/tests/cloudflare-test.d.ts +0 -5
- package/src/tests/executor.test.ts +0 -224
- package/src/tests/tool.test.ts +0 -454
- package/src/tests/tsconfig.json +0 -10
- package/src/tests/types.test.ts +0 -171
- package/src/tool.ts +0 -131
- package/src/types.ts +0 -202
- package/tsconfig.json +0 -4
- package/vitest.config.ts +0 -17
- package/wrangler.jsonc +0 -16
package/CHANGELOG.md
DELETED
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
# @cloudflare/codemode
|
|
2
|
-
|
|
3
|
-
## 0.1.0
|
|
4
|
-
|
|
5
|
-
### Minor Changes
|
|
6
|
-
|
|
7
|
-
- [#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.
|
|
8
|
-
|
|
9
|
-
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.
|
|
10
|
-
|
|
11
|
-
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.
|
|
12
|
-
|
|
13
|
-
AST-based code normalization via acorn replaces regex. sanitizeToolName() exported for converting MCP-style tool names to valid JS identifiers.
|
|
14
|
-
|
|
15
|
-
### Patch Changes
|
|
16
|
-
|
|
17
|
-
- [#954](https://github.com/cloudflare/agents/pull/954) [`943c407`](https://github.com/cloudflare/agents/commit/943c4070992bb836625abb5bf4e3271a6f52f7a2) Thanks [@threepointone](https://github.com/threepointone)! - update dependencies
|
|
18
|
-
|
|
19
|
-
## 0.0.8
|
|
20
|
-
|
|
21
|
-
### Patch Changes
|
|
22
|
-
|
|
23
|
-
- [#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.
|
|
24
|
-
|
|
25
|
-
## 0.0.7
|
|
26
|
-
|
|
27
|
-
### Patch Changes
|
|
28
|
-
|
|
29
|
-
- [#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`
|
|
30
|
-
|
|
31
|
-
- [#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
|
|
32
|
-
|
|
33
|
-
- [#865](https://github.com/cloudflare/agents/pull/865) [`c3211d0`](https://github.com/cloudflare/agents/commit/c3211d0b0cc36aa294c15569ae650d3afeab9926) Thanks [@threepointone](https://github.com/threepointone)! - update dependencies
|
|
34
|
-
|
|
35
|
-
## 0.0.6
|
|
36
|
-
|
|
37
|
-
### Patch Changes
|
|
38
|
-
|
|
39
|
-
- [#813](https://github.com/cloudflare/agents/pull/813) [`7aebab3`](https://github.com/cloudflare/agents/commit/7aebab369d1bef6c685e05a4a3bd6627edcb87db) Thanks [@threepointone](https://github.com/threepointone)! - update dependencies
|
|
40
|
-
|
|
41
|
-
- [#800](https://github.com/cloudflare/agents/pull/800) [`a54edf5`](https://github.com/cloudflare/agents/commit/a54edf56b462856d1ef4f424c2363ac43a53c46e) Thanks [@threepointone](https://github.com/threepointone)! - Update dependencies
|
|
42
|
-
|
|
43
|
-
- [#818](https://github.com/cloudflare/agents/pull/818) [`7c74336`](https://github.com/cloudflare/agents/commit/7c743360d7e3639e187725391b9d5c114838bd18) Thanks [@threepointone](https://github.com/threepointone)! - update dependencies
|
|
44
|
-
|
|
45
|
-
- 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)]:
|
|
46
|
-
- agents@0.3.7
|
|
47
|
-
|
|
48
|
-
## 0.0.5
|
|
49
|
-
|
|
50
|
-
### Patch Changes
|
|
51
|
-
|
|
52
|
-
- [#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
|
|
53
|
-
|
|
54
|
-
- Updated dependencies [[`395f461`](https://github.com/cloudflare/agents/commit/395f46105d3affb5a2e2ffd28c516a0eefe45bb4), [`f27e62c`](https://github.com/cloudflare/agents/commit/f27e62c24f586abb285843db183198230ddd47ca)]:
|
|
55
|
-
- agents@0.3.6
|
|
56
|
-
|
|
57
|
-
## 0.0.4
|
|
58
|
-
|
|
59
|
-
### Patch Changes
|
|
60
|
-
|
|
61
|
-
- [#771](https://github.com/cloudflare/agents/pull/771) [`87dc96d`](https://github.com/cloudflare/agents/commit/87dc96d19de1d26dbb2badecbb9955a4eb8e9e2e) Thanks [@threepointone](https://github.com/threepointone)! - update dependencies
|
|
62
|
-
|
|
63
|
-
- Updated dependencies [[`cf8a1e7`](https://github.com/cloudflare/agents/commit/cf8a1e7a24ecaac62c2aefca7b0fd5bf1373e8bd), [`87dc96d`](https://github.com/cloudflare/agents/commit/87dc96d19de1d26dbb2badecbb9955a4eb8e9e2e)]:
|
|
64
|
-
- agents@0.3.4
|
|
65
|
-
|
|
66
|
-
## 0.0.3
|
|
67
|
-
|
|
68
|
-
### Patch Changes
|
|
69
|
-
|
|
70
|
-
- [`a5d0137`](https://github.com/cloudflare/agents/commit/a5d01379b9ad2d88bc028c50f1858b4e69f106c5) Thanks [@threepointone](https://github.com/threepointone)! - trigger a new release
|
|
71
|
-
|
|
72
|
-
- Updated dependencies [[`a5d0137`](https://github.com/cloudflare/agents/commit/a5d01379b9ad2d88bc028c50f1858b4e69f106c5)]:
|
|
73
|
-
- agents@0.3.3
|
|
74
|
-
|
|
75
|
-
## 0.0.2
|
|
76
|
-
|
|
77
|
-
### Patch Changes
|
|
78
|
-
|
|
79
|
-
- [#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
|
|
80
|
-
|
|
81
|
-
Extract @cloudflare/ai-chat and @cloudflare/codemode into their own packages
|
|
82
|
-
with comprehensive READMEs. Update agents README to remove chat-specific
|
|
83
|
-
content and point to new packages. Fix documentation imports to reflect
|
|
84
|
-
new package structure.
|
|
85
|
-
|
|
86
|
-
Maintains backward compatibility, no breaking changes.
|
|
87
|
-
|
|
88
|
-
- Updated dependencies [[`0c4275f`](https://github.com/cloudflare/agents/commit/0c4275f8f4b71c264c32c3742d151ef705739c2f), [`f12553f`](https://github.com/cloudflare/agents/commit/f12553f2fa65912c68d9a7620b9a11b70b8790a2)]:
|
|
89
|
-
- agents@0.3.2
|
package/dist/types-B9g5T2nd.js
DELETED
|
@@ -1,138 +0,0 @@
|
|
|
1
|
-
import { createAuxiliaryTypeStore, createTypeAlias, printNode, zodToTs } from "zod-to-ts";
|
|
2
|
-
|
|
3
|
-
//#region src/types.ts
|
|
4
|
-
const JS_RESERVED = new Set([
|
|
5
|
-
"abstract",
|
|
6
|
-
"arguments",
|
|
7
|
-
"await",
|
|
8
|
-
"boolean",
|
|
9
|
-
"break",
|
|
10
|
-
"byte",
|
|
11
|
-
"case",
|
|
12
|
-
"catch",
|
|
13
|
-
"char",
|
|
14
|
-
"class",
|
|
15
|
-
"const",
|
|
16
|
-
"continue",
|
|
17
|
-
"debugger",
|
|
18
|
-
"default",
|
|
19
|
-
"delete",
|
|
20
|
-
"do",
|
|
21
|
-
"double",
|
|
22
|
-
"else",
|
|
23
|
-
"enum",
|
|
24
|
-
"eval",
|
|
25
|
-
"export",
|
|
26
|
-
"extends",
|
|
27
|
-
"false",
|
|
28
|
-
"final",
|
|
29
|
-
"finally",
|
|
30
|
-
"float",
|
|
31
|
-
"for",
|
|
32
|
-
"function",
|
|
33
|
-
"goto",
|
|
34
|
-
"if",
|
|
35
|
-
"implements",
|
|
36
|
-
"import",
|
|
37
|
-
"in",
|
|
38
|
-
"instanceof",
|
|
39
|
-
"int",
|
|
40
|
-
"interface",
|
|
41
|
-
"let",
|
|
42
|
-
"long",
|
|
43
|
-
"native",
|
|
44
|
-
"new",
|
|
45
|
-
"null",
|
|
46
|
-
"package",
|
|
47
|
-
"private",
|
|
48
|
-
"protected",
|
|
49
|
-
"public",
|
|
50
|
-
"return",
|
|
51
|
-
"short",
|
|
52
|
-
"static",
|
|
53
|
-
"super",
|
|
54
|
-
"switch",
|
|
55
|
-
"synchronized",
|
|
56
|
-
"this",
|
|
57
|
-
"throw",
|
|
58
|
-
"throws",
|
|
59
|
-
"transient",
|
|
60
|
-
"true",
|
|
61
|
-
"try",
|
|
62
|
-
"typeof",
|
|
63
|
-
"undefined",
|
|
64
|
-
"var",
|
|
65
|
-
"void",
|
|
66
|
-
"volatile",
|
|
67
|
-
"while",
|
|
68
|
-
"with",
|
|
69
|
-
"yield"
|
|
70
|
-
]);
|
|
71
|
-
/**
|
|
72
|
-
* Sanitize a tool name into a valid JavaScript identifier.
|
|
73
|
-
* Replaces hyphens, dots, and spaces with `_`, strips other invalid chars,
|
|
74
|
-
* prefixes digit-leading names with `_`, and appends `_` to JS reserved words.
|
|
75
|
-
*/
|
|
76
|
-
function sanitizeToolName(name) {
|
|
77
|
-
if (!name) return "_";
|
|
78
|
-
let sanitized = name.replace(/[-.\s]/g, "_");
|
|
79
|
-
sanitized = sanitized.replace(/[^a-zA-Z0-9_$]/g, "");
|
|
80
|
-
if (!sanitized) return "_";
|
|
81
|
-
if (/^[0-9]/.test(sanitized)) sanitized = "_" + sanitized;
|
|
82
|
-
if (JS_RESERVED.has(sanitized)) sanitized = sanitized + "_";
|
|
83
|
-
return sanitized;
|
|
84
|
-
}
|
|
85
|
-
function toCamelCase(str) {
|
|
86
|
-
return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()).replace(/^[a-z]/, (letter) => letter.toUpperCase());
|
|
87
|
-
}
|
|
88
|
-
/**
|
|
89
|
-
* Extract field descriptions from a Zod object schema's `.shape`, if available.
|
|
90
|
-
* Returns an array of `@param input.fieldName - description` lines.
|
|
91
|
-
*/
|
|
92
|
-
function extractParamDescriptions(schema) {
|
|
93
|
-
const descriptions = [];
|
|
94
|
-
const shape = schema.shape;
|
|
95
|
-
if (!shape || typeof shape !== "object") return descriptions;
|
|
96
|
-
for (const [fieldName, fieldSchema] of Object.entries(shape)) {
|
|
97
|
-
const desc = fieldSchema.description;
|
|
98
|
-
if (desc) descriptions.push(`@param input.${fieldName} - ${desc}`);
|
|
99
|
-
}
|
|
100
|
-
return descriptions;
|
|
101
|
-
}
|
|
102
|
-
/**
|
|
103
|
-
* Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.
|
|
104
|
-
* These types can be included in tool descriptions to help LLMs write correct code.
|
|
105
|
-
*/
|
|
106
|
-
function generateTypes(tools) {
|
|
107
|
-
let availableTools = "";
|
|
108
|
-
let availableTypes = "";
|
|
109
|
-
const auxiliaryTypeStore = createAuxiliaryTypeStore();
|
|
110
|
-
for (const [toolName, tool] of Object.entries(tools)) {
|
|
111
|
-
const inputSchema = "inputSchema" in tool ? tool.inputSchema : tool.parameters;
|
|
112
|
-
const outputSchema = "outputSchema" in tool ? tool.outputSchema : void 0;
|
|
113
|
-
const description = tool.description;
|
|
114
|
-
const safeName = sanitizeToolName(toolName);
|
|
115
|
-
const inputType = printNode(createTypeAlias(zodToTs(inputSchema, { auxiliaryTypeStore }).node, `${toCamelCase(safeName)}Input`));
|
|
116
|
-
const outputType = outputSchema ? printNode(createTypeAlias(zodToTs(outputSchema, { auxiliaryTypeStore }).node, `${toCamelCase(safeName)}Output`)) : `type ${toCamelCase(safeName)}Output = unknown`;
|
|
117
|
-
availableTypes += `\n${inputType.trim()}`;
|
|
118
|
-
availableTypes += `\n${outputType.trim()}`;
|
|
119
|
-
const paramDescs = extractParamDescriptions(inputSchema);
|
|
120
|
-
const jsdocLines = [];
|
|
121
|
-
if (description?.trim()) jsdocLines.push(description.trim());
|
|
122
|
-
else jsdocLines.push(toolName);
|
|
123
|
-
for (const pd of paramDescs) jsdocLines.push(pd);
|
|
124
|
-
const jsdocBody = jsdocLines.map((l) => `\t * ${l}`).join("\n");
|
|
125
|
-
availableTools += `\n\t/**\n${jsdocBody}\n\t */`;
|
|
126
|
-
availableTools += `\n\t${safeName}: (input: ${toCamelCase(safeName)}Input) => Promise<${toCamelCase(safeName)}Output>;`;
|
|
127
|
-
availableTools += "\n";
|
|
128
|
-
}
|
|
129
|
-
availableTools = `\ndeclare const codemode: {${availableTools}}`;
|
|
130
|
-
return `
|
|
131
|
-
${availableTypes}
|
|
132
|
-
${availableTools}
|
|
133
|
-
`.trim();
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
//#endregion
|
|
137
|
-
export { sanitizeToolName as n, generateTypes as t };
|
|
138
|
-
//# sourceMappingURL=types-B9g5T2nd.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types-B9g5T2nd.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\";\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 Zod object schema's `.shape`, if available.\n * Returns an array of `@param input.fieldName - description` lines.\n */\nfunction extractParamDescriptions(schema: ZodType): string[] {\n const descriptions: string[] = [];\n const shape = (schema as { shape?: Record<string, ZodType> }).shape;\n if (!shape || typeof shape !== \"object\") return descriptions;\n\n for (const [fieldName, fieldSchema] of Object.entries(shape)) {\n const desc = (fieldSchema as { description?: string }).description;\n if (desc) {\n descriptions.push(`@param input.${fieldName} - ${desc}`);\n }\n }\n return descriptions;\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 * 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 // Handle both our ToolDescriptor and AI SDK Tool types\n const inputSchema =\n \"inputSchema\" in tool ? tool.inputSchema : tool.parameters;\n const outputSchema = \"outputSchema\" in tool ? tool.outputSchema : undefined;\n const description = tool.description;\n\n const safeName = sanitizeToolName(toolName);\n\n const inputType = printNodeZodToTs(\n createTypeAlias(\n zodToTs(inputSchema as ZodType, { auxiliaryTypeStore }).node,\n `${toCamelCase(safeName)}Input`\n )\n );\n\n const outputType = outputSchema\n ? printNodeZodToTs(\n createTypeAlias(\n zodToTs(outputSchema as ZodType, { auxiliaryTypeStore }).node,\n `${toCamelCase(safeName)}Output`\n )\n )\n : `type ${toCamelCase(safeName)}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 = extractParamDescriptions(inputSchema as ZodType);\n const jsdocLines: string[] = [];\n if (description?.trim()) {\n jsdocLines.push(description.trim());\n } else {\n jsdocLines.push(toolName);\n }\n for (const pd of paramDescs) {\n jsdocLines.push(pd);\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: ${toCamelCase(safeName)}Input) => Promise<${toCamelCase(safeName)}Output>;`;\n availableTools += \"\\n\";\n }\n\n availableTools = `\\ndeclare const codemode: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n"],"mappings":";;;AASA,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,UAAU,QAAQ,mBAAmB,GAAG;AAEpD,KAAI,CAAC,UAAW,QAAO;AAGvB,KAAI,SAAS,KAAK,UAAU,CAC1B,aAAY,MAAM;AAIpB,KAAI,YAAY,IAAI,UAAU,CAC5B,aAAY,YAAY;AAG1B,QAAO;;AAGT,SAAS,YAAY,KAAa;AAChC,QAAO,IACJ,QAAQ,cAAc,GAAG,WAAW,OAAO,aAAa,CAAC,CACzD,QAAQ,WAAW,WAAW,OAAO,aAAa,CAAC;;;;;;AAOxD,SAAS,yBAAyB,QAA2B;CAC3D,MAAM,eAAyB,EAAE;CACjC,MAAM,QAAS,OAA+C;AAC9D,KAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAEhD,MAAK,MAAM,CAAC,WAAW,gBAAgB,OAAO,QAAQ,MAAM,EAAE;EAC5D,MAAM,OAAQ,YAAyC;AACvD,MAAI,KACF,cAAa,KAAK,gBAAgB,UAAU,KAAK,OAAO;;AAG5D,QAAO;;;;;;AAgBT,SAAgB,cAAc,OAA0C;CACtE,IAAI,iBAAiB;CACrB,IAAI,iBAAiB;CAErB,MAAM,qBAAqB,0BAA0B;AAErD,MAAK,MAAM,CAAC,UAAU,SAAS,OAAO,QAAQ,MAAM,EAAE;EAEpD,MAAM,cACJ,iBAAiB,OAAO,KAAK,cAAc,KAAK;EAClD,MAAM,eAAe,kBAAkB,OAAO,KAAK,eAAe;EAClE,MAAM,cAAc,KAAK;EAEzB,MAAM,WAAW,iBAAiB,SAAS;EAE3C,MAAM,YAAYA,UAChB,gBACE,QAAQ,aAAwB,EAAE,oBAAoB,CAAC,CAAC,MACxD,GAAG,YAAY,SAAS,CAAC,OAC1B,CACF;EAED,MAAM,aAAa,eACfA,UACE,gBACE,QAAQ,cAAyB,EAAE,oBAAoB,CAAC,CAAC,MACzD,GAAG,YAAY,SAAS,CAAC,QAC1B,CACF,GACD,QAAQ,YAAY,SAAS,CAAC;AAElC,oBAAkB,KAAK,UAAU,MAAM;AACvC,oBAAkB,KAAK,WAAW,MAAM;EAGxC,MAAM,aAAa,yBAAyB,YAAuB;EACnE,MAAM,aAAuB,EAAE;AAC/B,MAAI,aAAa,MAAM,CACrB,YAAW,KAAK,YAAY,MAAM,CAAC;MAEnC,YAAW,KAAK,SAAS;AAE3B,OAAK,MAAM,MAAM,WACf,YAAW,KAAK,GAAG;EAGrB,MAAM,YAAY,WAAW,KAAK,MAAM,QAAQ,IAAI,CAAC,KAAK,KAAK;AAC/D,oBAAkB,YAAY,UAAU;AACxC,oBAAkB,OAAO,SAAS,YAAY,YAAY,SAAS,CAAC,oBAAoB,YAAY,SAAS,CAAC;AAC9G,oBAAkB;;AAGpB,kBAAiB,8BAA8B,eAAe;AAE9D,QAAO;EACP,eAAe;EACf,eAAe;IACb,MAAM"}
|
package/e2e/codemode.spec.ts
DELETED
|
@@ -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
|
-
});
|
package/e2e/playwright.config.ts
DELETED
|
@@ -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
|
-
};
|
package/e2e/wrangler.jsonc
DELETED
|
@@ -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";
|