@cloudflare/codemode 0.4.1 → 0.4.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 +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 +51 -12
- package/dist/index.js +70 -23
- 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 +155 -0
- package/docs/connectors.md +343 -0
- package/docs/index.md +192 -0
- package/docs/runtime.md +261 -0
- package/docs/snippets.md +96 -0
- package/docs/vite-plugin.md +60 -0
- package/package.json +22 -4
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
# Approvals
|
|
2
|
+
|
|
3
|
+
A tool with `requiresApproval: true` pauses the run when the model's code calls it (the run aborts), the action is recorded as pending, and the user is asked to approve. On approval the execution **continues via replay** — see [Runtime](./runtime.md) for the mechanism.
|
|
4
|
+
|
|
5
|
+
## Marking tools
|
|
6
|
+
|
|
7
|
+
On a custom connector, set it on the tool itself:
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
protected tools() {
|
|
11
|
+
return {
|
|
12
|
+
create_issue: {
|
|
13
|
+
description: "Create a GitHub issue.",
|
|
14
|
+
requiresApproval: true,
|
|
15
|
+
execute: (args) => this.client.createIssue(args)
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
On a derived connector (MCP, OpenAPI), decorate via the `tool(name, t)` hook:
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
class GithubConnector extends McpConnector<Env> {
|
|
25
|
+
protected tool(name: string, t: ConnectorTool): ConnectorTool {
|
|
26
|
+
if (name === "create_issue" || name === "merge_pull_request") {
|
|
27
|
+
return { ...t, requiresApproval: true };
|
|
28
|
+
}
|
|
29
|
+
return t;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
`requiresApproval: true` is the entire surface. Mark only what needs a human — everything else executes immediately and is still recorded in the durable log for replay and audit.
|
|
35
|
+
|
|
36
|
+
## Flow
|
|
37
|
+
|
|
38
|
+
```
|
|
39
|
+
Model calls codemode({ code }) where code calls github.create_issue(...)
|
|
40
|
+
→ runtime logs calls; create_issue requires approval → run pauses
|
|
41
|
+
→ tool returns { status: "paused", executionId, pending: [...] }
|
|
42
|
+
|
|
43
|
+
Agent shows the pending action to the user.
|
|
44
|
+
User approves.
|
|
45
|
+
|
|
46
|
+
Agent calls runtime.approve({ executionId })
|
|
47
|
+
→ runtime replays the log, runs create_issue for real, continues
|
|
48
|
+
→ returns { status: "completed", result } (or pauses again at the next action)
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
The model writes code as if the call returns normally. It doesn't see a provisional result — the run simply pauses and resumes transparently across the approval.
|
|
52
|
+
|
|
53
|
+
## Tool output
|
|
54
|
+
|
|
55
|
+
Execution outcomes are returned, not thrown — a sandbox error or a replay divergence comes back as `{ status: "error" }` (and is recorded on the execution), so the agent loop is never broken by an exception:
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
type ProxyToolOutput =
|
|
59
|
+
| {
|
|
60
|
+
status: "completed";
|
|
61
|
+
executionId: string;
|
|
62
|
+
result: unknown;
|
|
63
|
+
logs?: string[];
|
|
64
|
+
}
|
|
65
|
+
| { status: "paused"; executionId: string; pending: PendingAction[] }
|
|
66
|
+
| { status: "error"; executionId: string; error: string; logs?: string[] };
|
|
67
|
+
|
|
68
|
+
type PendingAction = {
|
|
69
|
+
executionId: string;
|
|
70
|
+
seq: number;
|
|
71
|
+
connector: string;
|
|
72
|
+
method: string;
|
|
73
|
+
args: unknown;
|
|
74
|
+
};
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Resolving approvals
|
|
78
|
+
|
|
79
|
+
The agent drives resolution through the runtime handle:
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
const runtime = createCodemodeRuntime({ ctx: this.ctx, connectors, executor });
|
|
83
|
+
|
|
84
|
+
// List actions awaiting approval, for approval UIs. With no executionId this
|
|
85
|
+
// aggregates across every paused run, so concurrent approvals all show up.
|
|
86
|
+
await runtime.pending();
|
|
87
|
+
|
|
88
|
+
// Approve the pending action(s) and continue
|
|
89
|
+
await runtime.approve({ executionId });
|
|
90
|
+
|
|
91
|
+
// Reject — ends the execution. Does NOT undo actions already applied earlier
|
|
92
|
+
// in the same run; call rollback() for that. Returns false if the action was
|
|
93
|
+
// no longer pending (approved/rejected elsewhere) — check it before telling
|
|
94
|
+
// the user the run was rejected, because the action may have executed.
|
|
95
|
+
const terminated = await runtime.reject({ seq, executionId });
|
|
96
|
+
|
|
97
|
+
// Roll back applied actions in reverse order
|
|
98
|
+
await runtime.rollback({ executionId });
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Every lifecycle call targets an explicit `executionId` (there is no implicit "current run" — that would be racy when multiple runs are in flight). Get the id from `pending()`, from `executions()`, or from the tool's own output, which carries `executionId` on every outcome.
|
|
102
|
+
|
|
103
|
+
`approve()` is a **safe no-op on a run that is no longer paused.** Approval UIs are racy: the run may have completed, been rejected, or been rolled back — in another tab, by another operator, or by a concurrent turn — between the moment the queue was rendered and the moment someone clicks. In that case `approve()` does not revive the run (which would re-offer a rejected action or re-apply rolled-back effects); it returns `{ status: "error", executionId, error: "...is not paused..." }` and changes nothing. Treat that outcome as "this run already moved on, refresh the queue," not as an execution failure. Only a `paused` run can be resumed.
|
|
104
|
+
|
|
105
|
+
Wire these to callable agent methods so the client UI can approve/reject:
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
export class Chat extends AIChatAgent<Env> {
|
|
109
|
+
@callable()
|
|
110
|
+
async listPending() {
|
|
111
|
+
return this.codemodeRuntime().pending();
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
@callable()
|
|
115
|
+
async approve(executionId: string) {
|
|
116
|
+
return this.codemodeRuntime().approve({ executionId });
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## Rollback
|
|
122
|
+
|
|
123
|
+
Rollback reverts **all** applied actions that have a `revert` — not only approval-gated ones — in reverse order. Define `revert` on the tool (or override `revertAction`); it returns whether a revert actually ran, and the runtime marks only those entries as reverted:
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
protected tools() {
|
|
127
|
+
return {
|
|
128
|
+
create_issue: {
|
|
129
|
+
description: "Create a GitHub issue.",
|
|
130
|
+
requiresApproval: true,
|
|
131
|
+
execute: (args) => this.client.createIssue(args),
|
|
132
|
+
revert: (_args, result) => {
|
|
133
|
+
const { number } = result as { number: number };
|
|
134
|
+
return this.client.closeIssue(number);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
Tools without a `revert` are skipped, as are reads. Rollback is independent of approval: a non-approval write with a `revert` is still undone.
|
|
142
|
+
|
|
143
|
+
## Comparison with Gatekeeper
|
|
144
|
+
|
|
145
|
+
| Concept | Gatekeeper | Codemode |
|
|
146
|
+
| -------------------- | ---------------------------------- | ------------------------------------------------- |
|
|
147
|
+
| Read classification | `authorizeObservation()` | unannotated (default) |
|
|
148
|
+
| Write classification | `submitAction()` | `{ requiresApproval: true }` |
|
|
149
|
+
| Pending state | Simulated in the session | Logged; run aborts |
|
|
150
|
+
| Continue | Session simulates ahead | Abort-and-replay |
|
|
151
|
+
| Apply | `applyAction(action)` | `runtime.approve({ executionId })` replays + runs |
|
|
152
|
+
| Reject | `rejectAction(action)` | `runtime.reject({ seq, executionId })` |
|
|
153
|
+
| Revert | `revertAction(action, revertInfo)` | `revertAction(method, args, result)` |
|
|
154
|
+
|
|
155
|
+
The key difference: Gatekeeper _simulates_ pending actions so code keeps running. Codemode _aborts and replays_ — simpler and fully durable, at the cost of re-running the code (cheap, since prior calls are served from the log).
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
# Connectors
|
|
2
|
+
|
|
3
|
+
Connectors are class-based integrations that bridge external services into the codemode sandbox.
|
|
4
|
+
|
|
5
|
+
**Why this exists:** there should be one way to add a capability. Whether the source is an MCP server, an OpenAPI spec, an AI SDK toolset, or your own service, the answer is the same — wrap it in a connector class, put it in a runtime, and the model sees it as a typed global (`github.list_pull_requests(...)`). The model-facing protocol never changes; only the class you subclass does.
|
|
6
|
+
|
|
7
|
+
Connectors define and execute tools. The [Runtime](./runtime.md) facet routes every call through a durable log — the connector owns definition and execution, while the runtime owns state, approvals, and rollback.
|
|
8
|
+
|
|
9
|
+
A connector answers three questions: what global name does the model use (`name`), what guidance does the model get (`instructions`), and what tools exist (`tools`). Each tool carries its own docs, schema, approval requirement, execution, and optional revert — **everything about a tool lives in one place**.
|
|
10
|
+
|
|
11
|
+
## Base class
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { CodemodeConnector } from "@cloudflare/codemode";
|
|
15
|
+
|
|
16
|
+
export class MyConnector extends CodemodeConnector<Env> {
|
|
17
|
+
name() {
|
|
18
|
+
return "myService";
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
protected instructions() {
|
|
22
|
+
return "Use for interacting with My Service.";
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
protected tools() {
|
|
26
|
+
return {
|
|
27
|
+
listItems: {
|
|
28
|
+
description: "List all items.",
|
|
29
|
+
inputSchema: {
|
|
30
|
+
type: "object",
|
|
31
|
+
properties: { limit: { type: "number" } }
|
|
32
|
+
},
|
|
33
|
+
execute: (args) => this.env.MY_SERVICE.list(args)
|
|
34
|
+
},
|
|
35
|
+
createItem: {
|
|
36
|
+
description: "Create an item.",
|
|
37
|
+
inputSchema: {
|
|
38
|
+
type: "object",
|
|
39
|
+
properties: { title: { type: "string" } },
|
|
40
|
+
required: ["title"]
|
|
41
|
+
},
|
|
42
|
+
requiresApproval: true,
|
|
43
|
+
execute: (args) => this.env.MY_SERVICE.create(args),
|
|
44
|
+
revert: (_args, result) => this.env.MY_SERVICE.delete(result.id)
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### Authoring surface
|
|
52
|
+
|
|
53
|
+
| Method | Required | Purpose |
|
|
54
|
+
| ---------------- | -------- | -------------------------------------------------------------------------------- |
|
|
55
|
+
| `name()` | Yes | Unique namespace in the sandbox (`github`, `stripe`, etc.) |
|
|
56
|
+
| `instructions()` | No | Guidance shown to the model |
|
|
57
|
+
| `tools()` | Yes | One record, one entry per tool (derived connectors generate it for you) |
|
|
58
|
+
| `tool(name, t)` | No | Decoration hook — adjust tools you didn't author inline (approval, revert, docs) |
|
|
59
|
+
|
|
60
|
+
### Each tool
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
type ToolExecuteContext = { executionId: string };
|
|
64
|
+
|
|
65
|
+
type ConnectorTool = {
|
|
66
|
+
description?: string;
|
|
67
|
+
inputSchema?: JSONSchema7; // defaults to an open object
|
|
68
|
+
outputSchema?: JSONSchema7;
|
|
69
|
+
requiresApproval?: boolean; // omit to execute immediately
|
|
70
|
+
execute: (
|
|
71
|
+
args: unknown,
|
|
72
|
+
ctx?: ToolExecuteContext
|
|
73
|
+
) => Promise<unknown> | unknown;
|
|
74
|
+
revert?: (
|
|
75
|
+
args: unknown,
|
|
76
|
+
result: unknown,
|
|
77
|
+
ctx?: ToolExecuteContext
|
|
78
|
+
) => Promise<void> | void;
|
|
79
|
+
};
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
`execute`/`revert` receive an optional `ctx` carrying the `executionId` of the run they belong to. The id is stable across a run's pause/resume passes, so it's the key to use for any resource scoped to the whole execution (see [Per-execution resources](#per-execution-resources)).
|
|
83
|
+
|
|
84
|
+
`requiresApproval: true` pauses the run for [approval](./approvals.md). `revert` enables [rollback](./runtime.md#rollback). Everything else executes immediately and is recorded in the durable log.
|
|
85
|
+
|
|
86
|
+
AI SDK tools are shape-compatible — an existing `ToolSet` can be returned from `tools()` directly:
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
export class LinearConnector extends CodemodeConnector<Env> {
|
|
90
|
+
name() {
|
|
91
|
+
return "linear";
|
|
92
|
+
}
|
|
93
|
+
protected tools() {
|
|
94
|
+
return linearTools; // an AI SDK ToolSet
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### RPC surface (derived — you don't implement this)
|
|
100
|
+
|
|
101
|
+
The proxy tool talks to connectors over Workers RPC. The base class derives this wire surface from the tools record:
|
|
102
|
+
|
|
103
|
+
- `describe()` — name, instructions, descriptors, annotations
|
|
104
|
+
- `getTypeScriptTypes()` — TypeScript declarations for describe
|
|
105
|
+
- `executeTool(method, args, ctx?)` — dispatch to the tool's `execute`
|
|
106
|
+
- `revertAction(method, args, result, ctx?)` — dispatch to the tool's `revert`
|
|
107
|
+
|
|
108
|
+
## Per-execution resources
|
|
109
|
+
|
|
110
|
+
Some connectors own a resource that must live for the lifetime of one run — a browser/CDP session, a database transaction, a temp workspace. Two pieces of the contract make this work:
|
|
111
|
+
|
|
112
|
+
1. **`execute(args, ctx)`** receives the `executionId`. Use it to lazily acquire (or reconnect to) the resource on first use, keyed by that id. Because the id is stable across pause/resume, the resource is addressable even after a run pauses for approval and resumes in a later Worker invocation. `ctx` is typed optional (so AI SDK toolsets stay shape-compatible), so read it as `ctx?.executionId` — the runtime always provides it on a real call.
|
|
113
|
+
2. **`disposeExecution(executionId, status)`** is called when the run reaches a **terminal** state, so you can tear the resource down.
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
export class BrowserConnector extends CodemodeConnector<Env> {
|
|
117
|
+
name() {
|
|
118
|
+
return "browser";
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
protected tools() {
|
|
122
|
+
return {
|
|
123
|
+
navigate: {
|
|
124
|
+
description: "Open a URL in the run's browser session.",
|
|
125
|
+
execute: async ({ url }, ctx) => {
|
|
126
|
+
const session = await this.sessionFor(ctx?.executionId);
|
|
127
|
+
return session.goto(url);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Fires on completed / error / rejected / rolled_back — never on pause.
|
|
134
|
+
override async disposeExecution(
|
|
135
|
+
executionId: string,
|
|
136
|
+
_status: ExecutionEndStatus
|
|
137
|
+
) {
|
|
138
|
+
await this.closeSessionFor(executionId);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
`disposeExecution` is deliberately **not** called when a run pauses for approval — a paused run may resume, so a resource scoped to the whole run must survive the pause. It fires for **every** connector in the runtime on each terminal transition, not just the ones a run used, so a connector that opened nothing should find nothing to close. `status` is one of:
|
|
144
|
+
|
|
145
|
+
| `ExecutionEndStatus` | When |
|
|
146
|
+
| -------------------- | ----------------------------------------- |
|
|
147
|
+
| `completed` | the run finished and returned a result |
|
|
148
|
+
| `error` | the run threw or hit a replay divergence |
|
|
149
|
+
| `rejected` | a pending action was rejected by the user |
|
|
150
|
+
| `rolled_back` | the run's applied effects were reverted |
|
|
151
|
+
|
|
152
|
+
Implementation rules (the default is a no-op, so connectors with no per-run state skip it):
|
|
153
|
+
|
|
154
|
+
- **Idempotent.** It fires on each terminal transition, so it can run more than once for one execution — a `completed` run that is later rolled back disposes twice. The second call should no-op.
|
|
155
|
+
- **No instance memory.** It may run on a different connector instance than the one that opened the resource (the host can reconstruct connectors per request, and the opening pass may have hibernated). Read what you need from durable storage keyed by `executionId`.
|
|
156
|
+
- **Never throws.** Teardown failures must not turn a finished run into a failure; the runtime ignores rejections from this hook.
|
|
157
|
+
|
|
158
|
+
> To abandon a paused run and release its resources, [`reject`](./approvals.md) the pending action — that's a terminal transition and fires `disposeExecution`. Stale paused runs nobody answers can be reclaimed in bulk with [`runtime.expirePaused`](./runtime.md#retention). (`rollback` only fires `disposeExecution` when it actually reverts an effect; a paused, read-only run isn't terminated by rollback.)
|
|
159
|
+
|
|
160
|
+
### Per-pass resources
|
|
161
|
+
|
|
162
|
+
`onPassEnd(executionId, status)` fires at the end of **every** execution pass — including a pass that ends in a pause, where `disposeExecution` deliberately does not fire. Use it to release per-pass resources: an open socket, a lease, an in-memory cache entry. `status` is an `ExecutionEndStatus` or `"paused"`. On a terminal pass, `onPassEnd` fires first, then `disposeExecution`.
|
|
163
|
+
|
|
164
|
+
```ts
|
|
165
|
+
// Keep the browser session (per-execution) across a pause, but close the
|
|
166
|
+
// CDP socket (per-pass) — the resume pass reconnects.
|
|
167
|
+
override async onPassEnd(executionId: string, _status: PassEndStatus) {
|
|
168
|
+
await this.closeSocketFor(executionId);
|
|
169
|
+
}
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
The same implementation rules as `disposeExecution` apply: idempotent, no instance memory, never throws.
|
|
173
|
+
|
|
174
|
+
> **AI SDK toolsets:** when `tools()` returns an AI SDK `ToolSet`, codemode passes `{ executionId }` as the tool's second `execute` argument — the slot the AI SDK uses for its own call options. Inside codemode those options aren't otherwise populated, but a tool authored against the AI SDK's `toolCallId`/`messages` won't receive them here.
|
|
175
|
+
|
|
176
|
+
## Replay policy
|
|
177
|
+
|
|
178
|
+
By default every call's result is recorded in the durable log and replayed on resume. A tool whose results are large and cheap to recompute can opt out with `replay: "reexecute"`:
|
|
179
|
+
|
|
180
|
+
```ts
|
|
181
|
+
protected tools(): ConnectorTools {
|
|
182
|
+
return {
|
|
183
|
+
read_file: {
|
|
184
|
+
description: "Read a file from the workspace.",
|
|
185
|
+
replay: "reexecute", // ephemeral: re-runs on replay, result never stored
|
|
186
|
+
execute: ({ path }) => this.fs.read(path)
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
The call is still logged (for sequencing and divergence detection), but its result stays out of the durable log and a replay **re-executes** it. Only use this for idempotent reads — the call runs again on every resume pass, and the value may legitimately differ across passes (which the code must tolerate). `replay: "reexecute"` cannot be combined with `requiresApproval`: an approved side effect must be logged, never re-executed.
|
|
193
|
+
|
|
194
|
+
## McpConnector
|
|
195
|
+
|
|
196
|
+
Wraps an MCP server. Each MCP tool becomes one entry in the tools record, executing through `connection.client.callTool()`. Tool names are sanitized into valid JS identifiers.
|
|
197
|
+
|
|
198
|
+
Implement `createConnection()`; decorate derived tools with the `tool(name, t)` hook:
|
|
199
|
+
|
|
200
|
+
```ts
|
|
201
|
+
import {
|
|
202
|
+
McpConnector,
|
|
203
|
+
type McpConnectionLike,
|
|
204
|
+
type ConnectorTool
|
|
205
|
+
} from "@cloudflare/codemode";
|
|
206
|
+
|
|
207
|
+
export class GithubConnector extends McpConnector<Env> {
|
|
208
|
+
constructor(
|
|
209
|
+
ctx: ExecutionContext,
|
|
210
|
+
env: Env,
|
|
211
|
+
private conn: McpConnectionLike
|
|
212
|
+
) {
|
|
213
|
+
super(ctx, env);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
name() {
|
|
217
|
+
return "github";
|
|
218
|
+
}
|
|
219
|
+
protected instructions() {
|
|
220
|
+
return "Use for GitHub operations.";
|
|
221
|
+
}
|
|
222
|
+
protected createConnection() {
|
|
223
|
+
return this.conn;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
protected tool(name: string, t: ConnectorTool): ConnectorTool {
|
|
227
|
+
if (name === "create_issue") {
|
|
228
|
+
return {
|
|
229
|
+
...t,
|
|
230
|
+
requiresApproval: true,
|
|
231
|
+
revert: (_args, result) => this.closeIssue(result)
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
return t;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
| Method | Purpose |
|
|
240
|
+
| -------------------- | -------------------------------------------------------------------- |
|
|
241
|
+
| `createConnection()` | Required. Return an MCP connection. |
|
|
242
|
+
| `toolName(tool)` | Override to customize how MCP tool names map to sandbox identifiers. |
|
|
243
|
+
|
|
244
|
+
Sandbox sees one method per MCP tool:
|
|
245
|
+
|
|
246
|
+
```ts
|
|
247
|
+
github.list_pull_requests({ owner, repo, state });
|
|
248
|
+
github.search_issues({ query });
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
## OpenApiConnector
|
|
252
|
+
|
|
253
|
+
Wraps an OpenAPI spec. The base reads the spec **once, host-side** and derives one typed tool **per operation**, so the model calls operations directly — `stripe.CreatePaymentIntent({ amount, currency })` — discoverable through `codemode.search`/`describe` with real input types. Deriving on the host costs zero prompt tokens. Override two methods:
|
|
254
|
+
|
|
255
|
+
- `spec()` returns the OpenAPI document (used to derive operations).
|
|
256
|
+
- `request()` performs an authenticated request.
|
|
257
|
+
|
|
258
|
+
```ts
|
|
259
|
+
import {
|
|
260
|
+
OpenApiConnector,
|
|
261
|
+
type OpenApiRequestOptions
|
|
262
|
+
} from "@cloudflare/codemode";
|
|
263
|
+
|
|
264
|
+
export class StripeConnector extends OpenApiConnector<Env> {
|
|
265
|
+
name() {
|
|
266
|
+
return "stripe";
|
|
267
|
+
}
|
|
268
|
+
protected instructions() {
|
|
269
|
+
return "Use for Stripe payments. Call the per-operation tools directly.";
|
|
270
|
+
}
|
|
271
|
+
protected spec() {
|
|
272
|
+
return stripeOpenApiSpec;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
protected request(options: OpenApiRequestOptions) {
|
|
276
|
+
return fetch(`https://api.stripe.com${options.path}`, {
|
|
277
|
+
method: options.method ?? "GET",
|
|
278
|
+
headers: { Authorization: `Bearer ${this.env.STRIPE_KEY}` },
|
|
279
|
+
body: options.body ? JSON.stringify(options.body) : undefined
|
|
280
|
+
}).then((r) => r.json());
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
| Method | Purpose |
|
|
286
|
+
| ------------------ | ----------------------------------------------------------------------------------------------- |
|
|
287
|
+
| `spec()` | Required. Return the OpenAPI spec document. May be async. Operations are derived from it. |
|
|
288
|
+
| `request(options)` | Required. Perform an authenticated request. Receives `{ path, method, params, body, headers }`. |
|
|
289
|
+
| `exposeSpec()` | Optional. Return `true` to also expose the raw `spec` document as a tool. Off by default. |
|
|
290
|
+
|
|
291
|
+
Each derived tool takes a single object: top-level keys are the operation's path/query/header parameters, plus a `body` key when the operation has a JSON request body. The base substitutes path params and hands `request()` a clean `{ path, method, params, body, headers }`. Local `$ref`s in the spec are inlined so the generated input types are usable. A low-level `request` tool is also exposed as an escape hatch for operations a derived tool can't reach.
|
|
292
|
+
|
|
293
|
+
Sandbox sees:
|
|
294
|
+
|
|
295
|
+
```ts
|
|
296
|
+
// Path params are substituted; the body is a typed object.
|
|
297
|
+
const intent = await stripe.CreatePaymentIntent({
|
|
298
|
+
amount: 2000,
|
|
299
|
+
currency: "usd"
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
// Escape hatch, if needed:
|
|
303
|
+
const raw = await stripe.request({
|
|
304
|
+
path: "/v1/charges",
|
|
305
|
+
method: "GET"
|
|
306
|
+
});
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
## Constructor convention
|
|
310
|
+
|
|
311
|
+
Constructors are for **dependencies** — connections, tokens, clients. Service identity and behavior come from overridable methods, not constructor config.
|
|
312
|
+
|
|
313
|
+
```ts
|
|
314
|
+
// Good — constructor receives dependency
|
|
315
|
+
export class GithubConnector extends McpConnector<Env> {
|
|
316
|
+
constructor(
|
|
317
|
+
ctx: ExecutionContext,
|
|
318
|
+
env: Env,
|
|
319
|
+
private conn: McpConnectionLike
|
|
320
|
+
) {
|
|
321
|
+
super(ctx, env);
|
|
322
|
+
}
|
|
323
|
+
name() {
|
|
324
|
+
return "github";
|
|
325
|
+
}
|
|
326
|
+
protected createConnection() {
|
|
327
|
+
return this.conn;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// Also good — reads from env
|
|
332
|
+
export class StripeConnector extends OpenApiConnector<Env> {
|
|
333
|
+
name() {
|
|
334
|
+
return "stripe";
|
|
335
|
+
}
|
|
336
|
+
protected spec() {
|
|
337
|
+
return stripeSpec;
|
|
338
|
+
}
|
|
339
|
+
protected async request(options: OpenApiRequestOptions) {
|
|
340
|
+
// Uses this.env.STRIPE_KEY
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
```
|
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
|