Skip to content

Changelog

New updates and improvements at Cloudflare.

Introducing Billable Usage dashboard and Budget alerts

Pay-as-you-go customers can now monitor usage-based costs and configure spend alerts through two new features: the Billable Usage dashboard and Budget alerts.

Billable Usage dashboard

The Billable Usage dashboard provides daily visibility into usage-based costs across your Cloudflare account. The data comes from the same system that generates your monthly invoice, so the figures match your bill.

The dashboard displays:

  • A bar chart showing daily usage charges for your billing period
  • A sortable table breaking down usage by product, including total usage, billable usage, and cumulative costs
  • Ability to view previous billing periods

Usage data aligns to your billing cycle, not the calendar month. The total usage cost shown at the end of a completed billing period matches the usage overage charges on your corresponding invoice.

To access the dashboard, go to Manage Account > Billing > Billable Usage.

Screenshot of the Billable Usage dashboard in the Cloudflare dashboard

Budget alerts

Budget alerts allow you to set dollar-based thresholds for your account-level usage spend. You receive an email notification when your projected monthly spend reaches your configured threshold, giving you proactive visibility into your bill before month-end.

To configure a budget alert:

  1. Go to Manage Account > Billing > Billable Usage.
  2. Select Set Budget Alert.
  3. Enter a budget threshold amount greater than $0.
  4. Select Create.

Alternatively, configure alerts via Notifications > Add > Budget Alert.

Create Budget Alert modal in the Cloudflare dashboard

You can create multiple budget alerts at different dollar amounts. The notifications system automatically deduplicates alerts if multiple thresholds trigger at the same time. Budget alerts are calculated daily based on your usage trends and fire once per billing cycle when your projected spend first crosses your threshold.

Both features are available to Pay-as-you-go accounts with usage-based products (Workers, R2, Images, etc.). Enterprise contract accounts are not supported.

For more information, refer to the Usage based billing documentation.

WebSocket binary messages now delivered as Blob by default

Binary frames received on a WebSocket are now delivered to the message event as Blob objects by default. This matches the WebSocket specification and standard browser behavior. Previously, binary frames were always delivered as ArrayBuffer. The binaryType property on WebSocket controls the delivery type on a per-WebSocket basis.

This change has been active for Workers with compatibility dates on or after 2026-03-17, via the websocket_standard_binary_type compatibility flag. We should have documented this change when it shipped but didn't. We're sorry for the trouble that caused. If your Worker handles binary WebSocket messages and assumes event.data is an ArrayBuffer, the frames will arrive as Blob instead, and a naive instanceof ArrayBuffer check will silently drop every frame.

To opt back into ArrayBuffer delivery, assign binaryType before calling accept(). This works regardless of the compatibility flag:

const resp = await fetch("https://example.com", {
	headers: { Upgrade: "websocket" },
});
const ws = resp.webSocket;

// Opt back into ArrayBuffer delivery for this WebSocket.
ws.binaryType = "arraybuffer";
ws.accept();

ws.addEventListener("message", (event) => {
	if (typeof event.data === "string") {
		// Text frame.
	} else {
		// event.data is an ArrayBuffer because we set binaryType above.
	}
});

If you are not ready to migrate and want to keep ArrayBuffer as the default for all WebSockets in your Worker, add the no_websocket_standard_binary_type flag to your Wrangler configuration file.

This change has no effect on the Durable Object hibernatable WebSocket webSocketMessage handler, which continues to receive binary data as ArrayBuffer.

For more information, refer to WebSockets binary messages.

Increased concurrency, creation rate, and queued instance limits for Workflows instances

Workflows limits have been raised to the following:

Limit Previous New
Concurrent instances (running in parallel) 10,000 50,000
Instance creation rate (per account) 100/second per account 300/second per account, 100/second per workflow
Queued instances per Workflow 1 1 million 2 million

These increases apply to all users on the Workers Paid plan. Refer to the Workflows limits documentation for more details.

Footnotes

  1. Queued instances are instances that have been created or awoken and are waiting for a concurrency slot.

Local Explorer for local resource data

Local Explorer is a browser-based interface and REST API for viewing and editing local resource data during development. It removes the need to write throwaway scripts or dig through .wrangler/state to understand what data your Worker has stored locally.

Local Explorer is available in Wrangler 4.82.1+ and the Cloudflare Vite plugin 1.32.0+. Start a local development session and press e in your terminal, or navigate to /cdn-cgi/explorer on your local dev server.

Supported resources

Local Explorer supports five resource types and works across multiple workers running locally:

  • KV — Browse keys, view values and metadata, create, update, and delete key-value pairs.
  • R2 — List objects, view metadata, upload files, and delete objects. Supports directory views and multi-select.
  • D1 — Browse tables and rows, run arbitrary SQL queries, and edit schemas in a full data studio.
  • Durable Objects (SQLite storage) — Browse individual object SQLite tables, run SQL queries, and edit schemas.
  • Workflows — List instances, view status and step history, trigger new runs, and pause, resume, restart, or terminate instances.

OpenAPI-powered REST API

Local Explorer exposes a REST API at /cdn-cgi/explorer/api that provides programmatic access to the same operations available in the browser. The root endpoint returns an OpenAPI specification describing all available endpoints, parameters, and response formats.

curl http://localhost:8787/cdn-cgi/explorer/api

Point an AI coding agent at /cdn-cgi/explorer/api and it can discover and interact with your local resources without manual setup. This enables iterative development loops where an agent can populate test data in KV or D1, inspect Durable Object state, trigger Workflow runs, or upload files to R2.

For more details, refer to the Local Explorer documentation.

Relaxed simultaneous connection limiting for Workers

The simultaneous open connections limit has been relaxed. Previously, each Worker invocation was limited to six open connections at a time for the entire lifetime of each connection, including while reading the response body. Now, a connection is freed as soon as response headers arrive, so the six-connection limit only constrains how many connections can be in the initial "waiting for headers" phase simultaneously.

Before: New connections are blocked until an earlier connection fully completes

A 7th fetch is queued until an earlier connection fully completes, including reading its entire response body

After: New connections can start as soon as response headers arrive

A 7th fetch starts as soon as any earlier connection receives its response headers

This means Workers can now have many more connections open at the same time without queueing, as long as no more than six are waiting for their initial response. This eliminates the Response closed due to connection limit exception that could previously occur when the runtime canceled stalled connections to prevent deadlocks.

Previously, the runtime used a deadlock avoidance algorithm that watched each open connection for I/O activity. If all six connections appeared idle — even momentarily — the runtime would cancel the least-recently-used connection to make room for new requests. In practice, this heuristic was fragile. For example, when a response used Content-Encoding: gzip, the runtime's internal decompression created brief gaps between read and write operations. During these gaps, the connection appeared stalled despite being actively read by the Worker. If multiple connections hit these gaps at the same time, the runtime could spuriously cancel a connection that was working correctly. By only counting connections during the waiting-for-headers phase — where the runtime is fully in control and there is no ambiguity about whether the connection is active — this class of bug is eliminated entirely.

Before: Connections could be canceled during brief internal pauses

A connection with gaps from gzip decompression appears idle and is canceled by the runtime

After: Connections complete normally regardless of internal pauses

The same connection completes normally because the body phase is no longer counted against the limit

WebSockets now automatically reply to Close frames

The Workers runtime now automatically sends a reciprocal Close frame when it receives a Close frame from the peer. The readyState transitions to CLOSED before the close event fires. This matches the WebSocket specification and standard browser behavior.

This change is enabled by default for Workers using compatibility dates on or after 2026-04-07 (via the web_socket_auto_reply_to_close compatibility flag). Existing code that manually calls close() inside the close event handler will continue to work — the call is silently ignored when the WebSocket is already closed.

const [client, server] = Object.values(new WebSocketPair());
server.accept();

server.addEventListener("close", (event) => {
	// readyState is already CLOSED — no need to call server.close().
	console.log(server.readyState); // WebSocket.CLOSED
	console.log(event.code); // 1000
	console.log(event.wasClean); // true
});

Half-open mode for WebSocket proxying

The automatic close behavior can interfere with WebSocket proxying, where a Worker sits between a client and a backend and needs to coordinate the close on both sides independently. To support this use case, pass { allowHalfOpen: true } to accept():

const [client, server] = Object.values(new WebSocketPair());

server.accept({ allowHalfOpen: true });

server.addEventListener("close", (event) => {
	// readyState is still CLOSING here, giving you time
	// to coordinate the close on the other side.
	console.log(server.readyState); // WebSocket.CLOSING

	// Manually close when ready.
	server.close(event.code, "done");
});

For more information, refer to WebSockets Close behavior.

All Wrangler commands for Workflows now support local development

All wrangler workflows commands now accept a --local flag to target a Workflow running in a local wrangler dev session instead of the production API.

You can now manage the full Workflow lifecycle locally, including triggering Workflows, listing instances, pausing, resuming, restarting, terminating, and sending events:

npx wrangler workflows list --local
npx wrangler workflows trigger my-workflow --local
npx wrangler workflows instances list my-workflow --local
npx wrangler workflows instances pause my-workflow <INSTANCE_ID> --local
npx wrangler workflows instances send-event my-workflow <INSTANCE_ID> --type my-event --local

All commands also accept --port to target a specific wrangler dev session (defaults to 8787).

For more information, refer to Workflows local development.

Deploy Hooks are now available for Workers Builds

Workers Builds now supports Deploy Hooks — trigger builds from your headless CMS, a Cron Trigger, a Slack bot, or any system that can send an HTTP request.

Each Deploy Hook is a unique URL tied to a specific branch. Send it a POST and your Worker builds and deploys.

curl -X POST "https://api.cloudflare.com/client/v4/workers/builds/deploy_hooks/<DEPLOY_HOOK_ID>"

To create one, go to Workers & Pages > your Worker > Settings > Builds > Deploy Hooks.

Since a Deploy Hook is a URL, you can also call it from another Worker. For example, a Worker with a Cron Trigger can rebuild your project on a schedule:

export default {
	async scheduled(event, env, ctx) {
		ctx.waitUntil(fetch(env.DEPLOY_HOOK_URL, { method: "POST" }));
	},
};
export default {
  async scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext): Promise<void> {
    ctx.waitUntil(fetch(env.DEPLOY_HOOK_URL, { method: "POST" }));
  },
} satisfies ExportedHandler<Env>;

You can also use Deploy Hooks to rebuild when your CMS publishes new content or deploy from a Slack slash command.

Built-in optimizations

  • Automatic deduplication: If a Deploy Hook fires multiple times before the first build starts running, redundant builds are automatically skipped. This keeps your build queue clean when webhooks retry or CMS events arrive in bursts.
  • Last triggered: The dashboard shows when each hook was last triggered.
  • Build source: Your Worker's build history shows which Deploy Hook started each build by name.

Deploy Hooks are rate limited to 10 builds per minute per Worker and 100 builds per minute per account. For all limits, see Limits & pricing.

To get started, read the Deploy Hooks documentation.

New L4 transport telemetry fields in Workers

Three new properties are now available on request.cf in Workers that expose Layer 4 transport telemetry from the client connection. These properties let your Worker make decisions based on real-time connection quality signals — such as round-trip time and data delivery rate — without requiring any client-side changes.

Previously, this telemetry was only available via the Server-Timing: cfL4 response header. These new properties surface the same data directly in the Workers runtime, so you can use it for routing, logging, or response customization.

New properties

Property Type Description
clientTcpRtt number | undefined The smoothed TCP round-trip time (RTT) between Cloudflare and the client in milliseconds. Only present for TCP connections (HTTP/1, HTTP/2). For example, 22.
clientQuicRtt number | undefined The smoothed QUIC round-trip time (RTT) between Cloudflare and the client in milliseconds. Only present for QUIC connections (HTTP/3). For example, 42.
edgeL4 Object | undefined Layer 4 transport statistics. Contains deliveryRate (number) — the most recent data delivery rate estimate for the connection, in bytes per second. For example, 123456.

Example: Log connection quality metrics

export default {
  async fetch(request) {
    const cf = request.cf;

    const rtt = cf.clientTcpRtt ?? cf.clientQuicRtt ?? 0;
    const deliveryRate = cf.edgeL4?.deliveryRate ?? 0;
    const transport = cf.clientTcpRtt ? "TCP" : "QUIC";

    console.log(`Transport: ${transport}, RTT: ${rtt}ms, Delivery rate: ${deliveryRate} B/s`);

    const headers = new Headers(request.headers);
    headers.set("X-Client-RTT", String(rtt));
    headers.set("X-Delivery-Rate", String(deliveryRate));

    return fetch(new Request(request, { headers }));
  },
};

For more information, refer to Workers Runtime APIs: Request.

New RFC 9440 mTLS certificate fields in Workers

Four new fields are now available on request.cf.tlsClientAuth in Workers for requests that include a mutual TLS (mTLS) client certificate. These fields encode the client certificate and its intermediate chain in RFC 9440 format — the same standard format used by the Client-Cert and Client-Cert-Chain HTTP headers — so your Worker can forward them directly to your origin without any custom parsing or encoding logic.

New fields

Field Type Description
certRFC9440 String The client leaf certificate in RFC 9440 format (:base64-DER:). Empty if no client certificate was presented.
certRFC9440TooLarge Boolean true if the leaf certificate exceeded 10 KB and was omitted from certRFC9440.
certChainRFC9440 String The intermediate certificate chain in RFC 9440 format as a comma-separated list. Empty if no intermediates were sent or if the chain exceeded 16 KB.
certChainRFC9440TooLarge Boolean true if the intermediate chain exceeded 16 KB and was omitted from certChainRFC9440.

Example: forwarding client certificate headers to your origin

export default {
  async fetch(request) {
    const tls = request.cf.tlsClientAuth;

    // Only forward if cert was verified and chain is complete
    if (!tls || !tls.certVerified || tls.certRevoked || tls.certChainRFC9440TooLarge) {
      return new Response("Unauthorized", { status: 401 });
    }

    const headers = new Headers(request.headers);
    headers.set("Client-Cert", tls.certRFC9440);
    headers.set("Client-Cert-Chain", tls.certChainRFC9440);

    return fetch(new Request(request, { headers }));
  },
};

For more information, refer to Client certificate variables and Mutual TLS authentication.

Access Durable Object jurisdiction via `ctx.id.jurisdiction`

ctx.id.jurisdiction inside a Durable Object now reports the jurisdiction the object was created in — for example "eu" when accessed through env.MY_DURABLE_OBJECT.jurisdiction("eu") — so you can make region-aware decisions without passing the jurisdiction through method arguments or persisting it in storage. For the full list of ID-construction paths that preserve jurisdiction, refer to the Durable Object ID documentation.

export class RegionalRoom extends DurableObject {
	async fetch(request) {
		// "eu" when accessed through env.MY_DURABLE_OBJECT.jurisdiction("eu")
		const region = this.ctx.id.jurisdiction;
		return new Response(`Hello from ${region ?? "the default region"}!`);
	}
}

// Worker
export default {
	async fetch(request, env) {
		const stub = env.MY_DURABLE_OBJECT.jurisdiction("eu").getByName("general");
		return stub.fetch(request);
	},
};

ctx.id.jurisdiction is undefined for Durable Objects that were not created in a jurisdiction-restricted namespace. Alarms scheduled before 2026-03-15 also do not have jurisdiction stored; to backfill the value, reschedule the alarm from a fetch() or RPC handler.

Declare required secrets in your Wrangler configuration

The new secrets configuration property lets you declare the secret names your Worker requires in your Wrangler configuration file. Required secrets are validated during local development and deploy, and used as the source of truth for type generation.

{
	"secrets": {
		"required": ["API_KEY", "DB_PASSWORD"],
	},
}
[secrets]
required = [ "API_KEY", "DB_PASSWORD" ]

Local development

When secrets is defined, wrangler dev and vite dev load only the keys listed in secrets.required from .dev.vars or .env/process.env. Additional keys in those files are excluded. If any required secrets are missing, a warning is logged listing the missing names.

Type generation

wrangler types generates typed bindings from secrets.required instead of inferring names from .dev.vars or .env. This lets you run type generation in CI or other environments where those files are not present. Per-environment secrets are supported — the aggregated Env type marks secrets that only appear in some environments as optional.

Deploy

wrangler deploy and wrangler versions upload validate that all secrets in secrets.required are configured on the Worker before the operation succeeds. If any required secrets are missing, the command fails with an error listing which secrets need to be set.

For more information, refer to the secrets configuration property reference.

Dynamic Workers, now in open beta

Dynamic Workers are now in open beta for all paid Workers users. You can now have a Worker spin up other Workers, called Dynamic Workers, at runtime to execute code on-demand in a secure, sandboxed environment. Dynamic Workers start in milliseconds, making them well suited for fast, secure code execution at scale.

Use Dynamic Workers for

  • Code Mode: LLMs are trained to write code. Run tool-calling logic written in code instead of stepping through many tool calls, which can save up to 80% in inference tokens and cost.
  • AI agents executing code: Run code for tasks like data analysis, file transformation, API calls, and chained actions.
  • Running AI-generated code: Run generated code for prototypes, projects, and automations in a secure, isolated sandboxed environment.
  • Fast development and previews: Load prototypes, previews, and playgrounds in milliseconds.
  • Custom automations: Create custom tools on the fly that execute a task, call an integration, or automate a workflow.

Executing Dynamic Workers

Dynamic Workers support two loading modes:

  • load(code) — for one-time code execution (equivalent to calling get() with a null ID).
  • get(id, callback) — caches a Dynamic Worker by ID so it can stay warm across requests. Use this when the same code will receive subsequent requests.
export default {
	async fetch(request, env) {
		const worker = env.LOADER.load({
			compatibilityDate: "2026-01-01",
			mainModule: "src/index.js",
			modules: {
				"src/index.js": `
					export default {
						fetch() {
							return new Response("Hello from a dynamic Worker");
						},
					};
				`,
			},
			// Block all outbound network access from the Dynamic Worker.
			globalOutbound: null,
		});

		return worker.getEntrypoint().fetch(request);
	},
};
export default {
	async fetch(request: Request, env: Env): Promise<Response> {
		const worker = env.LOADER.load({
			compatibilityDate: "2026-01-01",
			mainModule: "src/index.js",
			modules: {
				"src/index.js": `
					export default {
						fetch() {
							return new Response("Hello from a dynamic Worker");
						},
					};
				`,
			},
			// Block all outbound network access from the Dynamic Worker.
			globalOutbound: null,
		});

		return worker.getEntrypoint().fetch(request);
	},
};

Helper libraries for Dynamic Workers

Here are 3 new libraries to help you build with Dynamic Workers:

  • @cloudflare/codemode: Replace individual tool calls with a single code() tool, so LLMs write and execute TypeScript that orchestrates multiple API calls in one pass.

  • @cloudflare/worker-bundler: Resolve npm dependencies and bundle source files into ready-to-load modules for Dynamic Workers, all at runtime.

  • @cloudflare/shell: Give your agent a virtual filesystem inside a Dynamic Worker with persistent storage backed by SQLite and R2.

Try it out

Dynamic Workers Starter

Deploy to Workers

Use this starter to deploy a Worker that can load and execute Dynamic Workers.

Dynamic Workers Playground

Deploy to Workers

Deploy the Dynamic Workers Playground to write or import code, bundle it at runtime with @cloudflare/worker-bundler, execute it through a Dynamic Worker, and see real-time responses and execution logs.

For the full API reference and configuration options, refer to the Dynamic Workers documentation.

Pricing

Dynamic Workers pricing is based on three dimensions: Dynamic Workers created daily, requests, and CPU time.

Included Additional usage
Dynamic Workers created daily 1,000 unique Dynamic Workers per month +$0.002 per Dynamic Worker per day
Requests ¹ 10 million per month +$0.30 per million requests
CPU time ¹ 30 million CPU milliseconds per month +$0.02 per million CPU milliseconds

¹ Uses Workers Standard rates and will appear as part of your existing Workers bill, not as separate Dynamic Workers charges.

Note: Dynamic Workers requests and CPU time are already billed as part of your Workers plan and will count toward your Workers requests and CPU usage. The Dynamic Workers created daily charge is not yet active — you will not be billed for the number of Dynamic Workers created at this time. Pricing information is shared in advance so you can estimate future costs.

Workflow instances now support pause(), resume(), restart(), and terminate() methods in local development

Workflow instance methods pause(), resume(), restart(), and terminate() are now available in local development when using wrangler dev.

You can now test the full Workflow instance lifecycle locally:

const instance = await env.MY_WORKFLOW.create({
	id: "my-instance-id",
});

await instance.pause(); // pauses a running workflow instance
await instance.resume(); // resumes a paused instance
await instance.restart(); // restarts the instance from the beginning
await instance.terminate(); // terminates the instance immediately

Agents SDK v0.8.0: readable state, idempotent schedules, typed AgentClient, and Zod 4

The latest release of the Agents SDK exposes agent state as a readable property, prevents duplicate schedule rows across Durable Object restarts, brings full TypeScript inference to AgentClient, and migrates to Zod 4.

Readable state on useAgent and AgentClient

Both useAgent (React) and AgentClient (vanilla JS) now expose a state property that reflects the current agent state. Previously, reading state required manually tracking it through the onStateUpdate callback.

React (useAgent)

const agent = useAgent({
	agent: "game-agent",
	name: "room-123",
});

// Read state directly — no separate useState + onStateUpdate needed
return <div>Score: {agent.state?.score}</div>;

// Spread for partial updates
agent.setState({ ...agent.state, score: (agent.state?.score ?? 0) + 10 });
const agent = useAgent<GameAgent, GameState>({
	agent: "game-agent",
	name: "room-123",
});

// Read state directly — no separate useState + onStateUpdate needed
return <div>Score: {agent.state?.score}</div>;

// Spread for partial updates
agent.setState({ ...agent.state, score: (agent.state?.score ?? 0) + 10 });

agent.state is reactive — the component re-renders when state changes from either the server or a client-side setState() call.

Vanilla JS (AgentClient)

const client = new AgentClient({
	agent: "game-agent",
	name: "room-123",
	host: "your-worker.workers.dev",
});

client.setState({ score: 100 });
console.log(client.state); // { score: 100 }
const client = new AgentClient<GameAgent>({
	agent: "game-agent",
	name: "room-123",
	host: "your-worker.workers.dev",
});

client.setState({ score: 100 });
console.log(client.state); // { score: 100 }

State starts as undefined and is populated when the server sends the initial state on connect (from initialState) or when setState() is called. Use optional chaining (agent.state?.field) for safe access. The onStateUpdate callback continues to work as before — the new state property is additive.

Idempotent schedule()

schedule() now supports an idempotent option that deduplicates by (type, callback, payload), preventing duplicate rows from accumulating when called in places that run on every Durable Object restart such as onStart().

Cron schedules are idempotent by default. Calling schedule("0 * * * *", "tick") multiple times with the same callback, expression, and payload returns the existing schedule row instead of creating a new one. Pass { idempotent: false } to override.

Delayed and date-scheduled types support opt-in idempotency:

import { Agent } from "agents";

class MyAgent extends Agent {
	async onStart() {
		// Safe across restarts — only one row is created
		await this.schedule(60, "maintenance", undefined, { idempotent: true });
	}
}
import { Agent } from "agents";

class MyAgent extends Agent {
	async onStart() {
		// Safe across restarts — only one row is created
		await this.schedule(60, "maintenance", undefined, { idempotent: true });
	}
}

Two new warnings help catch common foot-guns:

  • Calling schedule() inside onStart() without { idempotent: true } emits a console.warn with actionable guidance (once per callback; skipped for cron and when idempotent is set explicitly).
  • If an alarm cycle processes 10 or more stale one-shot rows for the same callback, the SDK emits a console.warn and a schedule:duplicate_warning diagnostics channel event.

Typed AgentClient with call inference and stub proxy

AgentClient now accepts an optional agent type parameter for full type inference on RPC calls, matching the typed experience already available with useAgent.

const client = new AgentClient({
	agent: "my-agent",
	host: window.location.host,
});

// Typed call — method name autocompletes, args and return type inferred
const value = await client.call("getValue");

// Typed stub — direct RPC-style proxy
await client.stub.getValue();
await client.stub.add(1, 2);
const client = new AgentClient<MyAgent>({
	agent: "my-agent",
	host: window.location.host,
});

// Typed call — method name autocompletes, args and return type inferred
const value = await client.call("getValue");

// Typed stub — direct RPC-style proxy
await client.stub.getValue();
await client.stub.add(1, 2);

State is automatically inferred from the agent type, so onStateUpdate is also typed:

const client = new AgentClient({
	agent: "my-agent",
	host: window.location.host,
	onStateUpdate: (state) => {
		// state is typed as MyAgent's state type
	},
});
const client = new AgentClient<MyAgent>({
	agent: "my-agent",
	host: window.location.host,
	onStateUpdate: (state) => {
		// state is typed as MyAgent's state type
	},
});

Existing untyped usage continues to work without changes. The RPC type utilities (AgentMethods, AgentStub, RPCMethods) are now exported from agents/client for advanced typing scenarios. agents, @cloudflare/ai-chat, and @cloudflare/codemode now require zod ^4.0.0. Zod v3 is no longer supported.

@cloudflare/ai-chat fixes

  • Turn serializationonChatMessage() and _reply() work is now queued so user requests, tool continuations, and saveMessages() never stream concurrently.
  • Duplicate messages on stop — Clicking stop during an active stream no longer splits the assistant message into two entries.
  • Duplicate messages after tool calls — Orphaned client IDs no longer leak into persistent storage.

keepAlive() and keepAliveWhile() are no longer experimental

keepAlive() now uses a lightweight in-memory ref count instead of schedule rows. Multiple concurrent callers share a single alarm cycle. The @experimental tag has been removed from both keepAlive() and keepAliveWhile().

@cloudflare/codemode: TanStack AI integration

A new entry point @cloudflare/codemode/tanstack-ai adds support for TanStack AI's chat() as an alternative to the Vercel AI SDK's streamText():

import {
	createCodeTool,
	tanstackTools,
} from "@cloudflare/codemode/tanstack-ai";
import { chat } from "@tanstack/ai";

const codeTool = createCodeTool({
	tools: [tanstackTools(myServerTools)],
	executor,
});

const stream = chat({ adapter, tools: [codeTool], messages });
import { createCodeTool, tanstackTools } from "@cloudflare/codemode/tanstack-ai";
import { chat } from "@tanstack/ai";

const codeTool = createCodeTool({
	tools: [tanstackTools(myServerTools)],
	executor,
});

const stream = chat({ adapter, tools: [codeTool], messages });

Upgrade

To update to the latest version:

npm i agents@latest @cloudflare/ai-chat@latest

Manage Cloudflare Tunnels with Wrangler

You can now manage Cloudflare Tunnels directly from Wrangler, the CLI for the Cloudflare Developer Platform. The new wrangler tunnel commands let you create, run, and manage tunnels without leaving your terminal.

Wrangler tunnel commands demo

Available commands:

  • wrangler tunnel create — Create a new remotely managed tunnel.
  • wrangler tunnel list — List all tunnels in your account.
  • wrangler tunnel info — Display details about a specific tunnel.
  • wrangler tunnel delete — Delete a tunnel.
  • wrangler tunnel run — Run a tunnel using the cloudflared daemon.
  • wrangler tunnel quick-start — Start a free, temporary tunnel without an account using Quick Tunnels.

Wrangler handles downloading and managing the cloudflared binary automatically. On first use, you will be prompted to download cloudflared to a local cache directory.

These commands are currently experimental and may change without notice.

To get started, refer to the Wrangler tunnel commands documentation.

@cloudflare/codemode v0.2.1: MCP barrel export, zero-dependency main entry point, and custom sandbox modules

The latest releases of @cloudflare/codemode add a new MCP barrel export, remove ai and zod as required peer dependencies from the main entry point, and give you more control over the sandbox.

New @cloudflare/codemode/mcp export

A new @cloudflare/codemode/mcp entry point provides two functions that wrap MCP servers with Code Mode:

  • codeMcpServer({ server, executor }) — wraps an existing MCP server with a single code tool where each upstream tool becomes a typed codemode.* method.
  • openApiMcpServer({ spec, executor, request }) — creates search and execute MCP tools from an OpenAPI spec with host-side request proxying and automatic $ref resolution.
import { codeMcpServer } from "@cloudflare/codemode/mcp";
import { DynamicWorkerExecutor } from "@cloudflare/codemode";

const executor = new DynamicWorkerExecutor({ loader: env.LOADER });

// Wrap an existing MCP server — all its tools become
// typed methods the LLM can call from generated code
const server = await codeMcpServer({ server: upstreamMcp, executor });
import { codeMcpServer } from "@cloudflare/codemode/mcp";
import { DynamicWorkerExecutor } from "@cloudflare/codemode";

const executor = new DynamicWorkerExecutor({ loader: env.LOADER });

// Wrap an existing MCP server — all its tools become
// typed methods the LLM can call from generated code
const server = await codeMcpServer({ server: upstreamMcp, executor });

Zero-dependency main entry point

Breaking change in v0.2.0: generateTypes and the ToolDescriptor / ToolDescriptors types have moved to @cloudflare/codemode/ai:

// Before
import { generateTypes } from "@cloudflare/codemode";

// After
import { generateTypes } from "@cloudflare/codemode/ai";
// Before
import { generateTypes } from "@cloudflare/codemode";

// After
import { generateTypes } from "@cloudflare/codemode/ai";

The main entry point (@cloudflare/codemode) no longer requires the ai or zod peer dependencies. It now exports:

Export Description
sanitizeToolName Sanitize tool names into valid JS identifiers
normalizeCode Normalize LLM-generated code into async arrow functions
generateTypesFromJsonSchema Generate TypeScript type definitions from plain JSON Schema
jsonSchemaToType Convert a single JSON Schema to a TypeScript type string
DynamicWorkerExecutor Sandboxed code execution via Dynamic Worker Loader
ToolDispatcher RPC target for dispatching tool calls from sandbox to host

The ai and zod peer dependencies are now optional — only required when importing from @cloudflare/codemode/ai.

Custom sandbox modules

DynamicWorkerExecutor now accepts an optional modules option to inject custom ES modules into the sandbox:

const executor = new DynamicWorkerExecutor({
	loader: env.LOADER,
	modules: {
		"utils.js": `export function add(a, b) { return a + b; }`,
	},
});

// Sandbox code can then: import { add } from "utils.js"
const executor = new DynamicWorkerExecutor({
	loader: env.LOADER,
	modules: {
		"utils.js": `export function add(a, b) { return a + b; }`,
	},
});

// Sandbox code can then: import { add } from "utils.js"

Internal normalization and sanitization

DynamicWorkerExecutor now normalizes code and sanitizes tool names internally. You no longer need to call normalizeCode() or sanitizeToolName() before passing code and functions to execute().

Upgrade

npm i @cloudflare/codemode@latest

See the Code Mode documentation for the full API reference.

Access Durable Object name via `ctx.id.name`

When your Worker accesses a Durable Object via idFromName() or getByName(), the same name is now available on ctx.id.name inside the object — no need to pass it through method arguments or persist it in storage. This brings the runtime behavior in line with the Workers runtime types.

This is especially useful for alarms, where there is no calling client to pass the name as an argument. When an alarm handler runs, ctx.id.name will hold the same name the object was originally accessed with.

import { DurableObject } from "cloudflare:workers";

export class ChatRoom extends DurableObject {
  async getRoomName() {
    // ctx.id.name returns the name passed to getByName() or idFromName()
    return this.ctx.id.name;
  }
}

// Worker
export default {
  async fetch(request, env) {
    const stub = env.CHAT_ROOM.getByName("general");
    const roomName = await stub.getRoomName();
    return new Response(`Welcome to ${roomName}!`);
  },
};

ctx.id.name is undefined in the following cases:

  • For Durable Objects created with newUniqueId().
  • When accessed via idFromString(), even if the ID was originally created from a name.
  • For names longer than 1,024 bytes.

This works the same way in local development with wrangler dev as it does in production. Run npm update wrangler to ensure you are on a version with this support.

For more information, refer to the Durable Object ID documentation.

Workflow steps now expose retry attempt number via step context

Cloudflare Workflows allows you to configure specific retry logic for each step in your workflow execution. Now, you can access which retry attempt is currently executing for calls to step.do():

await step.do("my-step", async (ctx) => {
	// ctx.attempt is 1 on first try, 2 on first retry, etc.
	console.log(`Attempt ${ctx.attempt}`);
});

You can use the step context for improved logging & observability, progressive backoff, or conditional logic in your workflow definition.

Note that the current attempt number is 1-indexed. For more information on retry behavior, refer to Sleeping and Retrying.

Workflows step limit increased to 25,000 steps per instance

Each Workflow on Workers Paid now supports 10,000 steps by default, configurable up to 25,000 steps in your wrangler.jsonc file:

{
	"workflows": [
		{
			"name": "my-workflow",
			"binding": "MY_WORKFLOW",
			"class_name": "MyWorkflow",
			"limits": {
				"steps": 25000
			}
		}
	]
}

Previously, each instance was limited to 1,024 steps. Now, Workflows can support more complex, long-running executions without the additional complexity of recursive or child workflow calls.

Note that the maximum persisted state limit per Workflow instance remains 100 MB for Workers Free and 1 GB for Workers Paid. Refer to Workflows limits for more information.

Agents SDK v0.7.0: Observability rewrite, keepAlive, and waitForMcpConnections

The latest release of the Agents SDK rewrites observability from scratch with diagnostics_channel, adds keepAlive() to prevent Durable Object eviction during long-running work, and introduces waitForMcpConnections so MCP tools are always available when onChatMessage runs.

Observability rewrite

The previous observability system used console.log() with a custom Observability.emit() interface. v0.7.0 replaces it with structured events published to diagnostics channels — silent by default, zero overhead when nobody is listening.

Every event has a type, payload, and timestamp. Events are routed to seven named channels:

Channel Event types
agents:state state:update
agents:rpc rpc, rpc:error
agents:message message:request, message:response, message:clear, message:cancel, message:error, tool:result, tool:approval
agents:schedule schedule:create, schedule:execute, schedule:cancel, schedule:retry, schedule:error, queue:retry, queue:error
agents:lifecycle connect, destroy
agents:workflow workflow:start, workflow:event, workflow:approved, workflow:rejected, workflow:terminated, workflow:paused, workflow:resumed, workflow:restarted
agents:mcp mcp:client:preconnect, mcp:client:connect, mcp:client:authorize, mcp:client:discover

Use the typed subscribe() helper from agents/observability for type-safe access:

import { subscribe } from "agents/observability";

const unsub = subscribe("rpc", (event) => {
	if (event.type === "rpc") {
		console.log(`RPC call: ${event.payload.method}`);
	}
	if (event.type === "rpc:error") {
		console.error(
			`RPC failed: ${event.payload.method} — ${event.payload.error}`,
		);
	}
});

// Clean up when done
unsub();
import { subscribe } from "agents/observability";

const unsub = subscribe("rpc", (event) => {
	if (event.type === "rpc") {
		console.log(`RPC call: ${event.payload.method}`);
	}
	if (event.type === "rpc:error") {
		console.error(
			`RPC failed: ${event.payload.method} — ${event.payload.error}`,
		);
	}
});

// Clean up when done
unsub();

In production, all diagnostics channel messages are automatically forwarded to Tail Workers — no subscription code needed in the agent itself:

export default {
	async tail(events) {
		for (const event of events) {
			for (const msg of event.diagnosticsChannelEvents) {
				// msg.channel is "agents:rpc", "agents:workflow", etc.
				console.log(msg.timestamp, msg.channel, msg.message);
			}
		}
	},
};
export default {
	async tail(events) {
		for (const event of events) {
			for (const msg of event.diagnosticsChannelEvents) {
				// msg.channel is "agents:rpc", "agents:workflow", etc.
				console.log(msg.timestamp, msg.channel, msg.message);
			}
		}
	},
};

The custom Observability override interface is still supported for users who need to filter or forward events to external services.

For the full event reference, refer to the Diagnostics channels documentation.

keepAlive() and keepAliveWhile()

Durable Objects are evicted after a period of inactivity (typically 70-140 seconds with no incoming requests, WebSocket messages, or alarms). During long-running operations — streaming LLM responses, waiting on external APIs, running multi-step computations — the agent can be evicted mid-flight.

keepAlive() prevents this by creating a 30-second heartbeat schedule. The alarm firing resets the inactivity timer. Returns a disposer function that cancels the heartbeat when called.

const dispose = await this.keepAlive();
try {
	const result = await longRunningComputation();
	await sendResults(result);
} finally {
	dispose();
}
const dispose = await this.keepAlive();
try {
	const result = await longRunningComputation();
	await sendResults(result);
} finally {
	dispose();
}

keepAliveWhile() wraps an async function with automatic cleanup — the heartbeat starts before the function runs and stops when it completes:

const result = await this.keepAliveWhile(async () => {
	const data = await longRunningComputation();
	return data;
});
const result = await this.keepAliveWhile(async () => {
	const data = await longRunningComputation();
	return data;
});

Key details:

  • Multiple concurrent callers — Each keepAlive() call returns an independent disposer. Disposing one does not affect others.
  • AIChatAgent built-inAIChatAgent automatically calls keepAlive() during streaming responses. You do not need to add it yourself.
  • Uses the scheduling system — The heartbeat does not conflict with your own schedules. It shows up in getSchedules() if you need to inspect it.

For the full API reference and when-to-use guidance, refer to Schedule tasks — Keeping the agent alive.

waitForMcpConnections

AIChatAgent now waits for MCP server connections to settle before calling onChatMessage. This ensures this.mcp.getAITools() returns the full set of tools, especially after Durable Object hibernation when connections are being restored in the background.

export class ChatAgent extends AIChatAgent {
	// Default — waits up to 10 seconds
	// waitForMcpConnections = { timeout: 10_000 };

	// Wait forever
	waitForMcpConnections = true;

	// Disable waiting
	waitForMcpConnections = false;
}
export class ChatAgent extends AIChatAgent {
	// Default — waits up to 10 seconds
	// waitForMcpConnections = { timeout: 10_000 };

	// Wait forever
	waitForMcpConnections = true;

	// Disable waiting
	waitForMcpConnections = false;
}
Value Behavior
{ timeout: 10_000 } Wait up to 10 seconds (default)
{ timeout: N } Wait up to N milliseconds
true Wait indefinitely until all connections ready
false Do not wait (old behavior before 0.2.0)

For lower-level control, call this.mcp.waitForConnections() directly inside onChatMessage instead.

Other improvements

  • MCP deduplication by name and URLaddMcpServer with HTTP transport now deduplicates on both server name and URL. Calling it with the same name but a different URL creates a new connection. URLs are normalized before comparison (trailing slashes, default ports, hostname case).
  • callbackHost optional for non-OAuth serversaddMcpServer no longer requires callbackHost when connecting to MCP servers that do not use OAuth.
  • MCP URL security — Server URLs are validated before connection to prevent SSRF. Private IP ranges, loopback addresses, link-local addresses, and cloud metadata endpoints are blocked.
  • Custom denial messagesaddToolOutput now supports state: "output-error" with errorText for custom denial messages in human-in-the-loop tool approval flows.
  • requestId in chat optionsonChatMessage options now include a requestId for logging and correlating events.

Upgrade

To update to the latest version:

npm i agents@latest @cloudflare/ai-chat@latest

Agents SDK v0.6.0: RPC transport for MCP, optional OAuth, hardened schema conversion, and @cloudflare/ai-chat fixes

The latest release of the Agents SDK lets you define an Agent and an McpAgent in the same Worker and connect them over RPC — no HTTP, no network overhead. It also makes OAuth opt-in for simple MCP connections, hardens the schema converter for production workloads, and ships a batch of @cloudflare/ai-chat reliability fixes.

RPC transport for MCP

You can now connect an Agent to an McpAgent in the same Worker using a Durable Object binding instead of an HTTP URL. The connection stays entirely within the Cloudflare runtime — no network round-trips, no serialization overhead.

Pass the Durable Object namespace directly to addMcpServer:

import { Agent } from "agents";

export class MyAgent extends Agent {
	async onStart() {
		// Connect via DO binding — no HTTP, no network overhead
		await this.addMcpServer("counter", env.MY_MCP);

		// With props for per-user context
		await this.addMcpServer("counter", env.MY_MCP, {
			props: { userId: "user-123", role: "admin" },
		});
	}
}
import { Agent } from "agents";

export class MyAgent extends Agent {
	async onStart() {
		// Connect via DO binding — no HTTP, no network overhead
		await this.addMcpServer("counter", env.MY_MCP);

		// With props for per-user context
		await this.addMcpServer("counter", env.MY_MCP, {
			props: { userId: "user-123", role: "admin" },
		});
	}
}

The addMcpServer method now accepts string | DurableObjectNamespace as the second parameter with full TypeScript overloads, so HTTP and RPC paths are type-safe and cannot be mixed.

Key capabilities:

  • Hibernation support — RPC connections survive Durable Object hibernation automatically. The binding name and props are persisted to storage and restored on wake-up, matching the behavior of HTTP MCP connections.
  • Deduplication — Calling addMcpServer with the same server name returns the existing connection instead of creating duplicates. Connection IDs are stable across hibernation restore.
  • Smaller surface area — The RPC transport internals have been rewritten and reduced from 609 lines to 245 lines. RPCServerTransport now uses JSONRPCMessageSchema from the MCP SDK for validation instead of hand-written checks.

Optional OAuth for MCP connections

addMcpServer() no longer eagerly creates an OAuth provider for every connection. For servers that do not require authentication, a simple call is all you need:

// No callbackHost, no OAuth config — just works
await this.addMcpServer("my-server", "https://mcp.example.com");
// No callbackHost, no OAuth config — just works
await this.addMcpServer("my-server", "https://mcp.example.com");

If the server responds with a 401, the SDK throws a clear error: "This MCP server requires OAuth authentication. Provide callbackHost in addMcpServer options to enable the OAuth flow." The restore-from-storage flow also handles missing callback URLs gracefully, skipping auth provider creation for non-OAuth servers.

Hardened JSON Schema to TypeScript converter

The schema converter used by generateTypes() and getAITools() now handles edge cases that previously caused crashes in production:

  • Depth and circular reference guards — Prevents stack overflows on recursive or deeply nested schemas
  • $ref resolution — Supports internal JSON Pointers (#/definitions/..., #/$defs/..., #)
  • Tuple supportprefixItems (JSON Schema 2020-12) and array items (draft-07)
  • OpenAPI 3.0 nullable: true — Supported across all schema branches
  • Per-tool error isolation — One malformed schema cannot crash the full pipeline in generateTypes() or getAITools()
  • Missing inputSchema fallbackgetAITools() falls back to { type: "object" } instead of throwing

@cloudflare/ai-chat fixes

  • Tool denial flow — Denied tool approvals (approved: false) now transition to output-denied with a tool_result, fixing Anthropic provider compatibility. Custom denial messages are supported via state: "output-error" and errorText.
  • Abort/cancel support — Streaming responses now properly cancel the reader loop when the abort signal fires and send a done signal to the client.
  • Duplicate message persistencepersistMessages() now reconciles assistant messages by content and order, preventing duplicate rows when clients resend full history.
  • requestId in OnChatMessageOptions — Handlers can now send properly-tagged error responses for pre-stream failures.
  • redacted_thinking preservation — The message sanitizer no longer strips Anthropic redacted_thinking blocks.
  • /get-messages reliability — Endpoint handling moved from a prototype onRequest() override to a constructor wrapper, so it works even when users override onRequest without calling super.onRequest().
  • Client tool APIs undeprecatedcreateToolsFromClientSchemas, clientTools, AITool, extractClientToolSchemas, and the tools option on useAgentChat are restored for SDK use cases where tools are defined dynamically at runtime.
  • jsonSchema initialization — Fixed jsonSchema not initialized error when calling getAITools() in onChatMessage.

Upgrade

To update to the latest version:

npm i agents@latest @cloudflare/ai-chat@latest

Better Windows support for Python Workers

Pywrangler, the CLI tool for managing Python Workers and packages, now supports Windows, allowing you to develop and deploy Python Workers from Windows environments. Previously, Pywrangler was only available on macOS and Linux.

You can install and use Pywrangler on Windows the same way you would on other platforms. Specify your Worker's Python dependencies in your pyproject.toml file, then use the following commands to develop and deploy:

uvx --from workers-py pywrangler dev
uvx --from workers-py pywrangler deploy

All existing Pywrangler functionality, including package management, local development, and deployment, works on Windows without any additional configuration.

Requirements

This feature requires the following minimum versions:

  • wrangler >= 4.64.0
  • workers-py >= 1.72.0
  • uv >= 0.29.8

To upgrade workers-py (which includes Pywrangler) in your project, run:

uv tool upgrade workers-py

To upgrade wrangler, run:

npm install -g wrangler@latest

To upgrade uv, run:

uv self update

To get started with Python Workers on Windows, refer to the Python packages documentation for full details on Pywrangler.

Write structured queries to filter and search your Workers logs and traces

Workers Observability now includes a query language that lets you write structured queries directly in the search bar to filter your logs and traces. The search bar doubles as a free text search box — type any term to search across all metadata and attributes, or write field-level queries for precise filtering.

Workers Observability search bar with autocomplete suggestions and Query Builder sidebar filters

Queries written in the search bar sync with the Query Builder sidebar, so you can write a query by hand and then refine it visually, or build filters in the Query Builder and see the corresponding query syntax. The search bar provides autocomplete suggestions for metadata fields and operators as you type.

The query language supports:

  • Free text search — search everywhere with a keyword like error, or match an exact phrase with "exact phrase"
  • Field queries — filter by specific fields using comparison operators (for example, status = 500 or $workers.wallTimeMs > 100)
  • Operators=, !=, >, >=, <, <=, and : (contains)
  • Functionscontains(field, value), startsWith(field, prefix), regex(field, pattern), and exists(field)
  • Boolean logic — add conditions with AND, OR, and NOT

Select the help icon next to the search bar to view the full syntax reference, including all supported operators, functions, and keyboard shortcuts.

Go to the Workers Observability dashboard to try the query language.

No config? No problem. Just `wrangler deploy`

You can now deploy any existing project to Cloudflare Workers — even without a Wrangler configuration file — and wrangler deploy will just work.

Starting with Wrangler 4.68.0, running wrangler deploy automatically configures your project by detecting your framework, installing required adapters, and deploying it to Cloudflare Workers.

Using Wrangler locally

npx wrangler deploy

When you run wrangler deploy in a project without a configuration file, Wrangler:

  1. Detects your framework from package.json
  2. Prompts you to confirm the detected settings
  3. Installs any required adapters
  4. Generates a wrangler.jsonc configuration file
  5. Deploys your project to Cloudflare Workers

You can also use wrangler setup to configure without deploying, or pass --yes to skip prompts.

Using the Cloudflare dashboard

Automatic configuration pull request created by Workers Builds

When you connect a repository through the Workers dashboard, a pull request is generated for you with all necessary files, and a preview deployment to check before merging.

Background

In December 2025, we introduced automatic configuration as an experimental feature. It is now generally available and the default behavior.

If you have questions or run into issues, join the GitHub discussion.