All Agent Engineering

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.

AINavWritten / Updated
On this page

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 globalOutbound defaults to null and blocks fetch() and connect(), unless the executor explicitly provides another capability such as a Fetcher.
  • 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.

Example: the official two-pass sketch (text diagram, reproduced as published; nothing was run here)
Plain text
first pass:   read ── execute ──> result
              write ── pause

approval

second pass:  read ── replay ───> recorded result
              write ── execute ─> result
              next call ────────> continue

So 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?

How the official page divides the three Code Mode parts
PartKeeps state?Responsibility
ExecutorNo (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
ConnectorDoes 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
RuntimeYesStores 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 AIChatAgent and the AI SDK, with Vite as the build tool.
  • Code Mode set up as in the official durable runtime guide: install @cloudflare/codemode; add a worker_loaders binding named LOADER and turn on nodejs_compat in the Wrangler configuration; add the agents(), codemode() and cloudflare() plugins to vite.config.ts. The codemode() plugin exports the CodemodeRuntime facet 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 McpConnector to wrap a GitHub MCP server, and each method's approval flag and optional revert are set in the connector.
  • Input: the code string the model generated, plus the list of connector methods it may call. This article uses github.list_pull_requests and github.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.

Example: the official GitHub connector and approval entry points (JavaScript, reproduced as published; nothing was deployed or run here)
javascript
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.

Which methods to gate (official basis and editorial advice marked separately)
Method typeAdviceBasis
A read-only query such as github.list_pull_requestsDo not gate it. Keep the default logging policy so replay returns the original resultOfficial: 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_issueSet requiresApproval: trueOfficial 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 compensatedGate it and also provide revertIn the official Notes example, createNote has both requiresApproval: true and revert
A write that cannot be compensatedGate it, and record on the checklist that it has no revert and stays applied after rollbackOfficial: 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 methodOfficial: 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.

What each execution log entry holds (official type definition and description)
FieldMeaning
seqThe 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, argsThe connector, method and arguments that were called
requiresApprovalWhether the call requires approval
stateOne of executing, applied, pending, reverted and error
resultOptional; the recorded result that later passes replay
ephemeralOptional; 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.

How common patterns in generated code fare under approval replay
PatternRisk when replayed after approvalVerdictFix
Putting Date.now() or another clock value straight into connector argumentsOn replay the arguments can differ from the recorded ones, which the official rule treats as divergenceMay divergeTake the value with codemode.step("created-at", () => Date.now()) and use the returned value
Using Math.random() to decide whether or which method to callThe two passes can take different branches, so the call sequences may not line upMay divergeRecord the random value once with codemode.step() and branch on that
Putting several connector calls inside Promise.all() in an execution that might pauseThe host assigns sequence numbers as calls arrive, and the arrival order can differ between passesMay divergeUse one await at a time when the execution might pause
Branching on the result of a connector readThe result is recorded and replay returns the same value, so the branch stays stableSafeThe 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 branchThe result is not stored and the call runs again each pass, so the two results can differRiskyUse 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 methodReplay could apply an approved side effect more than onceNot allowedUse the default logging policy; the pages do not say when or how an error is reported
Direct network operations or other side effects outside connectorsExternal fetch() and connect() are blocked by default; if you allowed direct access, replay would do the work againDepends on setupIf 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 charactersThe runtime does not truncate, since truncation would give replay different data; an oversized value fails the executionFailsStore 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.

Example: an editorial replay-safe version (one read, one step, one write that needs approval; organization and repository names are placeholders)
javascript
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.

Example: three editorial counterexamples (do not use them; organization and repository names are placeholders)
javascript
// 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.

Approve, reject, expire and roll back side by side (official descriptions; cells the pages do not cover say so)
OperationApplies toResulting execution statusCalls already appliedResources
approve({ executionId })Only a paused execution; it cannot revive a completed, rejected or rolled-back executionAfter replay it can complete, pause again or return errorReturn their recorded results without executing againExecution-level cleanup is not invoked on a pause; the return value for a non-paused execution is not stated
reject({ executionId, seq })One pending actionrejected, and the whole execution ends; returns false if the action is no longer pendingStay applied and are not undoneThe runtime invokes disposeExecution() after rejection
expirePaused({ maxAgeMs? })Stale paused executions and stale running executions; the default age is 24 hoursA stale paused execution becomes rejected and a stale running one becomes error; returns the IDs it terminatedNot 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 orderBecomes rolled_back only if at least one revert succeededOnly 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 enddisposeExecution() 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.

Example: a sketch of calling expirePaused from recurring maintenance (the signature is from the official API reference; the scheduling and value are editorial assumptions)
javascript
// 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 terminated

Retention 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.

State of each entry across the two passes of one piece of code (derived from the official rules)
StageA: list_pull_requestsB: step "created-at"C: create_issue
Initial passExecutes, is marked applied and its result is storedRuns the closure and stores the time valueMarked pending and the pass aborts; the outcome has status: "paused" with the arguments of C in pending
Replay after approvalReturns the recorded result without calling GitHub againReturns the recorded time value without running the closure againMatches 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.

Four endings after the same pause (derived from the official rules)
EndingCallExecution statusWhat happens to A, B and C
Approveapprove({ executionId })completed after replay (it could also pause again or error)A and B replay their records, and C executes once
Rejectreject({ executionId, seq }) with the seq of CrejectedC never executes; the records of A and B stay and are not undone
Nobody answersMaintenance calls expirePaused(), which terminates paused executions older than 24 hours (the default)rejectedThe 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 completionrollback({ executionId })Becomes rolled_back only if at least one revert succeeds, and otherwise does notA 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 requiresApproval flags in search() or describe() 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 (no Promise.all()), and that Date.now() and Math.random() appear only inside step() 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 passes executionId and seq, and the UI handles reject() returning false (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 the maxAgeMs value 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 step names 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" and requiresApproval are 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 McpConnector come with revert; the official GitHub example sets none.
  • No version number or stability commitment for @cloudflare/codemode is 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.

  1. Cloudflare Agents · How Code Mode works
  2. Cloudflare Agents · Create a durable Code Mode runtime
  3. Cloudflare Agents · Human-in-the-loop patterns
  4. Cloudflare Agents · Code Mode API reference

Found an error? Tell us →