Cloudflare Workers + Sandbox
Deploy to Cloudflare Workers with Durable Object sessions and Cloudflare Sandbox.
The Cloudflare target emits an unbundled Worker entrypoint, a Durable Object session store, and a Cloudflare Sandbox container binding for finite jobs and persistent agents. Wrangler owns the Cloudflare bundle; TechFabric Harness emits the entry, bindings, and config. Each persistent agent/instance pair is routed to one Durable Object, which serializes turns and persists named sessions in Durable Object SQLite.
Finite runs remain authoritative in one Durable Object per run. A separate, singleton
FabricHarnessRunRegistryObject stores only tenant-scoped run pointers so client.runs.list() can
discover runs across those objects. Registry mirror writes are best-effort and never turn a
successful run admission or settlement into a failure. A terminal pointer is an upsert, so it heals
a start pointer lost during a transient registry fault.
Before production, run the live smoke workflow in your Cloudflare account to validate bindings, Durable Object persistence, R2 access, and Sandbox container startup with your account limits.
Quickstart
npx @fabric-harness/cli init --template cloudflare --dir my-edge-agent
cd my-edge-agent
npm install
npx fabric-harness dev --target cloudflare --port 8787The template uses the Cloudflare Workers AI binding (env.AI) so the Worker can run inference without external model API keys.
Required application dependency policy
Use an up-to-date Node.js 22 LTS (22.19+) or Node 24 LTS, with npm or pnpm.
Published package engines accept >=22.19.0; the framework repository's maintenance
range separately excludes Node 23 and 25. As of 2026-10-27, Agents 0.28.0 pins older
MCP peers, and Computer's Bash dependency pins an older Undici. A normal installation without
application overrides still contains high-severity advisories. Framework workspace overrides
don't propagate into published-package consumers.
Fresh Cloudflare templates and Cloudflare recipes emit this explicit application-root policy:
{
"overrides": {
"@modelcontextprotocol/sdk": "^1.32.0",
"@modelcontextprotocol/client": "2.3.0",
"@modelcontextprotocol/server": "2.3.0",
"@modelcontextprotocol/core": "2.3.0",
"undici": "^7.30.1",
"@earendil-works/pi-ai": "~1.1.0",
"@earendil-works/pi-agent-core": "~1.1.0"
},
"pnpm": {
"overrides": {
"@modelcontextprotocol/sdk": "^1.32.0",
"@modelcontextprotocol/client": "2.3.0",
"@modelcontextprotocol/server": "2.3.0",
"@modelcontextprotocol/core": "2.3.0",
"undici": "^7.30.1",
"@earendil-works/pi-ai": "~1.1.0",
"@earendil-works/pi-agent-core": "~1.1.0"
}
}
}For an existing application, review and merge the policy rather than replacing its manifest.
withCloudflareDependencySecurity() from @fabric-harness/node produces a copy with both
policies and preserves unrelated settings. It rejects conflicting pins, unsupported protected-package
override objects, malformed metadata, and direct dependency specifications that don't match the validated
policy. No conflicting user setting is silently replaced. Cloudflare initialization fails before
writing files when an existing manifest lacks the required policy; recipes apply it before installation.
The Cloudflare build artifact also contains the policy because an install inside that artifact is a
separate application root.
Reinstall to refresh the lockfile, then run npm audit --audit-level=high or
pnpm audit --audit-level=high. Neither audit ignores advisories. The packed npm and pnpm proofs
validate zero high/critical findings, public types, offline web behavior, and Pi wire metadata.
These overrides deliberately replace upstream's exact peer pins; they are a Harness-tested policy,
not an upstream compatibility promise or full Agents/live Worker certification. Remaining moderate
findings are reported separately. Yarn and Bun installation aren't validated for this policy.
Remove or update the policy only after fixed upstream releases and the consumer checks pass.
The helper accepts this tested profile (or its documented exact minimum pins). Other versions and wider ranges need separate validation. A refusal identifies a compatibility-policy conflict; it makes no vulnerability assessment of the supplied version. Revalidate the packed consumers before updating the profile. It also applies to portable Agents/Computer integrations in non-Cloudflare deployments, since those install the same transport graph. Existing Yarn/Bun applications must apply and validate their own policy before enabling those integrations.
Application overrides must live at the effective npm/pnpm workspace root.
assertCloudflareApplicationRoot() rejects member directories before init or
recipe writes; run from the root or review and apply the root policy explicitly.
This conservative check rejects any nested application under a workspace root,
even outside its workspace globs. pnpm workspace-file overrides, package extensions,
pnpmfile hooks, and manifest resolutions need manual consolidation before the
automatic policy can validate them. hasCloudflareDependencySecurity() returns
false for missing, malformed, or conflicting manifest policy; use the assertion
and transformation helpers for diagnostics. Init --force replaces the manifest
and skips its existing-policy comparison. The workspace-root guard still applies.
Detached artifacts have an independent npm/pnpm policy, regardless of the source
project's package manager.
The automatic profile does not accept npm $name override references. Use
identical validated direct and override specifications instead. The installed
graph's audit is authoritative, not manifest comparison alone.
Manifest validation is independent of JSON key order.
Build
fh build --target cloudflare
cd .fabricharness/build/cloudflare
npm installOutput:
.fabricharness/build/cloudflare/
dist/worker.ts
wrangler.jsonc
Dockerfile # default Cloudflare Sandbox image
manifest.json
README.cloudflare.mdDevelop locally
fh dev --target cloudflareThis wraps wrangler dev so the same bundler runs in dev and deploy. Two reload paths run simultaneously:
- Wrangler watches the bundle's transitive import graph and reloads
workerdon body edits to your agent files. - TechFabric Harness's structural watcher watches
.fabricharness/jobs/and.fabricharness/agents/, then regenerates the entry whenever the definition set changes.
Net result: you can edit job bodies, add jobs, or change triggers: { webhook: true } without
restarting the dev server.
Or if you've already built once and just want raw wrangler.
npx wrangler devDeploy
fh build --target cloudflare
cd .fabricharness/build/cloudflare
npx wrangler deployRoutes
The Cloudflare Worker exposes both execution models:
GET /health·GET /ready·GET /manifestPOST /jobs/:name: invoke a finite job and receive{ result, runId }POST /jobs/:name?wait=false: admit an asynchronous run; anIdempotency-Keyreuses its runGET /runs?status=&job=&limit=&cursor=: list tenant-visible finite runs in reverse chronological orderGET /runs/:runId·GET /runs/:runId/events?offset=0: inspect finite runs and eventsPOST /runs/:runId/abort: abort an active finite runPOST /agents/:name/:instanceId?wait=falsewith{ message, session? }: durably admit a persistent submissionGET /agents/:name/:instanceId/submissions/:submissionId?session=default: inspect settlementGET /agents/:name/:instanceId/conversation?session=default&offset=0: read the offset streamGET /agents/:name/:instanceId/history?session=default&limit=50: bounded message-windowed historyGET /agents/:name/:instanceId/attachments/:digest?session=default: download a stored attachment as a sandboxed, uncachedcontent-disposition: attachmentresponsePOST /agents/:name/:instanceId/abort?session=default: abort queued or active submissionsGET /agents/:name/:instanceId/schedules·POST /agents/:name/:instanceId/schedules: list or create per-instance wake-up schedulesDELETE /agents/:name/:instanceId/schedules/:scheduleId: cancel a scheduleGET /agents/:name/:instanceId?session=default: inspect a named persistent sessionDELETE /agents/:name/:instanceId?session=default: delete that named sessionGET /sessions/:runId: inspect the stored runGET /sessions/:runId/timeline·/metrics·/tasks·/approvals·/artifacts
Webhook trigger gating applies on the Worker too. In production mode (FABRIC_ENV=production), only
definitions with triggers.webhook === true are exposed publicly.
Persistent instances are tenant-scoped by x-fabric-tenant. The tenant that first admits work to an
instance owns it. Every /agents/:name/:instanceId route (delivery, reads, history, attachments,
submissions, abort, schedules, and delete) answers 404 when the request's tenant differs from the
tenant recorded on the instance or the addressed session. The check is symmetric, like the finite
run routes. A tenant-owned instance is hidden from requests without that tenant, and an unscoped
instance is hidden from tenant-scoped requests.
Cron Triggers
Declare schedules on finite jobs.
export default defineAgent({
name: 'daily-report',
triggers: { schedule: '0 16 * * 1-5' }, // Cloudflare cron is UTC
async run({ input }) {
return buildReport(input);
},
});The Cloudflare build adds each unique expression to wrangler.jsonc and emits scheduled().
Scheduled runs use deterministic IDs, persist run state and offset events in a per-run Durable
Object, and deduplicate repeated delivery of the same occurrence. HTTP and cron execution share the
same job function and { runId, acceptedAt, statusUrl, eventsUrl } receipt contract.
Their pointers are indexed in FABRIC_HARNESS_RUN_REGISTRY, the same registry used by HTTP runs.
Per-instance schedules (Durable Object alarms)
Cron Triggers address finite jobs. Persistent agents get the complementary primitive. A per-instance wake-up backed by the instance Durable Object's alarm. Schedules are stored as rows in the same Durable Object SQLite database as the instance's sessions and submissions, and the single platform alarm is multiplexed across them. It is always armed for the earliest pending wake-up.
# Wake instance "user-42" of agent "support" every hour with an instruction.
curl --fail --request POST http://localhost:8787/agents/support/user-42/schedules \
--header 'content-type: application/json' \
--data '{"everySeconds": 3600, "task": "Check for unresolved threads and follow up."}'
# One-shot, with a small structured payload.
curl --fail --request POST http://localhost:8787/agents/support/user-42/schedules \
--header 'content-type: application/json' \
--data '{"delaySeconds": 900, "task": "Send the promised recap.", "payload": {"thread": "t-123"}}'at (epoch ms, ISO string, or Date), delaySeconds, and everySeconds control timing; everySeconds
makes the schedule recurring (first fire uses at/delaySeconds when given, otherwise one interval
from now). GET lists pending schedules and DELETE .../schedules/:scheduleId cancels one.
When the alarm fires, the Durable Object drains due schedules and admits each as a normal durable
submission whose delivered message is a signal with type: "schedule".
{
kind: 'signal',
type: 'schedule',
body: 'Check for unresolved threads and follow up.', // the task
attributes: { scheduleId, scheduledAt, intervalSeconds, payload },
tagName: 'schedule',
}The wake-up therefore flows through the same admission, FIFO, lease, cancellation, and settlement
path as any HTTP or dispatch interaction: POST .../abort cancels an in-flight scheduled run, the
durability policy of the agent applies, and the signal appears in the instance's conversation stream
where useDelivery() can branch on type === 'schedule'.
Semantics and caveats:
- Cloudflare alarms are at-least-once and retried on handler failure; a wake-up can be delivered more than once after a crash. Recurring schedules advance to their next occurrence when drained, before the run starts, so a crashed wake-up never blocks future occurrences, and occurrences missed while the object was down collapse into a single catch-up wake-up instead of rapid-fire replays.
- Durable Object eviction is not a failure mode: the platform re-instantiates the object when its
alarm fires. Startup also reconciles the alarm against stored schedules, repairing any drift left
by a crash between the storage write and
setAlarm. There is deliberately no watchdog. - Bounds (defaults, configurable on the library coordinator): minimum interval 1 second, payload ≤ 4 KiB, at most 128 schedules per instance. Sub-minute intervals burn Durable Object invocations; prefer Cron Triggers plus a dispatcher job for coarse fleet-wide work.
- Deleting the instance (
DELETE /agents/:name/:instanceId) clears its schedules and unsets the alarm. Schedules live in the instance's Durable Object storage. Wiping that storage loses them, and they do not follow the instance if its Durable Object name changes. - This API is Cloudflare-specific by design. It is exposed by
@fabric-harness/cloudflare(createCloudflareScheduleCoordinator,cloudflareScheduleMessage) and the generated Worker routes; the portable SDK has no Cloudflare dependency, andtriggers.scheduleoncreateAgent()remains unsupported, declare cron on a finite dispatcher job instead.
Hand-written Durable Object hosts
fh build --target cloudflare wires each persistent-agent instance Durable Object out of the same
machinery: Durable Object SQLite persistence stores, a session store with the conversation-stream
projection, a durable submission runner (per-session FIFO, attempt leases, crash reconciliation,
canonical settlement), and the per-instance alarm schedule coordinator. A hand-written Durable
Object (one not produced by fh build) gets the same behavior by composing
createCloudflareDurableObjectHost from @fabric-harness/cloudflare instead of re-implementing the
wiring.
Before (hand-rolled; the drain, admission, and cleanup wiring is yours to get right, and declared
durability bounds are not enforced).
const store = createCloudflareDurableObjectSessionStore(ctx.storage.sql);
const schedules = createCloudflareScheduleCoordinator(ctx.storage.sql, ctx.storage);
async alarm() {
await schedules.reconcile();
const fired = await schedules.drain();
for (const schedule of fired) {
// Render the agent, init it over the store, prompt the session… by hand,
// with no FIFO, lease, settlement, or maxAttempts/timeoutMs enforcement.
await runInteraction(env, store, tenantId(), cloudflareScheduleMessage(schedule));
}
}After (the host packages drain → durable submission, the schedule routes, startup reconciliation, admission with enforcement, and instance-delete cleanup).
import {
createCloudflareDurableObjectHost,
type CloudflareDurableObjectHost,
} from '@fabric-harness/cloudflare';
export class TenantOperatorObject {
private readonly host: CloudflareDurableObjectHost;
constructor(ctx: DurableObjectState, env: Env) {
this.host = createCloudflareDurableObjectHost({
sql: ctx.storage.sql,
alarm: ctx.storage,
objectName: ctx.id.name, // '<agent>:<instanceId>'
agents: { 'tenant-operator': tenantOperator }, // createAgent() results, by name
waitUntil: (promise) => ctx.waitUntil(promise),
execute: async (submission, options) => {
// Your interaction body: render the persistent agent, init it over
// this.host.store, and prompt its session, honoring options.signal,
// options.onInputApplied, and options.takeJoinedInputs.
return runInteraction(env, this.host.store, submission, options);
},
});
ctx.blockConcurrencyWhile(() => this.host.reconcile());
}
async fetch(request: Request): Promise<Response> {
// GET/POST/DELETE /agents/:name/:instanceId/schedules[/:scheduleId].
// Returns undefined for other paths, so custom routes compose freely.
return (
(await this.host.handleSchedulesRoute(request)) ??
new Response('not found', { status: 404 })
);
}
async alarm(): Promise<void> {
// Drains due schedules and admits each as a durable 'schedule'-signal submission.
await this.host.alarm();
}
// Custom RPC methods are unaffected — the host never intercepts them.
async nudge(nudge: TenantOperatorNudge): Promise<unknown> {
const receipt = await this.host.admit({
agent: 'tenant-operator',
id: tenantIdFrom(this.host),
message: nudgeSignal(nudge),
wait: true,
});
return receipt.settlement?.result;
}
}What the host enforces, for alarm-triggered and RPC/HTTP-triggered interactions alike:
- Every admission flows through the durable submission runner: per-session FIFO ordering, attempt
leases with startup and per-request crash reconciliation, idempotent input application, and
canonical settlement records readable through
host.runner/host.executor. - When
agentsis provided, the default admission validator rejects unknown agents, validates initial data and instance-contact preconditions, ensures the instance identity, and stamps the agent's declareddurability: { maxAttempts, timeoutMs }bounds onto the admission, the same policy the generated Worker applies. PassvalidateInputto override; the override then owns durability stamping (seepersistentAgentSubmissionDurabilityin the SDK). host.deleteInstance({ agent, id, session? })refuses while a submission is unsettled (returning the aborted ids), then clears all schedules and the alarm and deletes the instance's submissions, attachments, conversation stream, and instance identity.
What remains the host's composition, exactly as in the generated Worker. The execute body (model,
sandbox, and tool wiring), every non-schedule HTTP route (submissions, conversation, abort, auth,
rate limiting), and any custom RPC surface.
Voice and phone calls
Governed session.voice() runs in a Worker or Durable Object. Pass
socketFactory: createWorkersVoiceSocketFactory() from @fabric-harness/cloudflare/voice to the
built-in voice providers so provider WebSockets upgrade through fetch() instead of the Node ws
peer. For Twilio calls, routeTwilioMediaStream() verifies the Media Streams upgrade in the Worker
and forwards it to one Durable Object per CallSid; handleTwilioMediaStream() accepts the socket in
that object, whose SQLite store backs the governed voice journal. A deploy or eviction drops live
calls, and an active call keeps its object resident because the outbound provider socket can't
hibernate. See Phone calls (Twilio) and the runnable
examples/voice-twilio-cloudflare workspace.
Choosing a Cloudflare sandbox mode
TechFabric Harness supports two Cloudflare sandbox modes.
Containers / Cloudflare Sandbox
Use this mode when your agent needs Linux shell commands, package managers, language toolchains, bash, grep, read, write, and edit tools.
export default {
sandbox: {
backend: 'cloudflare',
mode: 'sandbox',
binding: 'Sandbox',
cwd: '/workspace',
},
};Computer / @cloudflare/computer
Use this early-preview mode when you want a lightweight, SQLite-backed durable Workspace and a
Worker Loader-backed just-bash runtime. It provides the standard bash, grep, glob, read,
write, and edit tools, but it is not a Linux container. Native binaries, package managers, and
language toolchains still require Cloudflare Sandbox.
export default {
sandbox: {
backend: 'cloudflare',
mode: 'computer',
loaderBinding: 'LOADER',
cwd: '/workspace',
},
};The generated wrangler.jsonc adds:
{
"compatibility_flags": ["nodejs_compat", "experimental"],
"worker_loaders": [{ "binding": "LOADER" }]
}Typed Workspace access is exported from @fabric-harness/cloudflare/computer. The generated Worker
also exports WorkspaceServiceProxy and hosts one workspace in each Fabric session Durable Object.
Existing @cloudflare/shell data is not migrated. The old shell-workspace configuration value is
a deprecated alias for one release window.
If Cloudflare sandboxing isn't configured, the Worker falls back to Fabric's empty sandbox.
The build always gives an explicitly configured Cloudflare sandbox precedence over the lightweight
virtual default added by the default-import defineAgent(). This means the same agent source can stay infrastructure-free
locally and use the container or Computer workspace selected by the deployment target without changing
its prompt and session code.
Verify the Sandbox contract
The runnable examples/with-cloudflare-sandbox project includes a
sandbox-certification job. It exercises the same nine behaviors used by the other maintained
remote sandbox adapters:
- shell execution and binary file round trips;
- working-directory and environment propagation;
- stdout/stderr collection;
- timeout and abort, including termination of the native Cloudflare process;
- portable reference encoding, reconnect, and provider cleanup.
Build and run the Worker locally with the actual Cloudflare Sandbox container.
cd examples/with-cloudflare-sandbox
pnpm fh build --target cloudflare
cd .fabricharness/build/cloudflare
pnpm exec wrangler dev --localIn another terminal, request the report.
curl --fail --request POST http://localhost:8787/jobs/sandbox-certification \
--header 'content-type: application/json' \
--data '{"input":{"credentialed":false}}'The response contains a schema-v1, secret-free report with one result per check. A passing report has
ok: true, provider: "cloudflare-sandbox", and nine status: "passed" rows. Protected live CI
uses credentialed: true and retains the same JSON as certification evidence. The generated
container image and @cloudflare/sandbox dependency are kept on the supported 0.9 line so local and
hosted results exercise the same SDK contract.
How it maps to Fabric primitives
| Fabric primitive | Cloudflare equivalent |
|---|---|
| Session store | Durable Object SQLite (one DO per persistent agent instance; finite runs route by run id) |
| Run discovery | Tenant-filtered registry DO containing pointers; per-run DOs remain authoritative |
SandboxEnv | Cloudflare Sandbox container binding via @cloudflare/sandbox, or a durable Computer workspace via @cloudflare/computer |
| Model provider | env.AI Workers AI binding via CloudflareWorkersAIModelProvider (optional; HTTP providers also work) |
| Webhook trigger | POST /jobs/:name |
| Schedule trigger | Worker scheduled() + triggers.schedule |
| Per-instance wake-up | Durable Object alarm + SQLite schedule rows (/agents/:name/:instanceId/schedules) |
| Persistent prompt | POST /agents/:name/:instanceId |
| Health/manifest | GET /health, GET /manifest |
Workers AI binding (no API tokens)
@fabric-harness/cloudflare/workers-ai ships a ModelProvider that routes inference through env.AI.run() instead of HTTP. Zero API tokens, zero egress, runs at the edge. Workers AI accepts the OpenAI Chat Completions request body, so the provider serializes through the SDK's standard OpenAI helpers.
import { CloudflareWorkersAIModelProvider } from '@fabric-harness/cloudflare/workers-ai';
export default {
async fetch(request: Request, env: Env) {
const fabric = await init({
modelProvider: new CloudflareWorkersAIModelProvider({
binding: env.AI,
defaultModel: '@cf/meta/llama-3.1-8b-instruct',
// Optional: route through Cloudflare AI Gateway
// gateway: { id: 'my-gateway', skipCache: false, cacheTtl: 3600 },
}),
});
// ...
},
};Add the binding to wrangler.jsonc:
{
"ai": { "binding": "AI" }
}You can still use HTTP providers (Anthropic, OpenAI-compatible, Vercel AI Gateway) on the Cloudflare target, store the API key as a Workers Secret and reference it via env.
Web search and web fetch
@fabric-harness/cloudflare/web gives an agent web_search and web_fetch, built on the
Cloudflare Agents SDK web tools (agents/websearch, agents/webfetch). The tools work inside a
Worker through the Workers AI binding and anywhere else (Node, CI jobs, containers) through the
Cloudflare REST API, so the same agent can search and read pages from a GitHub Actions job.
web_searchcalls the Cloudflare Web Search API through AI Gateway and returns a numbered list of titles, URLs and trimmed descriptions.web_fetchreads a URL. HTML, PDFs and Office documents are converted to Markdown with Workers AI Markdown Conversion; sites that serve Markdown for Agents answer in Markdown directly. Long pages come back in 20,000-character windows with anoffsetto continue, and the content is wrapped in<untrusted_web_content>.
The tools ship in @fabric-harness/cloudflare 2.7.0 and need @fabric-harness/sdk 6.6.0 or newer,
whose tools receive the call's policy; projects generated by CLI 6.7.6 or newer pin both. DNS-rebinding
pinning (below) needs @fabric-harness/cloudflare 2.7.1 and @fabric-harness/sdk 6.7.0; CLI 6.7.7 pins both. The Agents
SDK is an optional peer dependency, loaded the first time a tool runs:
npm install @fabric-harness/cloudflare agents@0.28Run the bounded, credential-free search → fetch → cached-continuation proof:
pnpm --dir examples/with-cloudflare-web testThe example's runnable guide includes prerequisites, expected output, an explicit optional live REST run, failures, and cleanup. Its fixtures test the real Agents web helpers without Workers globals. The full Agents root, MCP, decorator, and codemode APIs have separate peer requirements; this neutral web integration does not certify those APIs.
Outside a Worker, pass an account ID and an API token:
import { cloudflareWebTools, cloudflareWebToolsFromEnv } from '@fabric-harness/cloudflare/web';
// CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_API_TOKEN (or CLOUDFLARE_API_KEY), CLOUDFLARE_GATEWAY_ID,
// CLOUDFLARE_WEB_SEARCH_PROVIDER. Empty values count as unset.
const tools = cloudflareWebTools(cloudflareWebToolsFromEnv(process.env));
await session.prompt('What changed in Lakebase this month? Cite the pages you read.', { tools });Inside a Worker, pass the binding instead ("ai": { "binding": "AI" } in wrangler.jsonc;
web search needs workerd 1.20260924.1 or later):
const tools = cloudflareWebTools({ binding: env.AI, search: { gateway: 'research', provider: 'exa' } });With defineCloudflareAgent, the tool references search and fetch (or web_search and
web_fetch) turn the tools on with the bundle's credentials, and cloudflare({ ..., web: true })
adds them to a bundle directly.
In a bundle, web_fetch obeys the bundle's network policy, which allows only *.cloudflare.com
and *.workers.dev by default. List the hosts it may read in web.page.allowedHosts (or
CLOUDFLARE_WEB_FETCH_HOSTS, comma separated); they join the allowlist, and * allows any public
host. defineCloudflareAgent rebuilds the tools with the agent's merged policy at init(), so an
agent-level network rule applies too. At each call, web_fetch also checks the calling session's
effective policy (a prompt() policy over the session's over the agent's), which Harness passes to
every tool as context.policy. A session with network: { mode: 'none' } reads nothing. Each
policy is checked on its own, so a session can narrow what the tool may read but never widen it.
| Option | Tool | Default | Effect |
|---|---|---|---|
gateway | search | default | AI Gateway that routes and bills searches. |
provider | search | ceramic | ceramic, exa or linkup. The model never chooses it. |
limit | search | 5 | Results per search and the most the model may ask for, 1 to 10. |
pageChars | fetch | 20000 | Characters per result window. |
maxBytes | fetch | 5000000 | Largest body read. |
allowedHosts, blockedHosts | fetch | any public host | Host patterns; *.example.com matches subdomains. |
policy | fetch | none (bundle: the bundle's) | A CapabilityPolicy, or a list each checked on its own, applied to every page request and redirect hop with the SDK's own checks (DNS answers included when resolveDns is set). A denial is a permanent POLICY_DENIED. |
cachePages | fetch | 8 | Pages kept so reading on with offset does not fetch again. |
Authentication. The REST token needs Workers AI: Read for conversion and, for search,
Workers AI: Read with AI Gateway: Read (an AI Gateway: Run token also searches). The token
is sent only to api.cloudflare.com, never to the pages the tool reads. The tools remove the
configured REST token from provider/transport errors and rendered content, including token-echo
fixtures. This expanded redaction, including redaction before search-description
truncation, is pending the next Cloudflare package release. A custom binding must
keep its own secrets out of returned data and errors.
Credentials are checked when a tool first runs, so importing or constructing a tool needs none.
Cost. Searches bill the gateway's account at the provider's list price with no markup:
Ceramic $0.25, Linkup $5 and Exa $7 per 1,000 requests, from AI Gateway credits (a 5% fee applies
when credits are bought) or a provider key stored on the gateway. Markdown conversion of HTML,
PDF and Office documents is free; web_fetch never sends images for conversion. Results are not
cached by Cloudflare, so a repeated search is billed again.
Limits and failures. The Web Search API does not paginate; the model is told to rephrase. A
search fails with a retryable web_search_timeout after 30 seconds; an empty credit balance is
web_search_payment_required. web_fetch makes GET requests with no cookies or credentials,
refuses private and local hosts, credentials in URLs, URLs over 2,000 characters and https-to-http
redirects; outside Workers it also resolves each host and refuses names that point at private or
local addresses, using the Agents SDK's address classifier (resolveDns: false turns that off).
DNS rebinding (@fabric-harness/cloudflare 2.7.1 with @fabric-harness/sdk 6.7.0 or newer). In Node.js with the default page transport, every page request and redirect hop
goes through the SDK's pinnedFetch: the connection resolves the host once, refuses the request if
any answer is private, loopback, link-local, metadata (169.254.169.254), CGNAT, multicast or an
IPv4-mapped, NAT64 or 6to4 form of one, and dials only the answers that passed. The Host header,
the TLS servername (SNI) and the certificate check keep the URL's host name. A resolver that
answers with a public address for the check and a private one for the connection is refused, with
no unpinned retry. Two cases are not pinned, and keep only the check before each request, which
resolves separately from the connection:
- Cloudflare Workers (and Bun or Deno). A Worker's
fetchresolves the host itself, and the runtime offers no way to choose the address while keeping the host name for SNI and the certificate, so the connection cannot be pinned. Where the DNS check runs there (resolveDnswith your ownresolveHostname), a rebinding resolver can still answer the check and the connection differently. A Worker runs on Cloudflare's network rather than inside yours, so itsfetchdoes not reach your private hosts or a cloud provider's metadata service the way a Node process inside your network would. - A custom
pageFetch. It gets the check before every request and redirect hop but connects by itself. PasspinnedFetch(policy, { resolveHostname })from@fabric-harness/sdkif it must be pinned.
For untrusted workloads, pair either with an egress boundary, as for policiedFetch. The pinned
transport connects directly and does not use HTTP_PROXY or HTTPS_PROXY; behind a required
proxy, pass a pageFetch that uses it.
web_fetch does not run JavaScript: a client-rendered page comes back nearly empty and a bot
challenge fails with web_fetch_blocked. Every failure reaches the model as a
TOOL_EXECUTION_FAILED error naming the SDK's code (a search past its deadline is a retryable
web_search_timeout); cancellation propagates as an abort, to the conversion request as well.
Cached continuations also honor an already-aborted signal and are separated by the calling
session's effective network policy; these continuation guards are pending the next
Cloudflare release. maxBytes bounds downloaded page bytes, including a streamed
body without content-length; it does not cap search bodies or converted Markdown size.
Reading pages from code. A job that reads pages itself, rather than letting the model call
web_fetch, uses the same reader with cloudflareWebPageFetcher(). It applies every check above
and returns the whole page as the Agents SDK read it (content, title, status, finalUrl,
contentType, via), with no windowing and no <untrusted_web_content> wrapper. An error status
is a page, not a failure. A failure is a TOOL_EXECUTION_FAILED whose details.code is the SDK's
code and whose retryable says whether trying again could help, so a caller can tell a page that
is too large (web_fetch_too_large) from an outage worth a fallback (web_fetch_unavailable,
web_fetch_conversion_failed, web_fetch_timeout).
import { cloudflareWebPageFetcher } from '@fabric-harness/cloudflare/web';
const fetchPage = cloudflareWebPageFetcher({ accountId, apiToken, timeoutMs: 30_000 });
const page = await fetchPage({ url }, { signal, policy: { network: { mode: 'allowlist', hosts: ['*.databricks.com'] } } });To check a token against your account (one Ceramic search and two free conversions):
FABRIC_CLOUDFLARE_WEB_TEST=1 CLOUDFLARE_ACCOUNT_ID=<account-id> CLOUDFLARE_API_TOKEN=<token> \
pnpm --filter @fabric-harness/cloudflare test -- web.test.tsAccount validation
Run the Cloudflare smoke in your account before rollout.
FABRIC_CLOUDFLARE_TEST=1 \
FABRIC_CLOUDFLARE_WORKER_URL=https://<worker>.<subdomain>.workers.dev \
FABRIC_CLOUDFLARE_ARTIFACT_DIR=/path/to/.fabricharness/build/cloudflare \
CLOUDFLARE_ACCOUNT_ID=<account-id> \
pnpm --filter @fabric-harness/cloudflare test -- live.test.tsThe repository test suite also runs local workerd tests without account credentials. It admits concurrent persistent requests, verifies FIFO and attachment materialization, aborts finite and persistent work, deletes a session, kills workerd during a tool call, restarts with the same Durable Object storage, and verifies conservative interrupted-tool settlement. The account smoke adds the provider-specific bindings, Sandbox container, and R2 checks.
Limits and considerations
- Worker request/CPU limits apply; long-running workflows belong on the Temporal worker target.
- Persistent turns use a Durable Object submission queue with leases, FIFO execution, restart reconciliation, attachment materialization, abort, deletion, and offset conversation streams.
- Per-instance schedules use the instance Durable Object's single alarm with at-least-once delivery; schedule state lives in Durable Object SQLite and is lost if that storage is wiped.
- The run registry is a discovery index, not a second source of truth. Monitor mirror errors; terminal writes self-heal missing starts, but an account-level outage can temporarily omit an active pointer while direct run-id inspection continues to work.
- Use Temporal when workflows exceed Worker or Durable Object execution/storage limits, require long timers across many external activities, or need Temporal's workflow-history tooling.
- Sandbox container start latency depends on the Cloudflare image; warm pools help.
- Keep
FABRIC_HARNESS_API_TOKEN, body limits, rate limits, andFABRIC_ENV=productiontrigger gating enabled for public deployments. - With
FABRIC_ENV=production, an unset API token fails closed: only/healthand/readyremain reachable without authentication.