Durable Code Mode approvals: abort, replay and cleanup checklist
A design checklist for durable Code Mode approvals from the official Cloudflare docs: gated methods, replay rules, reject versus rollback, expiry.
Why approval is abort plus replay · Prerequisites and input · 1. Decide which methods require approval
At a glance
When a model writes code that calls a connector such as GitHub, a write like creating an issue often needs a person to approve it first. Durable Code Mode in Cloudflare Agents does not hold the code suspended. When the code reaches a call that needs approval, it aborts that pass, and after approval it replays the same source code under the same execution ID, with already applied calls returning their recorded results. This lets an approval outlast a request or a hibernation, and it makes "can this code be re-run safely" the core review question. The article gives a checklist you can fill in: which methods to mark as requiring approval, what to record at a pause, the replay rules, where codemode.step() is needed, and the outcome of rejection, expiry and rollback. The basis is four official pages, and nothing they leave unstated is inferred; the official pages describe Code Mode as experimental. Nothing was deployed or run for this article, so all of it is not tested.
Runtime and applicability
- Article type
- Engineering practice
- Verified
- Applies to
- Cloudflare Agents SDK Cloudflare Agents: Code Mode approval abort, replay and expiry cleanup
Execution locations and responsibilities
- The Code Mode runtime facet inside the Agent's Durable Object (isolated SQLite storage) Holds execution records, connector-call logs and pending actions; approve, reject, rollback and expiry cleanup all take effect here through runtime methods.
- The isolated Worker sandbox that DynamicWorkerExecutor creates for each pass Runs the model-generated code and keeps no state; after approval every pass re-runs from the top, and by default external operations go out through connector globals, because
globalOutbounddefaults tonulland blocksfetch()andconnect(), unless the executor explicitly provides another capability such as aFetcher. - The connector class (for example a GitHub connector extending McpConnector) and the @callable methods the approval UI calls The connector decides which methods carry requiresApproval and whether they have a revert; the @callable methods hand pending actions to the UI and pass approve or reject back to the runtime.
When to use
- Your Agent lets the model write code against connectors (for example GitHub MCP), some writes need human approval, and you must decide before launch which methods need it and how replay works after approval.
- You are reviewing generated code or a connector design and need to judge whether replay after approval would repeat a side effect or hit replay divergence.
When not to use
- The approval covers an application task that runs for days or longer and needs timeouts and reminders. The official page assigns that kind of approval to Workflow
waitForApproval(), a different layer from Code Mode approval. - You are handling MCP elicitation, where an MCP server asks the user for input. That is another approval layer, and the official page maps it to
configureElicitationHandlers(). - You need the full runtime setup (install, Wrangler binding, Vite plugin, connector class). This article quotes only the parts related to approval, and the official durable runtime guide is the reference for the full steps.
Why approval is abort plus replay
In the standard setup the model sees one outer tool named codemode. Its input has a single field, code, and it returns a durable outcome whose status is completed, paused or error. DynamicWorkerExecutor runs the generated code in an isolated Worker created for each pass, and the sandbox keeps no state. When the code reaches a connector method marked as requiring approval, the runtime records the call as pending and aborts the current pass, and the call receives no provisional result. After approval the runtime runs the same source code again under the same execution ID. Calls already marked applied return their recorded results instead of executing again.
first pass: read ── execute ──> result
write ── pause
approval
second pass: read ── replay ───> recorded result
write ── execute ─> result
next call ────────> continueSo at a pause the code is not left suspended in place: the pass ends, and after approval the code runs again from the top. The official page draws two consequences: generated code stays linear and needs no pause or resume logic, and an approval can wait beyond a single request or a Durable Object hibernation. The cost shows up in review, because every pass re-runs all statements before the approval point. The execution log covers connector calls and codemode.step() entries only, and every other statement really executes again. Most of the checklist below asks one question: does this code survive being re-run?
| Part | Keeps state? | Responsibility |
|---|---|---|
| Executor | No (keeps no execution history) | Runs one block of generated code once and returns a result, an error and captured console output; keeps no execution history |
| Connector | Does not store the runtime execution history (a connector can keep its own business data) | Bridges host-side services (an MCP server, an OpenAPI document, an AI SDK toolset or custom code) into the sandbox; does not manage replay, and generated code never receives its credentials |
| Runtime | Yes | Stores execution records, connector-call logs, pending approvals and snippets in isolated SQLite storage, and controls approval, replay, rollback and reuse; state survives request completion and Durable Object hibernation |
Executor and connector instances are transient, and the application provides them again when it handles a later approval. That shapes the approval entry point: the code that handles an approval must be able to rebuild the same runtime with the same connectors.
Prerequisites and input
- An Agents SDK application that already uses a Durable Object. The official example uses
AIChatAgentand the AI SDK, with Vite as the build tool. - Code Mode set up as in the official durable runtime guide: install
@cloudflare/codemode; add aworker_loadersbinding namedLOADERand turn onnodejs_compatin the Wrangler configuration; add theagents(),codemode()andcloudflare()plugins tovite.config.ts. Thecodemode()plugin exports theCodemodeRuntimefacet class, and without the plugin you export it by hand. This article does not repeat those steps. - A connector class. The official approval example extends
McpConnectorto wrap a GitHub MCP server, and each method's approval flag and optionalrevertare set in the connector. - Input: the
codestring the model generated, plus the list of connector methods it may call. This article usesgithub.list_pull_requestsandgithub.create_issue, which both appear on the official pages. - Deliverable: an approval design checklist that names the methods requiring approval, what is recorded at a pause, the replay rules after approval, where
codemode.step()is needed, and the outcome of rejection, expiry and rollback. - The official pages mark Code Mode as experimental with possible breaking changes, and the guide adds a caution about production use. The pages do not state a version number or release status for
@cloudflare/codemode.
1. Decide which methods require approval
The official approval example marks the GitHub create_issue tool as approval-gated. It extends McpConnector and overrides tool(name, tool): for create_issue it returns { ...tool, requiresApproval: true }, and every other method comes back unchanged. This code therefore adds the flag only to create_issue, and the other methods keep whatever setting the tool already has; a tool that itself carries requiresApproval: true still pauses. The JavaScript below is the official example.
import { AIChatAgent } from "@cloudflare/ai-chat";
import {
createCodemodeRuntime,
DynamicWorkerExecutor,
McpConnector,
} from "@cloudflare/codemode";
import { callable } from "agents";
import { convertToModelMessages, stepCountIs, streamText } from "ai";
import { model } from "./model";
class GitHubConnector extends McpConnector {
connection;
constructor(ctx, env, connection) {
super(ctx, env);
this.connection = connection;
}
name() {
return "github";
}
createConnection() {
return this.connection;
}
tool(name, tool) {
if (name === "create_issue") {
return { ...tool, requiresApproval: true };
}
return tool;
}
}
export class CodingAgent extends AIChatAgent {
runtime() {
const server = this.mcp
.listServers()
.find((item) => item.name === "GitHub");
if (!server) throw new Error("GitHub MCP server is not registered.");
const connection = this.mcp.mcpConnections[server.id];
if (!connection) throw new Error("GitHub MCP connection is unavailable.");
return createCodemodeRuntime({
ctx: this.ctx,
executor: new DynamicWorkerExecutor({ loader: this.env.LOADER }),
connectors: [new GitHubConnector(this.ctx, this.env, connection)],
});
}
async onChatMessage() {
const result = streamText({
model,
messages: await convertToModelMessages(this.messages),
tools: { codemode: this.runtime().tool() },
stopWhen: stepCountIs(10),
});
return result.toUIMessageStreamResponse();
}
@callable()
async pendingApprovals() {
return this.runtime().pending();
}
@callable()
async approveExecution(executionId) {
return this.runtime().approve({ executionId });
}
@callable()
async rejectExecution(executionId, seq) {
return this.runtime().reject({ executionId, seq });
}
}Three details in this code matter. name() returns github, which becomes the sandbox global, so generated code writes github.create_issue(...). runtime() creates a new runtime handle on every call and passes GitHubConnector in again, matching the point above about transient instances. The three @callable() methods are the entry points for an approval UI: pendingApprovals() returns the pending actions, approveExecution(executionId) takes only an execution ID, and rejectExecution(executionId, seq) also takes seq. How exposed these methods are to client calls is outside this article.
| Method type | Advice | Basis |
|---|---|---|
A read-only query such as github.list_pull_requests | Do not gate it. Keep the default logging policy so replay returns the original result | Official: the default policy stores the connector result and replays it on later passes, preserving the exact value the code saw |
A write with real consequences such as github.create_issue | Set requiresApproval: true | Official example; the official list of practices advises requiring confirmation only for actions with meaningful consequences such as payments, emails and data changes |
| A write that can be compensated | Gate it and also provide revert | In the official Notes example, createNote has both requiresApproval: true and revert |
| A write that cannot be compensated | Gate it, and record on the checklist that it has no revert and stays applied after rollback | Official: a method without revert remains applied after rollback; how this row is worded is editorial advice |
A read you want to set to replay: "reexecute" | Use it only for idempotent reads with large, inexpensive results; never on an approval-required method | Official: the policy stores no result and calls again on later passes, so the result can change; it cannot be combined with requiresApproval |
You can check that the flag took effect without running code. The official pages say search() and describe() do not run sandbox code, and in their results a connector method that requires approval carries requiresApproval: true, while methods that do not require approval and snippets omit the field. Compare their output with your list item by item.
2. What to record and show at a pause
At a pause the model receives a result with status: "paused", an executionId and a pending array. Each pending action has five fields: executionId, seq, connector, method and args. An approval UI should show the approver at least the connector, the method name and the full arguments, and the official list of practices also advises showing all arguments of the action. Called without an execution ID, pending(executionId?) combines the pending actions of all paused executions.
| Field | Meaning |
|---|---|
seq | The sequence number of a connector call or codemode.step() within the execution; on replay the same number must use the same connector, method and arguments |
connector, method, args | The connector, method and arguments that were called |
requiresApproval | Whether the call requires approval |
state | One of executing, applied, pending, reverted and error |
result | Optional; the recorded result that later passes replay |
ephemeral | Optional; marks a call from replay: "reexecute", whose result is not stored and which runs again on each pass |
The log has one ordering detail: the runtime marks a call executing before it invokes the connector, and marks it applied only after the result is recorded. If the host stops before a pass completes, the execution can remain in running. Approval does not resume such a stale running execution; a later expirePaused() call marks it as an error and releases its resources.
The runtime log records calls, not approval decisions. The official pages do not say the runtime stores who approved, when, or on what basis, and the general list of practices advises recording all approval decisions with this.sql. Put that into your own approval methods and make it a required item on the checklist; this is editorial advice, not documented runtime behavior.
Two more details of the approval entry point are easy to get wrong. First, approveExecution takes only an execution ID. When one execution has several pending actions at once, the official pages do not say whether approval applies to them one at a time, so do not design a UI that approves only one of them. Second, each execution records every connector configured when it starts, and approval replay and snippet execution require all recorded connectors to stay available, even if the original code never called one of them. While paused executions exist, do not remove a connector from the connectors array; the pages do not say what approval returns when a connector is missing.
3. Review generated code for replay safety
The replay rule is a single one: connector calls and steps must occur in the same order on every pass, and a given sequence number must use the same connector, method and arguments. A mismatch ends the execution with a replay-divergence error. The error comes back as data with error status, so it does not escape as an uncaught RPC exception. Recorded connector results keep ordinary data-dependent branches stable. The real risk comes from sources such as Date.now() and Math.random(), which can change from pass to pass and so alter control flow or action arguments.
| Pattern | Risk when replayed after approval | Verdict | Fix |
|---|---|---|---|
Putting Date.now() or another clock value straight into connector arguments | On replay the arguments can differ from the recorded ones, which the official rule treats as divergence | May diverge | Take the value with codemode.step("created-at", () => Date.now()) and use the returned value |
Using Math.random() to decide whether or which method to call | The two passes can take different branches, so the call sequences may not line up | May diverge | Record the random value once with codemode.step() and branch on that |
Putting several connector calls inside Promise.all() in an execution that might pause | The host assigns sequence numbers as calls arrive, and the arrival order can differ between passes | May diverge | Use one await at a time when the execution might pause |
| Branching on the result of a connector read | The result is recorded and replay returns the same value, so the branch stays stable | Safe | The default policy is enough; for very large values see the last row of this table |
A read set to replay: "reexecute" whose result drives a branch | The result is not stored and the call runs again each pass, so the two results can differ | Risky | Use it only for idempotent reads with large results; generated code must tolerate changes, and should not let the result decide whether the approval point is reached (the second half is editorial advice) |
Setting replay: "reexecute" on an approval-required method | Replay could apply an approved side effect more than once | Not allowed | Use the default logging policy; the pages do not say when or how an error is reported |
| Direct network operations or other side effects outside connectors | External fetch() and connect() are blocked by default; if you allowed direct access, replay would do the work again | Depends on setup | If you allow direct access, wrap anything that must happen only once in codemode.step() |
| Connector arguments, recorded results, step results or execution source above 1,000,000 serialized characters | The runtime does not truncate, since truncation would give replay different data; an oversized value fails the execution | Fails | Store large data elsewhere and pass a small reference such as a file path |
codemode.step(name, fn) runs the closure once and records its result, and on replay it returns the recorded value without running the closure again. Connector calls already pass through the runtime and need no step wrapper, so steps are for nondeterministic or side-effectful work outside connectors. The version below is a replay-safe rewrite based on the official rules: one read, one step and one write that needs approval. The repository names are placeholders, so replace them with your own.
async () => {
const prs = await github.list_pull_requests({
owner: "your-org",
repo: "your-repo",
state: "open",
});
const createdAt = await codemode.step("created-at", () => Date.now());
const issue = await github.create_issue({
owner: "your-org",
repo: "your-repo",
title: `Review created at ${createdAt}`,
});
return { prs, issue };
};Compare three counterexamples. A puts Date.now() directly into the arguments of a call that needs approval, so the time in the title can change on replay. B uses Math.random() to decide whether the call happens, so the two passes can take different branches. C issues two calls at once with Promise.all(), so the sequence numbers depend on arrival order. Under the official rule any of the three can end with a replay-divergence error; the pages do not say at which moment the mismatch is detected.
// A: a clock value goes straight into the arguments of a gated call
async () => {
return github.create_issue({
owner: "your-org",
repo: "your-repo",
title: `Review created at ${Date.now()}`,
});
};
// B: a random value decides whether the gated call happens at all
async () => {
if (Math.random() < 0.5) {
return github.create_issue({
owner: "your-org",
repo: "your-repo",
title: "Sampled review",
});
}
return "skipped";
};
// C: two connector calls are issued concurrently
async () => {
return Promise.all([
github.create_issue({ owner: "your-org", repo: "your-repo", title: "Issue one" }),
github.create_issue({ owner: "your-org", repo: "your-repo", title: "Issue two" }),
]);
};4. Write down what reject, expiry and rollback each do
Reject, expire and roll back are three different operations, so do not collapse them into one "cancel". Rejecting says no to one pending action and ends the whole execution. Expiry is a maintenance task that clears paused executions nobody answered. Rollback compensates for calls that were already applied. The official pages stress that rejection does not undo earlier actions and that rollback is a separate operation.
| Operation | Applies to | Resulting execution status | Calls already applied | Resources |
|---|---|---|---|---|
approve({ executionId }) | Only a paused execution; it cannot revive a completed, rejected or rolled-back execution | After replay it can complete, pause again or return error | Return their recorded results without executing again | Execution-level cleanup is not invoked on a pause; the return value for a non-paused execution is not stated |
reject({ executionId, seq }) | One pending action | rejected, and the whole execution ends; returns false if the action is no longer pending | Stay applied and are not undone | The runtime invokes disposeExecution() after rejection |
expirePaused({ maxAgeMs? }) | Stale paused executions and stale running executions; the default age is 24 hours | A stale paused execution becomes rejected and a stale running one becomes error; returns the IDs it terminated | Not stated by the official pages (the no-undo statement for reject() is not extended to expiry) | Execution-scoped resources are released |
rollback({ executionId }) | Applied calls, processed in reverse order | Becomes rolled_back only if at least one revert succeeded | Only methods that provide revert are compensated; methods without it and missing connectors stay applied; a failed revert does not stop the remaining attempts, and failures are reported at the end | disposeExecution() runs after rollback, and cleanup must be idempotent |
Rollback is compensation, not database transaction isolation. Connector authors define what reversal means for each action, and an external system may change between the original call and its compensation. For every approval-gated write method, the checklist should therefore say whether it has a revert and what that revert actually does. The official pages give no general reversal semantics.
Expiry is something you have to schedule. The official pages say running and paused executions are not pruned automatically because they may still finish or resume, and that you should call expirePaused() from recurring maintenance. The default age is 24 hours (the constant DEFAULT_PAUSED_TTL_MS, 86400000 milliseconds), and maxAgeMs changes it. The pages do not say whether age counts from creation or from the last update, so leave margin when you choose maxAgeMs. How the recurring maintenance is scheduled is also left to the application, and the pages give no example. The sketch below only shows the call.
// Sketch: call this from your own recurring maintenance.
// expirePaused({ maxAgeMs }) is documented; how you schedule it is up to the application.
const expired = await this.runtime().expirePaused({
maxAgeMs: 60 * 60 * 1000,
});
// expired holds the IDs of the executions that were terminatedRetention of terminal records is a separate matter. When a new run begins, the runtime inserts that run first and then prunes older terminal executions. maxExecutions defaults to 50, so completion can temporarily leave 51 terminal records until the next run begins or you call pruneExecutions(). deleteExecution(id) removes a single record, and deleting a nonterminal execution also releases its execution-scoped resources.
Worked example: the possible endings of one create_issue
Hand the replay-safe version from the previous section to the runtime, and call its three entries, in order, A (the list_pull_requests read), B (step("created-at")) and C (the create_issue write that needs approval). The two tables below follow the official rules and are not observed output. The pages do not say which number sequence numbering starts from, so the tables use letters.
| Stage | A: list_pull_requests | B: step "created-at" | C: create_issue |
|---|---|---|---|
| Initial pass | Executes, is marked applied and its result is stored | Runs the closure and stores the time value | Marked pending and the pass aborts; the outcome has status: "paused" with the arguments of C in pending |
| Replay after approval | Returns the recorded result without calling GitHub again | Returns the recorded time value without running the closure again | Matches the recorded connector, method and arguments, so the call executes and is marked applied; the code finishes and the outcome has status: "completed" |
The arguments of C use the time value recorded by B, so the title is identical on both passes and the sequence number and arguments line up. With counterexample A from the previous section, the arguments at the same sequence number could differ.
| Ending | Call | Execution status | What happens to A, B and C |
|---|---|---|---|
| Approve | approve({ executionId }) | completed after replay (it could also pause again or error) | A and B replay their records, and C executes once |
| Reject | reject({ executionId, seq }) with the seq of C | rejected | C never executes; the records of A and B stay and are not undone |
| Nobody answers | Maintenance calls expirePaused(), which terminates paused executions older than 24 hours (the default) | rejected | The execution status is the same as for rejection, and execution-scoped resources are released; the pages do not say what happens to applied calls; an approval that arrives later cannot revive it |
| Rollback after completion | rollback({ executionId }) | Becomes rolled_back only if at least one revert succeeds, and otherwise does not | A is a read; C is compensated only if it provides revert. The official GitHub example sets no revert on create_issue, and the pages do not say whether McpConnector supplies one |
Completion checks
- List every connector method with whether it requires approval and why, then compare the
requiresApprovalflags insearch()ordescribe()results with that list. - For each piece of generated code going live, mark every connector call and
codemode.step()in order; confirm that connector calls stay sequential in executions that might pause (noPromise.all()), and thatDate.now()andMath.random()appear only insidestep()closures. - For any call that needs approval, say what state it has in the initial pass and in the replay after approval (pending, applied), and why its arguments match on replay.
- The approval UI shows the connector, the method and the full arguments; approval passes only
executionId, rejection passesexecutionIdandseq, and the UI handlesreject()returningfalse(the action is no longer pending). Record the approval decision separately in your own store. - Write down the execution status, the fate of applied calls and the resource cleanup for reject, expiry and rollback, and state that rollback compensates only calls that provide
revert. - A recurring job calls
expirePaused(), and themaxAgeMsvalue has a stated source (the default is 24 hours); the retention count for terminal records also has one (the default is 50). - While paused executions exist, the connector configuration stays unchanged; connector cleanup hooks do not depend on instance memory and can run more than once.
What the pages leave open, and the scope of this batch
- The pages do not say which number sequence numbering starts from, or whether
stepnames must be unique. - The pages do not say whether one pause can hold several pending actions at once, or how
approve({ executionId })treats them if so. - The pages do not say what the model side receives after a rejection, or what
approve()returns for a non-paused execution. - The pages do not say at which moment a replay-divergence error is detected or what its text is, nor when or how an error is reported if
replay: "reexecute"andrequiresApprovalare set together. - The pages do not say whether expiry counts from creation or from the last update, whether
rollback()can act on rejected, errored or paused executions, or what happens when a recorded connector is missing during approval replay. - The pages do not say whether tools created by
McpConnectorcome withrevert; the official GitHub example sets none. - No version number or stability commitment for
@cloudflare/codemodeis given; the pages say only that Code Mode is experimental and may have breaking changes.
The facts in this article come from four official Cloudflare pages read on 2026-11-24: How Code Mode works, Create a durable Code Mode runtime, Human-in-the-loop patterns and Code Mode API reference. The Last updated dates shown at the top of the four pages are 2026-10-12, 2026-07-22, 2026-10-27 and 2026-07-22. Its code examples either come from the official pages as published or are labeled in their captions as editorial rewrites or constructions, which serve only to illustrate the replay rules. This batch did not install @cloudflare/codemode, deploy a Worker, run a Code Mode sandbox, connect to GitHub or any MCP server, or observe any actual pause, approval, rejection, expiry or rollback, so all of it is not tested. Sentences labeled as editorial advice are choices about checking order, not official commitments.
Sources
All links are official pages; verification dates are listed per source, and links point to the version checked.