@cloudflare/codemode 0.4.1 → 0.4.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/README.md +13 -11
- package/dist/ai.d.ts +2 -2
- package/dist/ai.js +3 -3
- package/dist/{base-CHRR_a5j.js → base-BqhlNCSH.js} +2 -2
- package/dist/{base-CHRR_a5j.js.map → base-BqhlNCSH.js.map} +1 -1
- package/dist/browser.d.ts +2 -2
- package/dist/browser.js +4 -4
- package/dist/browser.js.map +1 -1
- package/dist/{executor-BIs2dr7X.d.ts → executor-DkMGH_7-.d.ts} +2 -2
- package/dist/index.d.ts +54 -12
- package/dist/index.js +79 -27
- package/dist/index.js.map +1 -1
- package/dist/{json-schema-types-BGjW4KPy.js → json-schema-types-D_m9tVnI.js} +2 -2
- package/dist/{json-schema-types-BGjW4KPy.js.map → json-schema-types-D_m9tVnI.js.map} +1 -1
- package/dist/mcp.d.ts +35 -2
- package/dist/mcp.js +3 -3
- package/dist/mcp.js.map +1 -1
- package/dist/{resolve-CBr_VoPl.d.ts → resolve-tqDt6Djo.d.ts} +2 -2
- package/dist/{run-code-aKHcTgf9.js → run-code-Q3Jh6Dcu.js} +2 -2
- package/dist/{run-code-aKHcTgf9.js.map → run-code-Q3Jh6Dcu.js.map} +1 -1
- package/dist/{shared-Ce-zCEBP.d.ts → shared-BOF2IKt-.d.ts} +2 -2
- package/dist/tanstack-ai.d.ts +3 -3
- package/dist/tanstack-ai.js +2 -2
- package/dist/vite.js +19 -91
- package/dist/vite.js.map +1 -1
- package/docs/approvals.md +169 -0
- package/docs/connectors.md +343 -0
- package/docs/index.md +192 -0
- package/docs/runtime.md +263 -0
- package/docs/snippets.md +96 -0
- package/docs/vite-plugin.md +60 -0
- package/package.json +22 -4
package/docs/index.md
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
# Codemode
|
|
2
|
+
|
|
3
|
+
Codemode lets a model use external systems by **writing TypeScript** instead of making individual tool calls. The model gets one tool — `codemode({ code })` — that executes its code in a sandboxed Worker. Inside the sandbox, every integration the developer configured is available as a typed global, and a four-method platform SDK handles discovery, side effects, and reuse.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
// the developer configures this
|
|
7
|
+
const runtime = createCodemodeRuntime({ ctx, executor, connectors });
|
|
8
|
+
tools: {
|
|
9
|
+
codemode: runtime.tool();
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// the model writes this
|
|
13
|
+
const matches = await codemode.search("pull request");
|
|
14
|
+
const docs = await codemode.describe(matches.results[0].path);
|
|
15
|
+
const prs = await github.list_pull_requests({
|
|
16
|
+
owner: "cloudflare",
|
|
17
|
+
repo: "agents"
|
|
18
|
+
});
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Why we think this is a good idea
|
|
22
|
+
|
|
23
|
+
**Tool descriptions don't scale.** The classic approach generates types for every tool and puts them all in the tool description. Ten tools is fine; a GitHub MCP server plus a Stripe spec plus an internal API is thousands of prompt tokens the model pays for on every request, mostly for tools it won't call. Codemode moves discovery _inside the sandbox_: `codemode.search` and `codemode.describe` return results into the running code, not into the context window. The model pulls exactly the type information it needs, when it needs it.
|
|
24
|
+
|
|
25
|
+
**Models are better at code than at tool protocols.** Filtering, joining, retrying, looping over pages — in tool-call style each step is a round trip through the model. In code it's just code: the model fetches an OpenAPI spec _as data_ and writes its own three-line lookup instead of us shipping a search endpoint. One sandbox run can do what would otherwise take a dozen tool calls.
|
|
26
|
+
|
|
27
|
+
**Real work needs durable state.** Creating issues, sending messages, merging PRs — these need human approval, an audit trail, and sometimes an undo. Those concerns have one home, the runtime, instead of being rebuilt per app. The model's code pauses at an approval-required call and continues after approval as if nothing happened.
|
|
28
|
+
|
|
29
|
+
## The pieces
|
|
30
|
+
|
|
31
|
+
| Piece | What it is | State |
|
|
32
|
+
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------- |
|
|
33
|
+
| **Executor** | Runs a block of code once in an isolated sandbox (`DynamicWorkerExecutor` on Workers, `IframeSandboxExecutor` in the browser) | None — deliberately stateless and replaceable |
|
|
34
|
+
| **Connectors** | Classes that bridge an external service (MCP server, OpenAPI spec, AI SDK toolset, anything custom) into the sandbox as a global | Own their connection/credentials |
|
|
35
|
+
| **Runtime** | The thing you hold onto: `runtime.tool()` for the model, `pending`/`approve`/`reject`/`rollback` for your app, a durable log behind it | Durable — survives hibernation |
|
|
36
|
+
|
|
37
|
+
The sandbox has **no network access**. Model code cannot `fetch`; every effect goes through a connector (which routes through the runtime's log) or through `codemode.step`.
|
|
38
|
+
|
|
39
|
+
## Configure it (developer)
|
|
40
|
+
|
|
41
|
+
**1. Add the Vite plugin** — it exports the runtime facet class that `createCodemodeRuntime()` needs:
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
// vite.config.ts
|
|
45
|
+
import codemode from "@cloudflare/codemode/vite";
|
|
46
|
+
import agents from "agents/vite";
|
|
47
|
+
import { cloudflare } from "@cloudflare/vite-plugin";
|
|
48
|
+
|
|
49
|
+
export default { plugins: [agents(), codemode(), cloudflare()] };
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
**2. Write a connector** — a class per service. Mark only the tools that need a human; everything else executes immediately:
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
// github.codemode.ts
|
|
56
|
+
import {
|
|
57
|
+
McpConnector,
|
|
58
|
+
type McpConnectionLike,
|
|
59
|
+
type ConnectorTool
|
|
60
|
+
} from "@cloudflare/codemode";
|
|
61
|
+
|
|
62
|
+
export class GithubConnector extends McpConnector<Env> {
|
|
63
|
+
constructor(
|
|
64
|
+
ctx: ExecutionContext,
|
|
65
|
+
env: Env,
|
|
66
|
+
private conn: McpConnectionLike
|
|
67
|
+
) {
|
|
68
|
+
super(ctx, env);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
name() {
|
|
72
|
+
return "github";
|
|
73
|
+
}
|
|
74
|
+
protected instructions() {
|
|
75
|
+
return "Use for GitHub repositories, issues, and pull requests.";
|
|
76
|
+
}
|
|
77
|
+
protected createConnection() {
|
|
78
|
+
return this.conn;
|
|
79
|
+
}
|
|
80
|
+
protected tool(name: string, t: ConnectorTool): ConnectorTool {
|
|
81
|
+
return name === "create_issue" ? { ...t, requiresApproval: true } : t;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
**3. Create a runtime in your agent** and hand the model `runtime.tool()`. Approval handling is two `@callable` methods:
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
// server.ts
|
|
90
|
+
import {
|
|
91
|
+
createCodemodeRuntime,
|
|
92
|
+
DynamicWorkerExecutor
|
|
93
|
+
} from "@cloudflare/codemode";
|
|
94
|
+
import { GithubConnector } from "./github.codemode";
|
|
95
|
+
|
|
96
|
+
export class Chat extends AIChatAgent<Env> {
|
|
97
|
+
codemode() {
|
|
98
|
+
const conn = this.mcp.mcpConnections[this.githubServerId];
|
|
99
|
+
return createCodemodeRuntime({
|
|
100
|
+
ctx: this.ctx,
|
|
101
|
+
executor: new DynamicWorkerExecutor({ loader: this.env.LOADER }),
|
|
102
|
+
connectors: [
|
|
103
|
+
new GithubConnector(
|
|
104
|
+
this.ctx as unknown as ExecutionContext,
|
|
105
|
+
this.env,
|
|
106
|
+
conn
|
|
107
|
+
)
|
|
108
|
+
]
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async onChatMessage() {
|
|
113
|
+
return streamText({
|
|
114
|
+
model,
|
|
115
|
+
messages: await convertToModelMessages(this.messages),
|
|
116
|
+
tools: { codemode: this.codemode().tool() }
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
@callable()
|
|
121
|
+
listPending() {
|
|
122
|
+
return this.codemode().pending();
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
@callable()
|
|
126
|
+
approve(executionId?: string) {
|
|
127
|
+
return this.codemode().approve({ executionId });
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// e.g. a "save this script" button after a run the user liked
|
|
131
|
+
@callable()
|
|
132
|
+
saveSnippet(name: string, executionId?: string) {
|
|
133
|
+
return this.codemode().saveSnippet(name, { executionId });
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
That's the whole developer surface: a connector class, `createCodemodeRuntime`, and the runtime handle. The handle is the control plane — `tool()` for the model, `pending()`/`approve()`/`reject()`/`rollback()` for approvals, `executions()` for the audit trail, and `saveSnippet()`/`snippets()`/`deleteSnippet()` for curating what the model gets to reuse.
|
|
139
|
+
|
|
140
|
+
## Use it (what the model writes)
|
|
141
|
+
|
|
142
|
+
The sandbox SDK is four methods — discover, learn, do-once, reuse — plus one global per connector:
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
async () => {
|
|
146
|
+
// discover: ranked search over connector methods and saved snippets
|
|
147
|
+
const matches = await codemode.search("open pull requests");
|
|
148
|
+
|
|
149
|
+
// learn: TypeScript docs for one method — fetched on demand, not pre-dumped
|
|
150
|
+
const docs = await codemode.describe(matches.results[0].path);
|
|
151
|
+
|
|
152
|
+
// act: connector methods are typed globals
|
|
153
|
+
const prs = await github.list_pull_requests({
|
|
154
|
+
owner: "cloudflare",
|
|
155
|
+
repo: "agents",
|
|
156
|
+
state: "open"
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
// do-once: anything nondeterministic goes in a step so replay is exact
|
|
160
|
+
const stamp = await codemode.step("now", () => Date.now());
|
|
161
|
+
|
|
162
|
+
return { count: prs.length, stamp };
|
|
163
|
+
};
|
|
164
|
+
// reuse: once the developer promotes a run with runtime.saveSnippet("open-prs"),
|
|
165
|
+
// the model finds it via codemode.search and re-runs it by name:
|
|
166
|
+
const prs = await codemode.run("open-prs", {
|
|
167
|
+
owner: "cloudflare",
|
|
168
|
+
repo: "agents"
|
|
169
|
+
});
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
When the code hits an approval-required method (`github.create_issue`), the run pauses and the tool returns `{ status: "paused", executionId, pending }`. After `runtime.approve({ executionId })`, the same code re-runs: completed calls replay from the durable log, the approved action executes for real, and the script continues — the model never writes pause/resume logic.
|
|
173
|
+
|
|
174
|
+
## How the code actually runs
|
|
175
|
+
|
|
176
|
+
`runtime.tool()` builds the sandbox per run: it spawns the durable runtime facet on your agent's Durable Object, exposes each connector as an RPC-backed global, injects the `codemode` SDK, and hands the code to the executor. Every connector call routes through the runtime first — replay it, execute it, or pause — so the durable log is always the source of truth:
|
|
177
|
+
|
|
178
|
+
```
|
|
179
|
+
sandbox: github.create_issue(args)
|
|
180
|
+
→ runtime.decide("github", "create_issue", args) // replay | execute | pause
|
|
181
|
+
→ GithubConnector.executeTool(...) // only on execute
|
|
182
|
+
→ runtime.recordResult(...) // logged for replay/audit
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
## Docs
|
|
186
|
+
|
|
187
|
+
- [Using Codemode with Agents and AI SDK tools](https://github.com/cloudflare/agents/blob/main/docs/agents/codemode.md) — turn tool sets into a single sandboxed code tool
|
|
188
|
+
- [Connectors](./connectors.md) — write one class per service; MCP, OpenAPI, toolset, and custom bases
|
|
189
|
+
- [Runtime](./runtime.md) — both API surfaces (handle + sandbox SDK), the durable log, abort-and-replay
|
|
190
|
+
- [Approvals](./approvals.md) — annotations, pause/resume flow, wiring an approval UI
|
|
191
|
+
- [Snippets](./snippets.md) — scripts the model saves and reuses
|
|
192
|
+
- [Vite Plugin](./vite-plugin.md) — auto-export the `CodemodeRuntime` facet class
|
package/docs/runtime.md
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
# Runtime
|
|
2
|
+
|
|
3
|
+
The **Executor** is a simple, stateless sandbox: it runs a block of code once and dispatches tool calls back. The **Runtime** wraps an executor and makes execution durable.
|
|
4
|
+
|
|
5
|
+
**Why this exists:** approvals can take minutes or hours, and agents hibernate. A model may write a script that reads data, asks to create an issue, and continues after the user approves — possibly in a different request, after the Durable Object restarted. That needs durable state, which cannot live in the executor or in a single request. The runtime is where it lives.
|
|
6
|
+
|
|
7
|
+
The public runtime handle owns the executor and connectors for the current request. `CodemodeRuntime` is the DurableObject facet behind that handle. It owns the durable state: the tool-call log, pending approvals, and snippets.
|
|
8
|
+
|
|
9
|
+
## Configure
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import {
|
|
13
|
+
createCodemodeRuntime,
|
|
14
|
+
DynamicWorkerExecutor
|
|
15
|
+
} from "@cloudflare/codemode";
|
|
16
|
+
|
|
17
|
+
const runtime = createCodemodeRuntime({
|
|
18
|
+
ctx: this.ctx, // the agent's DurableObjectState
|
|
19
|
+
executor: new DynamicWorkerExecutor({ loader: this.env.LOADER }),
|
|
20
|
+
connectors: [github, repoApi]
|
|
21
|
+
});
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
| Handle method | Purpose |
|
|
25
|
+
| ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
26
|
+
| `runtime.tool(options?)` | The single model-facing AI SDK tool, `codemode({ code })` |
|
|
27
|
+
| `runtime.pending(executionId?)` | Actions awaiting approval — drives approval UIs; no id aggregates all paused runs |
|
|
28
|
+
| `runtime.approve({ executionId })` | Approve the pending action and continue via replay |
|
|
29
|
+
| `runtime.reject({ seq, executionId })` | Reject a pending action; ends the execution. Returns `false` if it was a no-op (action no longer pending — approved or rejected elsewhere) |
|
|
30
|
+
| `runtime.rollback({ executionId })` | Revert applied actions in reverse order via each tool's `revert` |
|
|
31
|
+
| `runtime.expirePaused({ maxAgeMs? })` | Expire stale awaiting-approval runs and reclaim their resources |
|
|
32
|
+
| `runtime.executions(limit?)` | All executions, newest first — the audit trail for developer UIs |
|
|
33
|
+
| `runtime.deleteExecution(id)` / `pruneExecutions(n)` | Drop one execution / keep only the newest N terminal ones |
|
|
34
|
+
| `runtime.saveSnippet(name, opts?)` | Promote an execution's script to a reusable [snippet](./snippets.md) |
|
|
35
|
+
| `runtime.snippets()` / `runtime.deleteSnippet(name)` | List / remove saved snippets |
|
|
36
|
+
|
|
37
|
+
## The sandbox API (`codemode.*`)
|
|
38
|
+
|
|
39
|
+
The runtime also provides the model's API. Inside the sandbox, `codemode` is a global with four methods — discover, learn, do-once, reuse:
|
|
40
|
+
|
|
41
|
+
| Sandbox method | Purpose |
|
|
42
|
+
| ---------------------------- | ------------------------------------------------------------------------ |
|
|
43
|
+
| `codemode.search(query)` | Ranked search across connector methods and saved snippets |
|
|
44
|
+
| `codemode.describe(target)` | TypeScript docs for a connector, method, or snippet — fetched on demand |
|
|
45
|
+
| `codemode.step(name, fn)` | Run a side-effectful or nondeterministic closure once; replay its result |
|
|
46
|
+
| `codemode.run(name, input?)` | Run a [snippet](./snippets.md) the developer saved |
|
|
47
|
+
|
|
48
|
+
Connector methods appear next to it as their own globals (`github.list_pull_requests(...)`).
|
|
49
|
+
|
|
50
|
+
**Why discovery lives in the sandbox:** the alternative is generating types for every tool and putting them all in the tool description, which floods the context as the tool count grows. `search` and `describe` return results **into the running code**, not into the prompt — the model pays for exactly the type information it asks for.
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
const matches = await codemode.search("pull request");
|
|
54
|
+
// { results: [{ path: "github.list_pull_requests", kind: "method", score: 145 }, ...], total, truncated }
|
|
55
|
+
|
|
56
|
+
const docs = await codemode.describe("github.list_pull_requests");
|
|
57
|
+
// { path, description, types: "type ListPullRequestsInput = { owner: string; ... }", kind: "method" }
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
`describe` works on a connector (`"github"`), a method (`"github.list_pull_requests"`), or a snippet name. Search ranks with executor-style matching: names are normalized (`camelCase`/`snake_case`/dots split into tokens), fields are scored by weight (path 12, method 10, connector 8, description 5) with bonuses for exact/prefix/phrase matches, and results are capped at 50 — when `truncated` is true the model should search again with a more specific query.
|
|
61
|
+
|
|
62
|
+
`codemode.step` is the explicit side-effect boundary that makes [abort-and-replay](#abort-and-replay) correct: the closure runs inside the sandbox, the result is recorded in the log, and on replay the closure is skipped.
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
const id = await codemode.step("gen-id", () => crypto.randomUUID());
|
|
66
|
+
const data = await codemode.step("fetch", async () =>
|
|
67
|
+
(await fetch(url)).json()
|
|
68
|
+
);
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Executor vs Runtime
|
|
72
|
+
|
|
73
|
+
| | Executor | Runtime |
|
|
74
|
+
| -------- | ------------------------------------------------ | ---------------------------------------- |
|
|
75
|
+
| What | Code sandbox | Durable execution engine |
|
|
76
|
+
| Lifetime | One `execute()` call | Whole conversation (DO facet) |
|
|
77
|
+
| State | None | Tool-call log, pending actions, snippets |
|
|
78
|
+
| Examples | `DynamicWorkerExecutor`, `IframeSandboxExecutor` | `CodemodeRuntime` |
|
|
79
|
+
|
|
80
|
+
The executor runs code. The runtime wraps the executor and adds durability, approvals, rollback, and state.
|
|
81
|
+
|
|
82
|
+
## Abort and replay
|
|
83
|
+
|
|
84
|
+
The core mechanism. When the model's code runs, every tool call is recorded in a durable log:
|
|
85
|
+
|
|
86
|
+
1. **Read** (no annotation) → executes, result recorded in the log.
|
|
87
|
+
2. **Approval-required action** → recorded as `pending`, and the run **aborts**.
|
|
88
|
+
3. On **continue** → the same code re-runs. Every call already in the log is served from it (a noop replay — reads return their recorded result, applied actions return theirs). The newly-approved action executes for real. The run proceeds to the next pause or to completion.
|
|
89
|
+
|
|
90
|
+
```
|
|
91
|
+
run 1: search() ──exec──> "results" [logged: applied]
|
|
92
|
+
list_prs() ──exec──> [pr1, pr2] [logged: applied]
|
|
93
|
+
create_issue() ──PAUSE── [logged: pending]
|
|
94
|
+
✗ run aborts
|
|
95
|
+
|
|
96
|
+
user approves
|
|
97
|
+
|
|
98
|
+
run 2: search() ──replay──> "results" (from log, no re-exec)
|
|
99
|
+
list_prs() ──replay──> [pr1, pr2] (from log, no re-exec)
|
|
100
|
+
create_issue() ──exec──> { number } (approved, runs for real)
|
|
101
|
+
post_comment() ──exec──> ok (continues)
|
|
102
|
+
✓ run completes
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
The log is the replay spine. Everything — replay, rollback, audit — reads off it.
|
|
106
|
+
|
|
107
|
+
## Determinism requirement
|
|
108
|
+
|
|
109
|
+
Replay only works if the code is **deterministic up to tool calls**. The Nth tool call on run 1 must be the Nth tool call on run 2, with the same arguments. If the code branches on `Math.random()` or `Date.now()` in a way that changes which tools it calls — or passes nondeterministic values as arguments to an approval-gated action — replay diverges. The runtime detects this (the connector/method differs, or the stably-stringified arguments differ from the recorded call), records the execution as failed, and the tool returns an error result rather than throwing:
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
{
|
|
113
|
+
status: "error",
|
|
114
|
+
executionId: "exec_...",
|
|
115
|
+
error: "Codemode replay divergence at step 2: arguments changed since the original run. Wrap nondeterministic work in codemode.step()."
|
|
116
|
+
}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Returning the divergence as data (instead of throwing across the RPC boundary) keeps the agent loop intact and lets the model self-correct. To make nondeterministic work replay-safe, wrap it in `codemode.step(name, fn)` so the value is captured once and replayed identically.
|
|
120
|
+
|
|
121
|
+
In practice, model-generated code is naturally deterministic — it fetches data, branches on the data (which is replayed identically), and calls tools. The constraint only bites if code uses nondeterministic sources to drive control flow or build action arguments.
|
|
122
|
+
|
|
123
|
+
**Issue tool calls sequentially.** The replay cursor assigns each call its sequence number when the call reaches the host, so `await a(); await b();` is stable across runs but `await Promise.all([a(), b()])` is not — the two calls can arrive in either order. On a run that never pauses this is harmless, but if such a run later pauses and resumes, the reordered calls trip divergence detection. Await connector calls one at a time in any run that might pause for approval.
|
|
124
|
+
|
|
125
|
+
## The tool-call log
|
|
126
|
+
|
|
127
|
+
```ts
|
|
128
|
+
type ToolLogEntry = {
|
|
129
|
+
seq: number;
|
|
130
|
+
connector: string;
|
|
131
|
+
method: string;
|
|
132
|
+
args: unknown;
|
|
133
|
+
result?: unknown; // recorded for replay (never for ephemeral entries)
|
|
134
|
+
requiresApproval: boolean;
|
|
135
|
+
ephemeral?: boolean; // replay: "reexecute" — re-runs instead of replaying
|
|
136
|
+
state: "executing" | "applied" | "pending" | "reverted";
|
|
137
|
+
};
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
A call is logged `executing` the moment the runtime decides to run it, and only flips to `applied` once its result is recorded. So a crash between those two points replays as a fresh execution (re-run) rather than replaying a missing result. Once a run pauses or terminates, every further call/step gets a pause decision and records nothing — model code that catches the pause and keeps going cannot apply extra effects.
|
|
141
|
+
|
|
142
|
+
The log lives in the facet's SQLite database — one row per entry, so recording a call appends a row instead of rewriting the whole execution.
|
|
143
|
+
|
|
144
|
+
The tool's output echoes the log on every outcome as `calls?: ToolLogEntry[]` (see [Tool output](./approvals.md#tool-output)), so a UI can render the run's audit trail directly from the tool result; `runtime.executions()` remains the durable source for past runs.
|
|
145
|
+
|
|
146
|
+
### Ephemeral entries
|
|
147
|
+
|
|
148
|
+
A tool can opt out of result recording with [`replay: "reexecute"`](./connectors.md#replay-policy). Its calls are still logged (for sequencing and divergence detection) but the result is never stored: a replay **re-executes** the call instead of replaying a recorded value. Use it for idempotent reads with large results — file contents, directory listings — that would otherwise bloat the durable log.
|
|
149
|
+
|
|
150
|
+
### Size limits
|
|
151
|
+
|
|
152
|
+
Any single recorded value (a call's arguments, a recorded result, the final result) is capped at 1 MB serialized (`MAX_DURABLE_VALUE_BYTES`). Truncating a logged value is never an option — replay would feed resumed code corrupted data — so an oversized argument or call result **fails the run** with a model-actionable error suggesting the data be written to a file/workspace and passed by reference. An oversized **final** result does not fail the run (replay never needs it): the run completes, the model receives the real value, and the audit trail stores a placeholder note.
|
|
153
|
+
|
|
154
|
+
## Rollback
|
|
155
|
+
|
|
156
|
+
Rollback walks the log backward and calls the `revert` of **every** applied action that has one — independent of `requiresApproval`. A non-approval write with a `revert` is still undone; an approval-gated action without a `revert` is not. `revert` (via `revertAction`) returns whether it actually reverted, and the runtime marks only those entries `reverted`:
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
protected tool(name: string, t: ConnectorTool): ConnectorTool {
|
|
160
|
+
if (name === "create_issue") {
|
|
161
|
+
return {
|
|
162
|
+
...t,
|
|
163
|
+
requiresApproval: true,
|
|
164
|
+
revert: async (_args, result) => {
|
|
165
|
+
const { number } = result as { number: number };
|
|
166
|
+
await this.closeIssue(number);
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
return t;
|
|
171
|
+
}
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
Tools without a `revert` are skipped (the user is told the action can't be auto-reverted). Reads are never reverted. `reject()` does **not** roll back — it only ends a paused execution (marking it `rejected`); call `rollback()` to undo actions already applied earlier in the run. Rollback attempts every revert even if one throws (failures are reported afterward rather than aborting the rest), and marks the execution `rolled_back` so the audit trail reflects that its effects were undone.
|
|
175
|
+
|
|
176
|
+
A terminal execution is one of `completed`, `error` (a thrown sandbox error or replay divergence), `rejected`, or `rolled_back`. These are exactly the statuses a connector's [`disposeExecution`](./connectors.md#per-execution-resources) hook fires for; `running` and `paused` are not terminal.
|
|
177
|
+
|
|
178
|
+
## Retention
|
|
179
|
+
|
|
180
|
+
The execution log is the audit trail, so it grows with every run. Terminal executions (completed or errored) are **auto-pruned** as new runs begin, keeping the newest `maxExecutions` (default 50). Running and paused executions are never pruned — an awaiting-approval run is always resumable.
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
const runtime = createCodemodeRuntime({
|
|
184
|
+
ctx,
|
|
185
|
+
executor,
|
|
186
|
+
connectors,
|
|
187
|
+
maxExecutions: 50 // cap on retained terminal executions
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
// Explicit controls
|
|
191
|
+
await runtime.executions(20); // newest first, optionally limited
|
|
192
|
+
await runtime.deleteExecution(id); // drop one (returns whether it existed)
|
|
193
|
+
await runtime.pruneExecutions(10); // keep only the newest N terminal runs
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
Because paused runs are exempt from pruning, an approval nobody ever answers would otherwise live forever — holding its log and any per-execution connector resources (a browser session, for example). `runtime.expirePaused({ maxAgeMs })` (default 24 hours) marks stale paused runs `rejected` and fires each connector's `disposeExecution`, reclaiming their resources. Call it from a recurring alarm or scheduled task:
|
|
197
|
+
|
|
198
|
+
```ts
|
|
199
|
+
// e.g. in a daily scheduled task
|
|
200
|
+
const expired = await runtime.expirePaused({ maxAgeMs: 24 * 60 * 60 * 1000 });
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
## Shaping results
|
|
204
|
+
|
|
205
|
+
A run's final result can be large enough to crowd the model's context. Pass `transformResult` to reshape the **model-facing** result of a completed run — most often to truncate it. It runs after the raw result is recorded, so the audit trail (`runtime.executions()`) keeps the full value while the model sees the shaped one. It applies on both the initial run and a resume after approval.
|
|
206
|
+
|
|
207
|
+
```ts
|
|
208
|
+
import { createCodemodeRuntime, truncateResult } from "@cloudflare/codemode";
|
|
209
|
+
|
|
210
|
+
const runtime = createCodemodeRuntime({
|
|
211
|
+
ctx,
|
|
212
|
+
executor,
|
|
213
|
+
connectors,
|
|
214
|
+
// Cap response size; small structured results pass through unchanged.
|
|
215
|
+
transformResult: (result) => truncateResult(result)
|
|
216
|
+
});
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
`truncateResult(value, options?)` returns the value unchanged when its serialized size is within budget, and a truncated string (with a marker noting the original size) when it isn't. `truncateResponse(text, options?)` is the string-only variant. Both take `{ maxChars?, maxTokens? }` (default ~6000 tokens).
|
|
220
|
+
|
|
221
|
+
`transformResult` shapes only the final returned value — individual connector results inside the run are unaffected, so the model's own code still sees full data to reason over.
|
|
222
|
+
|
|
223
|
+
## Snippets
|
|
224
|
+
|
|
225
|
+
The runtime also stores [snippets](./snippets.md) — durable, addressable scripts the developer promotes with `runtime.saveSnippet(name)` and the model re-runs with `codemode.run(name)`. They live here because the runtime is the natural home for accumulated state (unlike the executor and connectors, which are transient).
|
|
226
|
+
|
|
227
|
+
## Runtime identity
|
|
228
|
+
|
|
229
|
+
The runtime facet's identity is an explicit **name** (default `"default"`):
|
|
230
|
+
|
|
231
|
+
```ts
|
|
232
|
+
const runtime = createCodemodeRuntime({
|
|
233
|
+
ctx,
|
|
234
|
+
executor,
|
|
235
|
+
connectors,
|
|
236
|
+
name: "research" // optional — distinct names keep separate histories
|
|
237
|
+
});
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
The connector set is **data, not identity**: adding, removing, or renaming a connector does not address a different runtime, so executions and snippets survive connector changes. Staleness is handled with recorded requirements instead — every execution and snippet records the connector names it ran with, and:
|
|
241
|
+
|
|
242
|
+
- **Resuming** a paused run whose recorded connectors are no longer configured returns a clear error outcome (instead of diverging confusingly mid-replay).
|
|
243
|
+
- **Running a snippet** (`codemode.run`) whose recorded connectors are missing returns an error explaining which connector is absent.
|
|
244
|
+
|
|
245
|
+
Use distinct names when two runtimes should not share history (for example, two unrelated tools on the same agent).
|
|
246
|
+
|
|
247
|
+
The runtime handle keeps the same `ctx`, `executor`, `connectors`, and `name` together, so lifecycle calls address the same durable facet:
|
|
248
|
+
|
|
249
|
+
```ts
|
|
250
|
+
const runtime = createCodemodeRuntime({ ctx, executor, connectors });
|
|
251
|
+
await runtime.pending();
|
|
252
|
+
await runtime.approve({ executionId });
|
|
253
|
+
await runtime.reject({ seq, executionId });
|
|
254
|
+
await runtime.rollback({ executionId });
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
## Why a facet
|
|
258
|
+
|
|
259
|
+
The runtime is a DurableObject facet of the agent because:
|
|
260
|
+
|
|
261
|
+
- The log, snippets, and state must survive hibernation — approvals can take minutes or hours.
|
|
262
|
+
- The facet is durable; the executor and connector stubs are transient and re-provided per message.
|
|
263
|
+
- One named runtime facet owns the whole execution lifecycle, with its own isolated SQLite database.
|
package/docs/snippets.md
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# Snippets
|
|
2
|
+
|
|
3
|
+
A **snippet** is a saved sandbox script — a reusable pattern that already ran and worked. Snippets are durable: they live on the [Runtime](./runtime.md) facet, are addressable by name, and accumulate over time.
|
|
4
|
+
|
|
5
|
+
Connectors provide raw capability. Snippets are recipes that worked. The split is deliberate: **the model writes and reuses scripts; the developer decides which ones are worth keeping.** Promotion is a curation decision — wire it to a "save this script" button, an eval, or your own heuristics, not to the model's judgement.
|
|
6
|
+
|
|
7
|
+
## Lifecycle
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
// 1. The model writes and runs a script (one execution)
|
|
11
|
+
const prs = await github.list_pull_requests({ owner, repo, state: "open" });
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
// 2. The developer reviews the run and promotes it — e.g. from a @callable
|
|
16
|
+
const runs = await runtime.executions(); // newest first
|
|
17
|
+
await runtime.saveSnippet("list-open-prs", {
|
|
18
|
+
executionId: runs[0].id, // defaults to the current execution
|
|
19
|
+
description: "List open pull requests for a repository."
|
|
20
|
+
});
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
// 3. The model finds it via codemode.search and runs it by name
|
|
25
|
+
const prs = await codemode.run("list-open-prs");
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
`runtime.saveSnippet(name, options?)` snapshots **an execution's code** — by default the current one, or any past run via `executionId`. `runtime.snippets()` lists what's saved and `runtime.deleteSnippet(name)` removes it.
|
|
29
|
+
|
|
30
|
+
## Parameterised snippets
|
|
31
|
+
|
|
32
|
+
`codemode.run(name, input)` passes `input` to the snippet. If a snippet takes input, write it to accept an argument:
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
// saved as "list-open-prs"
|
|
36
|
+
async (input) => {
|
|
37
|
+
return await github.list_pull_requests({
|
|
38
|
+
owner: input.owner,
|
|
39
|
+
repo: input.repo,
|
|
40
|
+
state: "open"
|
|
41
|
+
});
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
// run it
|
|
45
|
+
const prs = await codemode.run("list-open-prs", {
|
|
46
|
+
owner: "cloudflare",
|
|
47
|
+
repo: "agents"
|
|
48
|
+
});
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Snippets with no input are written `async () => { ... }` and run with `codemode.run("name")`.
|
|
52
|
+
|
|
53
|
+
## Discovery
|
|
54
|
+
|
|
55
|
+
Once saved, snippets surface to the model alongside connector methods:
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
codemode.search("open pull requests"); // returns methods AND snippets (kind: "snippet")
|
|
59
|
+
codemode.describe("list-open-prs"); // returns the snippet's description + source
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## API
|
|
63
|
+
|
|
64
|
+
| Call | Who | Effect |
|
|
65
|
+
| ------------------------------------------------------------------------- | --------- | --------------------------------------------------------------- |
|
|
66
|
+
| `runtime.saveSnippet(name, { executionId?, description?, inputSchema? })` | Developer | Promote an execution's script to `name`. Returns the `Snippet`. |
|
|
67
|
+
| `runtime.snippets()` / `runtime.deleteSnippet(name)` | Developer | List / remove saved snippets. |
|
|
68
|
+
| `codemode.run(name, input?)` | Model | Run a saved snippet, optionally with input. |
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
interface Snippet {
|
|
72
|
+
name: string;
|
|
73
|
+
description: string;
|
|
74
|
+
code: string; // the saved script source
|
|
75
|
+
savedAt: number;
|
|
76
|
+
inputSchema?: unknown;
|
|
77
|
+
connectors?: string[]; // connector names the source execution ran with
|
|
78
|
+
}
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Snippets record their connector requirements
|
|
82
|
+
|
|
83
|
+
A snippet's code references connectors as globals (`github.list_pull_requests(...)`), so it is only valid when those connectors are configured. When an execution is promoted, the connector names it ran with carry over to the snippet. `codemode.run(name)` checks them against the runtime's current connector set and returns a clear error — naming the missing connector — instead of failing partway through the script.
|
|
84
|
+
|
|
85
|
+
This means the runtime can gain or lose connectors without orphaning its snippets (see [Runtime identity](./runtime.md#runtime-identity)): snippets whose requirements are still met keep working, and ones whose requirements are not are refused up front.
|
|
86
|
+
|
|
87
|
+
## Why durable and curated, not authored
|
|
88
|
+
|
|
89
|
+
Earlier designs passed in a static list of "skills" at construction. Snippets replace that:
|
|
90
|
+
|
|
91
|
+
- **Grown, not authored** — snippets come from real runs that worked, instead of a human pre-writing recipes.
|
|
92
|
+
- **Curated, not self-promoted** — the developer (or their user) decides what the model gets to reuse; the model doesn't grade its own work.
|
|
93
|
+
- **Durable** — they persist on the facet across runs and conversations.
|
|
94
|
+
- **Self-consistent** — they record the connector set that can run them, and refuse to run without it.
|
|
95
|
+
|
|
96
|
+
There is no separate skill-source interface to implement. Snippets are part of the runtime.
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# Vite Plugin
|
|
2
|
+
|
|
3
|
+
The `@cloudflare/codemode/vite` plugin exports the `CodemodeRuntime` facet class from your Worker entry module.
|
|
4
|
+
|
|
5
|
+
**Why this exists:** `createCodemodeRuntime()` stores execution state in a Durable Object facet. The Workers runtime requires facet classes to be available through `ctx.exports`, so the Worker entry module must export `CodemodeRuntime`. The plugin adds that export for you.
|
|
6
|
+
|
|
7
|
+
Connector classes do not need special import syntax. Import them normally and pass instances to `createCodemodeRuntime()`.
|
|
8
|
+
|
|
9
|
+
## Setup
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
// vite.config.ts
|
|
13
|
+
import codemode from "@cloudflare/codemode/vite";
|
|
14
|
+
import agents from "agents/vite";
|
|
15
|
+
import { cloudflare } from "@cloudflare/vite-plugin";
|
|
16
|
+
|
|
17
|
+
export default {
|
|
18
|
+
plugins: [agents(), codemode(), cloudflare()]
|
|
19
|
+
};
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## What it does
|
|
23
|
+
|
|
24
|
+
For Worker entry modules (`src/server.ts`, `src/index.ts`, or `src/worker.ts`), the plugin appends:
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
// Auto-exported by @cloudflare/codemode/vite
|
|
28
|
+
export { CodemodeRuntime } from "@cloudflare/codemode";
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
That makes `CodemodeRuntime` available as `ctx.exports.CodemodeRuntime`, which the runtime handle uses when it creates its facet.
|
|
32
|
+
|
|
33
|
+
If your entry module already exports `CodemodeRuntime`, the plugin leaves it unchanged.
|
|
34
|
+
|
|
35
|
+
## Connector imports
|
|
36
|
+
|
|
37
|
+
Use normal TypeScript imports:
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
import { GithubConnector } from "./github.codemode";
|
|
41
|
+
import { RepoApiConnector } from "./repoapi.codemode";
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Then construct connector instances where you create the runtime:
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
const runtime = createCodemodeRuntime({
|
|
48
|
+
ctx: this.ctx,
|
|
49
|
+
executor: new DynamicWorkerExecutor({ loader: this.env.LOADER }),
|
|
50
|
+
connectors: [new GithubConnector(this.ctx, this.env, conn)]
|
|
51
|
+
});
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Manual alternative
|
|
55
|
+
|
|
56
|
+
If you do not use the plugin, export `CodemodeRuntime` yourself from the Worker entry module:
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
export { CodemodeRuntime } from "@cloudflare/codemode";
|
|
60
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cloudflare/codemode",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.3",
|
|
4
4
|
"description": "Code Mode: use LLMs to generate executable code that performs tool calls",
|
|
5
5
|
"repository": {
|
|
6
6
|
"directory": "packages/codemode",
|
|
@@ -16,10 +16,10 @@
|
|
|
16
16
|
},
|
|
17
17
|
"devDependencies": {
|
|
18
18
|
"@modelcontextprotocol/sdk": "1.29.0",
|
|
19
|
-
"@playwright/test": "^1.
|
|
20
|
-
"@tanstack/ai": "
|
|
19
|
+
"@playwright/test": "^1.61.1",
|
|
20
|
+
"@tanstack/ai": "0.38.0",
|
|
21
21
|
"ai": "^6.0.202",
|
|
22
|
-
"vitest": "4.1.
|
|
22
|
+
"vitest": "4.1.9",
|
|
23
23
|
"zod": "^4.4.3"
|
|
24
24
|
},
|
|
25
25
|
"peerDependencies": {
|
|
@@ -87,12 +87,30 @@
|
|
|
87
87
|
"type": "module",
|
|
88
88
|
"files": [
|
|
89
89
|
"dist",
|
|
90
|
+
"docs",
|
|
90
91
|
"README.md"
|
|
91
92
|
],
|
|
93
|
+
"nx": {
|
|
94
|
+
"targets": {
|
|
95
|
+
"build": {
|
|
96
|
+
"inputs": [
|
|
97
|
+
"production",
|
|
98
|
+
"^production",
|
|
99
|
+
"{workspaceRoot}/docs/codemode/**/*",
|
|
100
|
+
"{workspaceRoot}/scripts/copy-package-docs.ts"
|
|
101
|
+
],
|
|
102
|
+
"outputs": [
|
|
103
|
+
"{projectRoot}/dist",
|
|
104
|
+
"{projectRoot}/docs"
|
|
105
|
+
]
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
},
|
|
92
109
|
"scripts": {
|
|
93
110
|
"build": "tsx ./scripts/build.ts",
|
|
94
111
|
"test": "vitest run && vitest run --config vitest.runtime.config.ts && vitest run --config vitest.browser.config.ts",
|
|
95
112
|
"test:e2e": "playwright test --config e2e/playwright.config.ts",
|
|
113
|
+
"test:e2e:llm": "playwright test --config e2e/playwright.llm.config.ts",
|
|
96
114
|
"test:watch": "vitest",
|
|
97
115
|
"test:browser": "vitest run --config vitest.browser.config.ts"
|
|
98
116
|
}
|