Skip to content

Changelog

New updates and improvements at Cloudflare.

Browser Run adds structured handoff for Human in the Loop

Browser Run now supports structured handoff for Human in the Loop workflows. Using Cloudflare-specific CDP commands, your agent can signal that it needs help, a human steps in through Live View to handle the task, and the agent resumes once the work is done.

For agents running multi-step browser workflows, a single login wall or unexpected prompt can fail the entire run. Previously, scripts had to manage human intervention manually by sharing a Live View URL and polling for completion. Structured handoff replaces this with a formal pause-and-resume flow.

The following example requests human intervention for a login page and waits for the human to finish before continuing:

const cdp = await page.createCDPSession();

// Get Live View URL for the human operator
const { devtoolsFrontendUrl } = await cdp.send("Cloudflare.getLiveView", {
	mode: "tab",
});
console.log(`Human input needed: ${devtoolsFrontendUrl}`);

// Request human intervention and wait for completion
const handoffComplete = new Promise((resolve) => {
	cdp.once("Cloudflare.handoffComplete", resolve);
});

await cdp.send("Cloudflare.handoff", {
	instructions: "Please log in with your credentials",
	timeout: 600000,
});

const result = await handoffComplete;
console.log(result.success ? "Handoff complete" : `Failed: ${result.reason}`);

Refer to the Human in the Loop documentation for the full API reference, examples, and best practices.

Select models now require the Workers Paid plan

We are limiting Workers Free plan access to a few resource-intensive models so we can prioritize capacity for the broader Workers AI user base. This helps everyone get a more reliable inference experience, with fewer 429 and 3040 (Out of Capacity) errors.

The following models now require the Workers Paid plan:

On the Workers Free plan, requests to these models now return a 403 HTTP error (internal error 5035) prompting you to upgrade. The Workers Paid plan starts at $5 per month and still includes the 10,000 free Neurons per day allocation, with usage beyond that billed at each model's pricing.

Many models remain available on the Workers Free plan, including:

For the full list, refer to the Workers AI model catalog.

Agents SDK adds MCP Specification 2026-07-28 support

Agents SDK v0.20.0 adds client and server support for the MCP 2026-07-28 release candidate. Workers can serve tools, prompts, resources, and elicitation without an MCP transport session or Durable Object. Agents can connect to both MCP 2026-07-28 servers and existing legacy servers.

Client support

The MCP client manager now uses @modelcontextprotocol/client. For each connection, it probes for MCP 2026-07-28 support with server/discover. If the server does not support the stateless protocol, the client continues with the legacy initialize handshake on the same connection. Existing addMcpServer calls do not need a protocol-version setting or separate clients for each protocol generation.

For stateless requests, elicitation uses input_required through multi-round-trip requests (MRTR). The legacy path uses the same form and URL handlers for pushed requests. The SDK collects input, retries the original operation, and resolves the original callTool, getPrompt, or readResource promise with its final result.

OAuth callbacks now validate issuer metadata through the v2 SDK. Discovery state and issuer-bound credentials persist across browser redirects and Durable Object hibernation.

Run stateless servers

createMcpHandler now accepts a factory that returns a server from @modelcontextprotocol/server. The factory creates an isolated server for each request.

import { McpServer } from "@modelcontextprotocol/server";
import { createMcpHandler } from "agents/mcp/server";

function createServer() {
	return new McpServer({ name: "example", version: "1.0.0" });
}

export default {
	fetch(request, env, ctx) {
		return createMcpHandler(createServer)(request, env, ctx);
	},
};
import { McpServer } from "@modelcontextprotocol/server";
import { createMcpHandler } from "agents/mcp/server";

function createServer() {
	return new McpServer({ name: "example", version: "1.0.0" });
}

export default {
	fetch(request, env, ctx) {
		return createMcpHandler(createServer)(request, env, ctx);
	},
} satisfies ExportedHandler;

The isolated agents/mcp/server entry keeps McpAgent, WorkerTransport, MCP client transports, and SDK v1 modules out of stateless server bundles.

The Workers wrapper validates present browser Origins, supports explicit delegation to trusted Origin middleware, and exposes request handling plus typed change notifications.

Backward compatibility

The same createMcpHandler(createServer)(request, env, ctx) route serves MCP 2026-07-28 clients and legacy clients that use stateless requests. You do not need separate routes or tool definitions for ordinary tools, prompts, and resources.

McpAgent is deprecated and feature-frozen. Migrate existing McpAgent servers to the stateless handler at your earliest convenience. If a server depends on protocol sessions, RPC, pushed server-to-client requests, standalone streams, or replay, use the migration guide to design stateless equivalents and run both routes while clients transition.

Migrate existing SDK v1 servers

Upgrade the Agents SDK:

npm i agents@latest

Move ordinary SDK v1 server definitions into an SDK v2 factory and serve them with createMcpHandler. The handler's default legacy compatibility means most stateless deployments need only one route.

If an existing McpAgent server still needs sessionful features, add the stateless path beside it. Use isLegacyRequest() to send only legacy traffic to the existing route:

import { isLegacyRequest } from "@modelcontextprotocol/server";
import { createMcpHandler } from "agents/mcp/server";
import { MyMcpAgent } from "./legacy-server";
import { createServer } from "./server";

const stateless = createMcpHandler(createServer, {
	route: "/mcp",
	legacy: "reject",
});
const legacy = MyMcpAgent.serve("/mcp");

export default {
	async fetch(request, env, ctx) {
		if (await isLegacyRequest(request)) {
			return legacy.fetch(request, env, ctx);
		}
		return stateless(request, env, ctx);
	},
};
import { isLegacyRequest } from "@modelcontextprotocol/server";
import { createMcpHandler } from "agents/mcp/server";
import { MyMcpAgent } from "./legacy-server";
import { createServer } from "./server";

const stateless = createMcpHandler(createServer, {
	route: "/mcp",
	legacy: "reject",
});
const legacy = MyMcpAgent.serve("/mcp");

export default {
	async fetch(request: Request, env: Env, ctx: ExecutionContext) {
		if (await isLegacyRequest(request)) {
			return legacy.fetch(request, env, ctx);
		}
		return stateless(request, env, ctx);
	},
} satisfies ExportedHandler<Env>;

Migrate the remaining sessionful features, allow existing sessions to drain, then remove the legacy route. Refer to Migrate to MCP SDK v2 for package changes, compatibility limits, and rollout steps.

Deprecations in v0.20.0

This release deprecates the following Agents SDK APIs:

Deprecated API Replacement Status
McpAgent Use an SDK v2 factory with createMcpHandler for stateless servers. Use the migration guide to replace stateful features before removing a legacy route. Feature-frozen. No removal version is announced.
createMcpHandler(v1Server, options) Move the server to an SDK v2 factory and call createMcpHandler(factory, options). Use createLegacyMcpHandler only as a temporary bridge for sessionful features. Scheduled for removal in the next major version.
MCPClientManager.callTool(params, resultSchema, options) and the equivalent withX402Client overload Use callTool(params, options) or callTool(confirm, params, options). Compatibility overload. No removal version is announced.

The MCP 2026-07-28 draft separately deprecates Roots, Sampling, Logging, the old HTTP+SSE transport, and Dynamic Client Registration.

Agents SDK packages support AI SDK v6 and v7

The agents, @cloudflare/ai-chat, @cloudflare/codemode, and @cloudflare/think packages now support AI SDK v6 and v7. Existing applications can remain on v6 when updating these packages. Applications can also adopt v7 without changing the Cloudflare Agents APIs they use.

The supported peer ranges are ai@^6 || ^7 and @ai-sdk/react@^3 || ^4. Use matching major versions: pair AI SDK v6 with @ai-sdk/react v3, or pair AI SDK v7 with @ai-sdk/react v4.

To install the latest packages with AI SDK v7:

npm i agents@latest @cloudflare/ai-chat@latest @cloudflare/codemode@latest @cloudflare/think@latest ai@^7 @ai-sdk/react@^4

Think normalizes streaming, tool completion events, and telemetry across both AI SDK versions. Existing v6 applications do not need to migrate these integrations before updating Think.

For setup and usage details, refer to the Think documentation.

Agents SDK reduces MCP schema conversion, adds exposure controls for MCP in Think and Code Mode SDK adds direct host APIs

This release reduces repeated MCP schema conversion and adds an opt-out for Think's automatic MCP tool exposure. It also lets non-AI-SDK hosts invoke the durable Code Mode runtime directly.

Control direct MCP tool exposure in Think

Agents SDK MCP clients now reuse converted input and output schemas while a live connection keeps the same tool catalog. This avoids converting every MCP JSON Schema to Zod again for each model turn.

@cloudflare/think also adds includeMcpTools. Set it to false when you expose MCP tools through Code Mode or another mechanism outside Think's automatic tool set:

import { Think } from "@cloudflare/think";

export class MyAgent extends Think {
	includeMcpTools = false;
	waitForMcpConnections = true;
}
import { Think } from "@cloudflare/think";

export class MyAgent extends Think<Env> {
	includeMcpTools = false;
	waitForMcpConnections = true;
}

This setting skips Think's automatic getAITools() call. MCP registration, restoration, discovery, raw catalog access, direct calls, and Code Mode connectors continue to work.

Use listTools() when you only need the raw MCP catalog. For connector setup, refer to Use MCP tools with Code Mode.

Invoke the Code Mode runtime without the AI SDK

@cloudflare/codemode@latest adds execute(), search(), and describe() to the durable runtime handle. MCP servers and other hosts can now execute code and discover connector methods without adapting the runtime to an AI SDK tool.

const matches = await runtime.search("create issue");
const docs = await runtime.describe(matches.results[0].path);
const outcome = await runtime.execute({
	code: `async () => github.create_issue({ title: "Bug" })`,
});
const matches = await runtime.search("create issue");
const docs = await runtime.describe(matches.results[0].path);
const outcome = await runtime.execute({
	code: `async () => github.create_issue({ title: "Bug" })`,
});

Search and describe results include requiresApproval: true for protected connector methods. Resolve a paused execution with the existing approve() and reject() methods.

For setup and exact method types, refer to Create a durable Code Mode runtime and the Code Mode API reference.

Upgrade

npm i agents@latest @cloudflare/think@latest @cloudflare/codemode@latest

Run Devin on Cloudflare using Devin Outposts

Devin Outposts lets you run Devin agents on Cloudflare. Each Devin session runs in its own isolated sandbox backed by Cloudflare Containers, so agents can execute code and use development tooling in an isolated environment.

Use Devin Outposts when you want Devin sessions to run on Cloudflare managed infrastructure, with each session isolated from the others.

Devin interface showing Cloudflare selected as an Outposts virtual environment

To get started, refer to Run Devin on Cloudflare using Devin Outposts.

Agents can respond to MCP elicitation requests

Agents connected to Model Context Protocol (MCP) servers with addMcpServer can now handle elicitation requests.

Elicitation lets an MCP server request user input while it handles a tool call. Form mode collects structured, non-sensitive data. URL mode asks for consent before opening an out-of-band flow, such as third-party authorization or payment.

sequenceDiagram
    participant User
    participant Agent as Agent (MCP client)
    participant Server as MCP server
    participant Browser

    Server->>Agent: elicitation/create
    Agent->>User: Show server, reason, and input or URL
    User->>Agent: Submit, open, decline, or cancel
    Agent->>Browser: Open URL after consent (URL mode)
    Agent->>Server: accept, decline, or cancel
    Server-->>Agent: Optional URL completion notification

Register a handler for each mode your Agent supports in onStart():

import { Agent } from "agents";

export class MyAgent extends Agent {
	onStart() {
		this.mcp.configureElicitationHandlers({
			form: (request, serverId) => this.forwardToUser(request, serverId),
			url: (request, serverId) => this.forwardToUser(request, serverId),
		});
	}

	forwardToUser(request, serverId) {
		// Show the request in your UI and resolve after the user responds.
		throw new Error(
			`Implement elicitation for ${serverId}: ${request.params.message}`,
		);
	}
}
import { Agent } from "agents";
import type { ElicitRequest, ElicitResult } from "agents/mcp";

export class MyAgent extends Agent<Env> {
	onStart() {
		this.mcp.configureElicitationHandlers({
			form: (request, serverId) => this.forwardToUser(request, serverId),
			url: (request, serverId) => this.forwardToUser(request, serverId),
		});
	}

	private forwardToUser(
		request: ElicitRequest,
		serverId: string,
	): Promise<ElicitResult> {
		// Show the request in your UI and resolve after the user responds.
		throw new Error(
			`Implement elicitation for ${serverId}: ${request.params.message}`,
		);
	}
}

Connections advertise only the modes with configured handlers. An Agent without handlers advertises no elicitation capability, which lets the server use its fallback. The SDK stores the advertised modes with each MCP server registration so they survive Durable Object hibernation. Callback functions remain in memory and reattach when onStart() runs.

For implementation details and a browser forwarding pattern, refer to MCP client elicitation. The mcp-client and mcp-elicitation examples implement both sides.

Upgrade

To update to this release:

npm i agents@latest

Plain text output for Markdown Conversion

The Markdown Conversion service now supports a new output conversion option that controls the format of the converted content.

Set output.format to text to receive plain text with Markdown syntax removed. The default value is markdown, so existing conversions are unchanged.

Use the env.AI binding:

await env.AI.toMarkdown(
	{ name: "page.html", blob: new Blob([html]) },
	{
		conversionOptions: {
			output: { format: "text" },
		},
	},
);
await env.AI.toMarkdown(
	{ name: "page.html", blob: new Blob([html]) },
	{
		conversionOptions: {
			output: { format: "text" },
		},
	},
);

Or call the REST API:

curl https://api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/ai/tomarkdown \
  -H 'Authorization: Bearer {API_TOKEN}' \
  -F 'files=@index.html' \
  -F 'conversionOptions={"output": {"format": "text"}}'

When you request text output, the format field of each result is set to text. For more details, refer to Conversion Options.

Filter AI Search list items by exact object key

In AI Search, you can upload files to an instance, or connect a data source such as an R2 bucket, to make your content searchable with natural language. Each file becomes an item identified by an object key (its filename or path). The list items endpoint returns the items in an instance.

That endpoint now accepts a key query parameter, so you can look up a single item by its exact object key without paging through the full list. This complements the existing item_id filter for when you know the key but not the ID.

curl "https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/ai-search/instances/<INSTANCE_NAME>/items?key=docs/readme.md" \
  -H "Authorization: Bearer <API_TOKEN>"

Keys are unique per data source, so combine key with source (for example, source=builtin) to disambiguate when the same key exists across multiple sources.

For more information, refer to managing items.

Workers AI toMarkdown and AI Search now supports GIF and BMP image conversion

Workers AI Markdown conversion (toMarkdown) now supports .gif and .bmp image files, in addition to the JPEG, PNG, WebP, and SVG formats already supported.

GIF and BMP files run through the same image pipeline as other formats. Each image is resized if needed (and for animated GIFs, only the first frame is used), then passed to an object-detection model to identify what it contains. Those detected objects prompt a vision model that writes a natural-language description of the image, which becomes searchable, machine-readable Markdown.

AI Search uses toMarkdown automatically to process the files it ingests, so any .gif and .bmp files are included the next time your index syncs, with no configuration changes required. This helps when your content mixes formats, for example a support knowledge base full of screenshots or an archive of BMP scans.

Learn more about Markdown conversion and the full list of AI Search's supported file types.

Moondream 3.1 now available on Workers AI

Partnering with Moondream to bring their latest model @cf/moondream/moondream3.1-9B-A2B to Workers AI. Moondream 3.1 is a fast vision language model built on a mixture-of-experts architecture with 9B total parameters and 2B active, delivering frontier-level visual reasoning while retaining fast, cost-efficient inference.

Moondream 3.1 is designed for real-world vision tasks, with a 32K token context window for handling complex queries and structured outputs.

Key capabilities

  • Query — ask open-ended questions about an image, with an optional reasoning parameter
  • Caption — generate short, normal, or long descriptions of an image
  • Point — return coordinates for objects matching a target phrase
  • Detect — return bounding boxes for objects matching a target phrase

Real-time vision at the edge

Vision workloads like live camera feeds, robotics, content moderation, and interactive agents need answers in milliseconds, not seconds. Moondream 3.1's small active footprint (2B active parameters) pairs well with Workers AI's serverless, globally distributed inference: requests run close to your users, and streaming responses start returning tokens almost immediately.

In our testing, first tokens streamed back in roughly 20–30 ms, and results were fast across every task. The example end-to-end times below (client-observed median, including network round trip) are for a simple, single-subject image. Actual latency depends heavily on the image and how much detail you ask for.

Task End-to-end (p50)
query ~770 ms
caption ~480 ms
point ~145 ms
detect ~160 ms

At these speeds you can call the model inline while handling a request rather than pushing the work to a background queue or a separate service. That opens up use cases where a slow response breaks the experience: moderating user-uploaded images before they are stored, locating an object in a video frame to drive a live overlay, extracting fields from a document during a form submission, or letting an agent inspect a screenshot and decide its next step within a single turn.

Get started

Use Moondream 3.1 through the Workers AI binding (env.AI.run()) or the REST API at /ai/run. You can also use AI Gateway with these endpoints.

For more information, refer to the Moondream 3.1 model page and pricing.

New Browser Run endpoint for accessibility trees

Browser Run now supports a standalone /accessibilityTree endpoint, giving agent and automation workflows direct access to the browser's accessibility tree for a rendered webpage.

An accessibility tree is the browser's structured view of a rendered page: roles, names, states, values, and hierarchy. It is useful for accessibility tooling, but also for AI agents and automation workflows that need page structure without the noise of raw HTML or the cost of screenshots.

For AI agents, this means less inference from pixels and less parsing HTML. You can provide the page structure directly, helping agents identify available elements and determine which actions they can take.

With the new /accessibilityTree endpoint, you can request the accessibility tree directly when you only need the semantic structure of a page. If you need multiple page formats in a single API call, you can use the /snapshot endpoint, which also returns Markdown, HTML, and screenshots.

curl -X POST 'https://api.cloudflare.com/client/v4/accounts/<accountId>/browser-run/accessibilityTree' \
  -H 'Authorization: Bearer <apiToken>' \
  -H 'Content-Type: application/json' \
  -d '{
    "url": "https://example.com/"
}'
{
	"success": true,
	"result": {
		"accessibilityTree": {
			"role": "RootWebArea",
			"name": "Example Domain",
			"children": [
				{
					"role": "heading",
					"name": "Example Domain",
					"level": 1
				},
				{
					"role": "link",
					"name": "Learn more"
				}
			]
		}
	}
}

Use interestingOnly to return only semantically meaningful nodes, or root to capture the accessibility tree for a specific subtree.

Refer to the /accessibilityTree documentation for usage examples and supported parameters.

Manage AI Search sync jobs with Wrangler CLI

When you connect a data source to your AI Search instance, AI Search runs sync jobs to keep your index up to date with your content. You can now manage those jobs directly from Wrangler.

For example, you can trigger a sync job from your CI/CD or automated pipelines with the jobs create command so your index refreshes when you push a change:

wrangler ai-search jobs create my-instance

This creates an asynchronous sync job that checks for changes in your data source, and sends new, modified, or deleted files to be indexed. The following commands are available:

Command Description
wrangler ai-search jobs create Trigger a new sync job
wrangler ai-search jobs list List sync jobs for an instance
wrangler ai-search jobs get Get details for a job
wrangler ai-search jobs cancel Cancel a running job
wrangler ai-search jobs logs View log entries for a job

All commands accept --namespace/-n (defaults to default) and --json for structured output that automation and AI agents can parse directly. The list and logs commands also support --page and --per-page for pagination, and cancel prompts for confirmation unless you pass -y/--force.

For full usage details, refer to the AI Search Wrangler commands documentation.

Reduced end-to-end latency for vector changes

We have greatly improved the throughput of the Vectorize write-ahead log (WAL). As a result, we have significantly reduced the end-to-end latency for a vector change to become queryable: median latency has dropped from 2 minutes to under 30 seconds, and p99 latency from 5 minutes to under 2 minutes.

Vectorize p99 WAL batch end-to-end latency improved

This means inserts, upserts, and deletes are reflected in query results faster, improving the freshness of semantic search, recommendation, and retrieval-augmented generation (RAG) workloads. You do not need to change your code or configuration to benefit from this improvement.

For more information, refer to the Vectorize documentation.

Agents SDK adds background sub-agents and a unified turn entry point

The latest release of the Agents SDK makes it easier to run long work in the background, drive turns through one entry point, and keep chat agents working through deploys, evictions, and reconnects.

This release adds first-class detached (background) sub-agent runs with live progress and durable milestones, a single runTurn turn-admission entry point, and a large round of recovery and reliability fixes that continue converging @cloudflare/think and @cloudflare/ai-chat onto one model.

Background sub-agents with progress and milestones

runAgentTool can now dispatch a sub-agent without blocking the calling turn. A detached run returns a handle immediately and is owned by a durable, eviction-surviving backbone instead of being abandoned when the dispatching turn ends.

class OrdersAgent extends Think {
	async startImport(input) {
		// Fire-and-forget, or wire a durable completion callback
		// (by method name, like schedule()):
		await this.runAgentTool(ImportAgent, {
			input,
			detached: { onFinish: "onImportDone", maxBudgetMs: 60 * 60 * 1000 },
		});
	}

	// result.status: "completed" | "error" | "aborted" | "interrupted"
	async onImportDone(run, result) {}
}
class OrdersAgent extends Think {
	async startImport(input) {
		// Fire-and-forget, or wire a durable completion callback
		// (by method name, like schedule()):
		await this.runAgentTool(ImportAgent, {
			input,
			detached: { onFinish: "onImportDone", maxBudgetMs: 60 * 60 * 1000 },
		});
	}

	// result.status: "completed" | "error" | "aborted" | "interrupted"
	async onImportDone(run, result) {}
}

Highlights:

  • Durable, exactly-once-on-the-happy-path completion via a warm fast path plus a self-scheduling reconcile backbone that survives eviction and deploys.
  • Bounded. An absolute maxBudgetMs ceiling (default 24h) and cancelAgentTool(runId) keep abandoned runs from holding a concurrency slot forever.
  • detached: { notify: true } lets a finished background run inject a message back into the chat so the model reacts to the result — no hand-wired onFinish needed.

Sub-agents can also report mid-run progress that rides their own turn stream back to the parent's connected clients:

// Inside the child sub-agent:
await this.reportProgress({
	fraction: 0.6,
	phase: "deploying",
	message: "Generating menu page…",
});
// Inside the child sub-agent:
await this.reportProgress({
	fraction: 0.6,
	phase: "deploying",
	message: "Generating menu page…",
});

Progress surfaces on AgentToolRunState.progress via useAgentToolEvents, so a background-runs tray can render a live bar without drilling in, and the latest snapshot is persisted for inspection after eviction. Naming a milestone promotes a signal to a durable, replayable row, and detached: { onMilestones } can surface a milestone as a synthetic chat message ("narrate" for a cheap status line, or "react" to drive a model turn).

One entry point for turns: runTurn

@cloudflare/think adds a public runTurn(options) facade that unifies turn admission behind a single mode:

await this.runTurn({ mode: "wait", messages }); // saveMessages / continueLastTurn
await this.runTurn({ mode: "submit", messages }); // durable submitMessages
await this.runTurn({ mode: "stream", messages }); // chat()
await this.runTurn({ mode: "wait", messages }); // saveMessages / continueLastTurn
await this.runTurn({ mode: "submit", messages }); // durable submitMessages
await this.runTurn({ mode: "stream", messages }); // chat()

stream mode accepts array and function inputs to match wait mode, and all entry points now route through a shared internal admission path that throws a clear error on nested blocking admissions that previously could deadlock.

Recovery and reliability

A large part of this release continues hardening recovery and converging @cloudflare/think and @cloudflare/ai-chat onto one model:

  • Stream stall watchdog. AIChatAgent can detect and recover from a hung model/transport stream via the opt-in chatStreamStallTimeoutMs watchdog. With chatRecovery enabled the stall routes into the same bounded-recovery machinery a deploy or eviction uses; otherwise it surfaces as a terminal stream error so the spinner clears.
  • Interrupted tool-call repair. AIChatAgent now repairs a transcript with a dead server-tool call before re-entering inference (parity with @cloudflare/think), so a recovered turn no longer fails with AI_MissingToolResultsError. An overridable repairInterruptedToolPart(part) hook lets apps customize the repaired shape.
  • Stuck status after reconnect. Fixed AI SDK status getting stuck when a reconnect races a turn that has been accepted but has not started streaming yet, so the UI now renders the in-flight turn instead of settling on ready.
  • Live "recovering…" on connect. AIChatAgent now replays the recovering status to a client that connects mid-recovery, so useAgentChat's isRecovering reflects in-progress recovery immediately instead of appearing frozen.
  • Terminal connection failures. The client stops reconnecting on terminal WebSocket close events and exposes them via connectionError / onConnectionError on AgentClient, useAgent, and useAgentChat.
  • Agent-tool child recovery. A healthy long-running sub-agent run is no longer abandoned as interrupted after a deploy (both @cloudflare/think and AIChatAgent).
  • Workflows from sub-agent facets. Agent Workflows can now start from sub-agent facets, with callbacks and Workflow RPC routed back to the originating facet.
  • Plus forward-progress crediting convergence, broadcast-first give-up ordering, an event-driven auto-continuation barrier, and structured row-size compaction in AIChatAgent.

Other improvements

  • Shared chat React core. A new agents/chat/react entry exposes useAgentChat, transport helpers, and shared wire types, with syncMessagesToServer for server-authoritative transcript storage. @cloudflare/think/react and @cloudflare/ai-chat/react are now thin wrappers over it.
  • Optional ai peer. The root agents and @cloudflare/codemode runtimes no longer reference AI SDK types, so they bundle without ai / zod installed; AI-specific entry points still require the peer when imported. just-bash likewise moves to an optional peer used only by the skills bash runner.
  • Code Mode. The default DynamicWorkerExecutor timeout increases from 30s to 60s, executions now dispose the dynamically-loaded Worker and its RPC stub after each run (fixing a flaky isolate-shutdown assertion), connector imports are cleaned up, and the outer MCP tool-call context is passed to openApiMcpServer request callbacks.
  • Voice. Voice turns now support AI SDK fullStream responses (and warn when textStream is used).
  • MCP. McpAgent server-to-client requests can now be sent from callbacks that do not inherit the agent's async context, including callbacks reached through Worker Loader RPC.
  • Experimental: server actions and channels. This release lays groundwork for guarded server actions (action() / getActions() with a durable replay ledger and approvals) and a unified channels surface (configureChannels(), deliverNotice()). Both are experimental and their APIs may change, so we don't recommend depending on them yet.

Upgrade

To update to the latest version:

npm i agents@latest @cloudflare/think@latest @cloudflare/ai-chat@latest @cloudflare/codemode@latest @cloudflare/voice@latest

Refer to the Think documentation, Code Mode documentation, and Agents documentation for more information.

Control AI Search similarity cache freshness

AI Search now gives you more control over similarity cache freshness. Similarity cache helps reduce latency and inference cost by reusing responses for semantically similar queries.

With these updates, you can choose how long responses are eligible for reuse and clear cached responses when they may be stale.

Cache duration now defaults to 48 hours

Previously, AI Search cached responses for a fixed duration of 30 days. Cached responses now use the instance's cache_ttl setting, and the default is 48 hours.

You can set cache_ttl when creating or updating an instance to choose a cache duration from 10 minutes to 6 days.

Use a shorter TTL when your source content changes frequently and freshness is more important. Use a longer TTL when your content is stable and you want more cache reuse.

For example, set cache_ttl to 518400 to retain cached responses for 6 days:

{
	"cache_ttl": 518400
}

Purge cached responses

You can also purge all cached responses for an instance on demand. Purging cached responses does not delete indexed content or source files.

It prevents AI Search from reusing previous cached responses, so subsequent similar queries generate fresh answers and repopulate the cache.

curl -X POST "https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/ai-search/instances/$INSTANCE_NAME/purge_cache" \
  -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"

You can also purge cached responses from the instance settings page in the Cloudflare dashboard.

Refer to similarity cache for the full list of supported cache_ttl values and more details about cache behavior.

Agents SDK improves browser automation, code execution, and recovery

The latest release of the Agents SDK makes it easier to build agents that can safely interact with real systems and keep working through interruptions.

Agents can now browse websites through Browser Run, write code against external tools through Code Mode, use client-provided tools when delegating to Think sub-agents, and recover more reliably from deploys, Durable Object evictions, and connection churn.

Safer browser automation

Agents can now use Browser Run through a single durable browser_execute tool. Instead of choosing from a fixed list of actions, the model writes code against the Chrome DevTools Protocol (CDP) and can inspect pages, capture screenshots, read rendered content, debug frontend behavior, and interact with live browser sessions.

const browserTools = createBrowserTools({
	ctx: this.ctx,
	browser: this.env.BROWSER,
	loader: this.env.LOADER,
	session: { mode: "dynamic" },
});
const browserTools = createBrowserTools({
	ctx: this.ctx,
	browser: this.env.BROWSER,
	loader: this.env.LOADER,
	session: { mode: "dynamic" },
});

Browser sessions can be one-time, reused, or promoted from one-time to persistent during a run. This is useful when an agent needs a human to log in, complete MFA, or approve a sensitive action. The run can pause, keep the same tabs and cookies, and resume after approval.

The browser tools also add Live View URLs, optional session recording, and quick actions such as browser_markdown, browser_extract, browser_links, and browser_scrape for one-shot browsing tasks.

Resumable code execution with approvals

Code Mode now uses createCodemodeRuntime, connectors, and a durable execution log. This lets you give a model one codemode tool instead of a large prompt full of tool definitions. The model can discover the capabilities it needs, write code against typed globals, and reuse saved snippets.

const runtime = createCodemodeRuntime({
	ctx: this.ctx,
	executor: new DynamicWorkerExecutor({ loader: this.env.LOADER }),
	connectors: [new GithubConnector(this.ctx, this.env, connection)],
});

const result = streamText({
	model,
	messages,
	tools: { codemode: runtime.tool() },
});
const runtime = createCodemodeRuntime({
	ctx: this.ctx,
	executor: new DynamicWorkerExecutor({ loader: this.env.LOADER }),
	connectors: [new GithubConnector(this.ctx, this.env, connection)],
});

const result = streamText({
	model,
	messages,
	tools: { codemode: runtime.tool() },
});

When the code reaches an approval-gated action, the runtime pauses execution and returns a pending approval. After approval, completed calls replay from the durable log, the approved action runs, and the same code continues. This makes it practical to build agents that create issues, update external systems, or perform other side effects without custom pause-and-resume logic for every tool.

Better Think delegation

Think sub-agents can now use client-defined tools over the RPC chat() path. A parent agent can pass tool schemas with clientTools and resolve tool calls through onClientToolCall. This lets delegated agents use caller-provided capabilities without requiring a browser WebSocket.

await child.chat(message, callback, {
	signal,
	clientTools: [
		{
			name: "get_user_timezone",
			description: "Get the caller's timezone",
			parameters: { type: "object" },
		},
	],
	onClientToolCall: async ({ toolName, input }) => {
		return runClientTool(toolName, input);
	},
});
await child.chat(message, callback, {
	signal,
	clientTools: [
		{
			name: "get_user_timezone",
			description: "Get the caller's timezone",
			parameters: { type: "object" },
		},
	],
	onClientToolCall: async ({ toolName, input }) => {
		return runClientTool(toolName, input);
	},
});

Think Workflows also improve step.prompt(). A prompt step now runs a full agentic turn before returning structured output, so the agent can call tools before producing the typed result. This makes Workflow steps more useful for durable triage, research, and approval flows.

The unified Think execute tool can also include cdp.* browser capabilities alongside state.* and tools.* when Browser Run is bound.

Voice output device selection

Voice clients can route assistant audio to a specific output device. Use outputDeviceId with useVoiceAgent, or call client.setOutputDevice() from the framework-agnostic client.

const voice = useVoiceAgent({
	agent: "MyVoiceAgent",
	outputDeviceId: selectedSpeakerId,
});
const voice = useVoiceAgent({
	agent: "MyVoiceAgent",
	outputDeviceId: selectedSpeakerId,
});

Browsers without speaker-selection support continue playing through the default output device and report a non-fatal outputDeviceError.

Reliability fixes

This release includes several fixes for production agents:

  • useAgent and AgentClient handle WebSocket replacement more reliably during reconnects and configuration changes.
  • Chat stream replay is more reliable after reconnects, deploys, and provider errors.
  • Fiber recovery continues across multi-pass scans and backs off when recovery hooks keep failing.
  • Agent teardown continues even when the request that started teardown is canceled.
  • Large session histories use byte-budgeted reads to reduce memory pressure during startup.

Upgrade

To update to the latest version:

npm i agents@latest @cloudflare/think@latest @cloudflare/codemode@latest @cloudflare/ai-chat@latest @cloudflare/voice@latest

Refer to the Code Mode documentation, Browser tools documentation, Think tools documentation, and Voice documentation for more information.

Pay Per Crawl advanced configuration

You can now configure advanced Pay Per Crawl settings for your zone, including:

  • Disable Pay Per Crawl by URI pattern using Configuration Rules to offer free access to specific pages while charging for others.
  • Dynamic pricing by having your origin return a crawler-price response header, or by using a Cloudflare Worker to set prices based on request properties.

When dynamic pricing is enabled, Pay Per Crawl adds a cf-pay-per-crawl request header to origin requests so your origin or Worker can determine the appropriate price.

Refer to the Advanced configuration documentation for details.

Introducing GLM-5.2 on Workers AI

We are excited to announce GLM-5.2 on Workers AI, Z.ai's flagship agentic coding model.

@cf/zai-org/glm-5.2 is a text generation model built for agentic coding workflows. With function calling and reasoning support, it can handle long codebases, multi-step planning, and tool-augmented agents.

Key features and use cases:

  • Agentic coding: Designed for autonomous coding tasks, long-horizon planning, and complex software engineering workflows
  • Large context window: GLM-5.2 supports up to a 1,048,576 token context window. Workers AI is launching the model with a 262,144 token context window and plans to increase this in the future
  • Function calling: Build agents that invoke tools and APIs across multiple conversation turns
  • Reasoning: Tackles complex problem-solving and step-by-step reasoning tasks

Use GLM-5.2 through the Workers AI binding (env.AI.run()), the REST API at /run or /v1/chat/completions, or AI Gateway.

Pricing is available on the model page or pricing page.

View the user agent of requests in AI Gateway logs

AI Gateway logs now capture the user agent of the client that made each request, making it easier to identify which SDK, library, or application sent the traffic flowing through your gateway. For example, you can tell apart requests coming from openai-python versus a custom application or a Cloudflare Worker.

The user agent appears alongside the other details in each log entry, and you can filter logs by user agent (equals, does not equal, or contains) in the dashboard.

For more information, refer to Logging.

Moonshot AI Kimi K2.7 Code now available on Workers AI

@cf/moonshotai/kimi-k2.7-code is now available on Workers AI. Kimi K2.7 Code is a code-optimized variant of the Kimi K2 family, built on a Mixture-of-Experts architecture with 1T total parameters and 32B active per token.

Improved coding and agent performance

K2.7 Code delivers meaningful gains over K2.6 on coding and agentic benchmarks:

  • +21.8% on Kimi Code Bench v2
  • +11.0% on Program Bench
  • +31.5% on MLS Bench Lite

Reasoning efficiency

K2.7 Code uses 30% fewer reasoning tokens compared to K2.6, reducing overthinking and lowering inference cost for reasoning-heavy workloads.

Key capabilities

  • 262.1k token context window for retaining full conversation history, tool definitions, and codebases across long-running agent sessions
  • Long-horizon coding with improved instruction following and higher end-to-end coding task success rates
  • Vision inputs for processing images alongside text
  • Thinking mode with configurable reasoning depth via chat_template_kwargs.thinking
  • Multi-turn tool calling for building agents that invoke tools across multiple conversation turns
  • Structured outputs with JSON schema support

Differences from Kimi K2.6

If you are migrating from Kimi K2.6, note the following:

  • K2.7 Code is optimized for coding tasks with improved benchmark performance and reasoning efficiency
  • Cached input token pricing is $0.19 per M tokens (vs $0.16 for K2.6)
  • API usage is identical — no parameter changes required

Get started

Use Kimi K2.7 Code through the Workers AI binding (env.AI.run()), the REST API at /ai/run, or the OpenAI-compatible endpoint at /v1/chat/completions. You can also use AI Gateway with any of these endpoints.

For more information, refer to the Kimi K2.7 Code model page and pricing.

New formats parameter for the Browser Run /snapshot endpoint

Browser Run's /snapshot endpoint now supports a formats parameter that lets you return multiple page formats in a single API call. Previously, /snapshot returned only HTML content and a screenshot. You can now also include Markdown and the accessibility tree in the same response.

These formats are particularly useful for AI agent workflows:

  • Markdown provides a token-efficient representation of page content that LLMs can process directly, without parsing HTML markup.
  • The accessibility tree provides a structured representation of a page's elements, including roles, labels, and hierarchy, helping LLMs understand page structure and navigate its contents.

The following example returns a screenshot, Markdown, and the accessibility tree in one call:

curl -X POST 'https://api.cloudflare.com/client/v4/accounts/<accountId>/browser-rendering/snapshot' \
  -H 'Authorization: Bearer <apiToken>' \
  -H 'Content-Type: application/json' \
  -d '{
    "url": "https://example.com/",
    "formats": ["screenshot", "markdown", "accessibilityTree"]
  }'
import Cloudflare from "cloudflare";

const client = new Cloudflare({
	apiToken: process.env["CLOUDFLARE_API_TOKEN"],
});

const snapshot = await client.browserRendering.snapshot.create({
	account_id: process.env["CLOUDFLARE_ACCOUNT_ID"],
	url: "https://example.com/",
	formats: ["screenshot", "markdown", "accessibilityTree"],
});

console.log(snapshot.markdown);
console.log(snapshot.accessibilityTree);
interface Env {
	BROWSER: BrowserRun;
}

export default {
	async fetch(request, env): Promise<Response> {
		return await env.BROWSER.quickAction("snapshot", {
			url: "https://example.com/",
			formats: ["screenshot", "markdown", "accessibilityTree"],
		});
	},
} satisfies ExportedHandler<Env>;

You must request at least two formats. If you only need one, use the respective single-format endpoint such as /screenshot or /markdown.

Refer to the /snapshot documentation for the full list of accepted values.

Manage AI Search namespaces with Wrangler CLI

AI Search now supports namespace-level Wrangler commands, making it easier to manage namespaces from your terminal, scripts, and agent workflows.

The following commands are available:

Command Description
wrangler ai-search namespace list List AI Search namespaces
wrangler ai-search namespace create Create a new AI Search namespace
wrangler ai-search namespace get Get details for a namespace
wrangler ai-search namespace update Update a namespace description
wrangler ai-search namespace delete Delete an AI Search namespace

Create a namespace for a new application or tenant directly from the CLI:

wrangler ai-search namespace create docs-production --description "Production documentation search"

List namespaces with pagination or filter by name or description:

wrangler ai-search namespace list --search docs --page 1 --per-page 10

Use --json with list, create, get, and update to return structured output that automation and AI agents can parse directly.

Instance-level commands also now support a --namespace flag, so you can interact with instances inside a specific namespace from the CLI:

wrangler ai-search list --namespace docs-production

For full usage details, refer to the AI Search Wrangler commands documentation.

Deprecating Sandbox SDK features

Today we are announcing the deprecation of several features from the Sandbox SDK. The SDK has grown and matured substantially since it first launched. As agent workflows have developed, we have shipped many new features and experiments so developers can easily integrate secure, isolated code execution into their workflows.

We want the SDK to continue providing a stable foundation for agentic workflows while we iterate quickly on the codebase. These deprecated features have either been superseded by newer capabilities or seen low adoption. Do not build new work on them. Migrate using the 2026 deprecation migration guide, or move to the Sandbox SDK 1.0 preview when you can.

HTTP and WebSocket transports

In April 2026, we released the new RPC transport and deprecated the WebSocket transport. This setting governs how the sandbox container talks to the Workers ecosystem. The RPC transport removes the limitations of both the HTTP and WebSocket transports. As of this announcement, RPC is the recommended default. HTTP and WebSocket transports are deprecated and will not ship in future Sandbox SDK majors.

To migrate, update the SANDBOX_TRANSPORT variable to rpc or set the transport option when calling getSandbox(). For more information, refer to the transport configuration documentation.

Desktop

The desktop feature ran a full Linux desktop inside the sandbox (display server, desktop environment, and VNC/noVNC) so agents and apps could drive a GUI with screenshots, mouse, and keyboard — the same computer-use shape other sandbox products expose for UI automation. Adoption stayed low, and we removed it in 0.10.2. If you need that capability again, you can build it on top of the sandbox with extensions rather than a built-in sandbox.desktop API.

Expose ports

We recently released support for Cloudflare Tunnel in the Sandbox SDK. This provides a robust API for exposing services running in your sandbox to the public internet. It fixes issues many were facing with local development and deployment to workers.dev domains. To migrate from exposePort() to tunnels, refer to the tunnels API documentation and the expose services guide.

Default sessions

By default, the exec() method in the Sandbox SDK maintains a default session across all calls, so a cd in one call is honored in the next. This convenience helped developers writing exec statements by hand, but confused agents and caused hard-to-trace bugs. As of 0.10.3, we have introduced the enableDefaultSession flag on the getSandbox() interface to turn this off. Default sessions as a concept — and the flag — will be removed in an upcoming release.

We recommend setting enableDefaultSession: false today and using the sandbox.createSession() API when you need the previous behavior.

Other changes

We are also consolidating all APIs that buffer data to support streaming by default. This includes readFile, writeFile, and exec. The stream equivalents will be removed.

We are exploring moving non-core features like the code interpreter, terminal, and git APIs into helpers. These features will retain their existing APIs, so migration should be simple.

Next steps

If you use any of these features on the current stable package, refer to the 2026 deprecation migration guide. Coding agents can use the sandbox-stable skill for stable-package work and that guide for cleanup (Agent setup · Cloudflare Skills).

If you are moving to Sandbox SDK 1.0 (@next), use the 1.0 preview and Migrate guides instead — or the sandbox-migrate-to-next skill after installing Cloudflare Skills. New projects should prefer sandbox-next on @next.

For any questions, ask in the Cloudflare Developers Discord.

Control AI costs with spend limits

AI Gateway now supports spend limits — cost-based budgets that track cumulative dollar spend and block requests when the budget is exceeded. Unlike rate limiting, which caps the number of requests, spend limits track actual cost based on token usage and model pricing.

You can scope limits by model, provider, or custom metadata dimensions. For example, give each user a $200/day budget, cap total gateway spend at $10,000/day, or limit a specific model to $50/day per user. Each rule uses a configurable time window with fixed or sliding enforcement.

Spend limits work with both Unified Billing and BYOK requests for models with known pricing.

For more details, refer to the Spend limits documentation.