Pi Harness Agents: Lifecycle, Extensions, Sessions, and Recovery
How Cloudflare's PiHarness runs Pi Durable in Workers, with models, tools, sessions, and recovery after eviction.
This page summarizes Cloudflare’s documentation on running the Pi agent harness through PiHarness in the Agents SDK: a long-running agent loop inside a Durable Object, with SQLite-backed transcripts, tools, and wake-up after crashes or eviction. If you are choosing a harness, Cloudflare recommends starting with Pi when you want Pi Durable to own the loop, transcript, and recovery; alternatives such as OpenCodeHarness or a custom loop are documented separately on Harnesses.
Beta PiHarness is beta; Pi Durable is experimental and its API can change as the package matures.
Pi harness and PiHarness: what runs where
Section titled “Pi harness and PiHarness: what runs where”A harness is the turn-by-turn loop around the model: prompts, memory, tools, streaming, persistence, and whether the agent continues or stops. The Agents SDK runtime answers where the agent lives and stays durable; the harness answers what happens on each turn.
A harness is the loop that makes an agent behave like an agent instead of a single model call.
— Cloudflare, Harnesses
Pi runs that loop (transcript, model calls, tools, retries, recovery). PiHarness connects Pi to Cloudflare: Pi’s state lives in the Durable Object’s SQLite database (tables prefixed with pi_), and Lifecycle keeps the object alive while Pi has work.
PiHarness is a new “Lifecycle capability” provided by the Cloudflare Agents SDK. Pi Durable provides the agent harness and the Lifecycle is responsible for keeping the agent running in the Durable Object. The Lifecycle is a core concept in the Agents SDK ensuring that long-running work can run in a Durable Object, surviving restarts, crashes, and network issues.
— Cloudflare, Run the Pi Durable harness on Cloudflare with the Agents SDK
Storage. Transcripts, inbox, and tasks use Pi’s tables in the object’s SQLite. Wake-up. Pi’s in-memory scheduler is lost on eviction; PiHarness schedules a Lifecycle job driven by Pi’s wake(), with heartbeats while work runs and alarms that reopen storage after eviction so a run can continue.
PiHarness does not choose transport—you wire session.events() to WebSockets, HTTP, or RPC yourself (Pi harness).
PiHarness vs Agent class
Section titled “PiHarness vs Agent class”You can mount PiHarness on a plain DurableObject with Lifecycle.install(this).use(this.harness) (Pi harness), or on the SDK Agent class via this.lifecycle.use(this.harness) in the constructor (changelog). Both patterns need the same harness factory: models, registry, and Harness.open().
Install Pi packages: peer dependencies and Wrangler bindings
Section titled “Install Pi packages: peer dependencies and Wrangler bindings”Install the Agents SDK with Pi Durable, Pi AI, and Chord (Chord is listed in the getting started flow and Pi harness install steps):
npm i agents @earendil-works/pi-durable @earendil-works/pi-ai @earendil-works/chordThe three Pi packages are optional peer dependencies of agents (around 1.4.x); install them only when you use this harness (Pi harness). Examples use Workers AI through an AI binding—no separate API keys in the Worker when the binding is configured.
Add at least the AI binding and a SQLite-backed Durable Object class in Wrangler (Pi harness):
{ "ai": { "binding": "AI" }, "durable_objects": { "bindings": [{ "name": "Assistant", "class_name": "Assistant" }] }, "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Assistant"] }]}Run wrangler types so Env includes bindings. For agents that use the Browser tool, also bind browser, worker_loaders (LOADER), and @cloudflare/codemode (legacy browser tools still need it even when browserTool does not use Code Mode).
Create a Pi agent: factory, Lifecycle, and default model
Section titled “Create a Pi agent: factory, Lifecycle, and default model”Creating a Pi agent means configuring the harness factory (model provider, registry, tools), wrapping it in PiHarness, and registering it on Lifecycle (changelog).
The factory receives { storage, context, onWake } and must return Pi’s Harness from Harness.open(). It runs at object startup and again if the harness reopens Pi after a storage error—keep registry.install() idempotent (Pi harness, Extensions).
Typical wiring:
createAI({ binding: this.env.AI })fromagents/models/pi-aicreateModels()+models.setProvider(this.ai.provider)createRegistry()as a per-object class field, not module scope (Extensions)PiHarnessdefaults.modelset to a Pi AI model such asthis.ai("@cf/zai-org/glm-5.3-flash")
Without a default model, prompts stay unanswered until you call session.setModel() (Pi harness).
Extensions: tools, prompt sections, and skills
Section titled “Extensions: tools, prompt sections, and skills”Both tools and system prompt sections reach Pi through extensions: plain objects with a name, tools, and sections, installed on the registry before Harness.open(). PiHarness does not wrap them, so Pi Durable extension features work as documented by Earendil (Extensions).
Register a custom tool
Section titled “Register a custom tool”A tool is a ToolRegistration with typed parameters (validated before execute), optional replay: "safe" for eviction replay, and execute(args, api, context) (Extensions):
api.output()streams progress;api.details()feeds a UI;api.memo()stores values across eviction- Honor
context.abortSignalsosession.abort()can finish cleanly - Parallel tool calls are default; set
executionMode: "sequential"when order matters
Install in the harness factory:
this.registry.install({ name: "editor", sections: [ { key: "preamble", render: () => "You are an editor.", tag: false }, ], tools: [wordCount],});Sections run before each model request; Pi wraps output in <key> tags unless tag: false (Extensions).
Agent Skills and workspace tools
Section titled “Agent Skills and workspace tools”skills(sources) from agents/harness/pi builds an agents.skills extension with activate_skill and read_skill_resource—install inside an async factory because it reads sources (Extensions).
For a @cloudflare/computer workspace, createPiTools() returns declarations plus a shared execute; map them to ToolRegistration objects and mark file tools replay: "safe" where re-running after eviction is harmless (File system).
Browser tool with Pi Durable: bindings and persistence across turns
Section titled “Browser tool with Pi Durable: bindings and persistence across turns”To let Pi choose when to browse, install browserTool({ browser, loader }) on the registry alongside Browser and browserRun(this.env.BROWSER) (Browser). The LOADER binding runs model browser code in a Dynamic Worker per call with no network except through the browser API.
Persistence across prompts works within the browser idle timeout—for example, open a page in one request and screenshot the same tab in the next (Browser):
curl http://localhost:8787 --data 'Open https://example.com and tell me the page title.'curl http://localhost:8787 --data 'Take a screenshot of the page you already opened without navigating again.'Screenshots can return as images in tool results for vision-capable models; HTTP handlers that only return final text need Pi event streaming for a rich UI (Browser).
Sessions: submit, prompt, fork, and event streams
Section titled “Sessions: submit, prompt, fork, and event streams”A session is one Pi conversation. The root session id is "1". Use one Durable Object per user or chat and the root session in each—session ids are assigned by Pi, not chosen by your app (Pi harness).
| Method | Role |
|---|---|
submit(input, options) |
Durably enqueue input; returns a receipt |
prompt(input, options) |
Submit and wait for answer + transcript |
steer(input) |
Submit with whenBusy: "steer" |
messages() / events() |
Transcript entries and live event batches |
setModel(model) |
Change model for this session |
For input your code injects (webhooks, approvals), pass entry: { kind: "app.…", data: … } so the transcript records the source; kinds starting with pi. are reserved. The model still sees normal user text—do not put secrets there (Pi harness).
If a run fails, settings.afterFailedRun (keep, continue, withdraw) controls queued submissions (Pi harness).
Streaming: session.events() yields a snapshot then batches per commit; after object restart, open a new stream (Pi harness).
Limitations and operational trade-offs
Section titled “Limitations and operational trade-offs”Documented limits on Pi harness include:
- No built-in approval step for tool calls yet
- Event streams start from a snapshot only—no cursor resume
abort()waits until tools honor abort signals and return- A single streaming model call beyond roughly 15 minutes may be cut off (alarm handoff every 10 minutes)
- Background task completion may be noticed up to ~30 seconds late on heartbeats
- Session deletion is not supported yet
Retry behavior for transient stream errors ties to Pi harness retry settings and Pi AI’s isRetryableAssistantError() (Pi AI).
Common mistakes
Section titled “Common mistakes”- Registry at module scope — Pi keeps harnesses subscribed until close; use a per-object
createRegistry()field (Extensions). - Missing default model — new sessions fail with
no_modeluntildefaults.modelorsetModelis set. - Factory throws once — the next operation retries startup; avoid side effects that are unsafe to repeat except idempotent
registry.install(). - Ignoring
abortSignalin tools — blocksabort()and keepsbusy()true. - One object name for every user in production — the browser doc’s
getByName("demo")is illustrative; bind object names to authenticated users or workspaces (Browser).
For a full sample with WebSockets, UI, filesystem, and code execution, Cloudflare points to the deployable Pi harness example from Build Agents on Cloudflare and Pi harness.
How to check this on your site
Section titled “How to check this on your site”-
Confirm
package.jsonincludesagents,@earendil-works/pi-durable, and@earendil-works/pi-ai, matching Pi harness install. -
Verify Wrangler has the
AIbinding and SQLite Durable Object migration for your assistant class (Pi harness). -
Run local dev and send a
promptthrough your Worker entrypoint; confirm JSON or streamed events return an assistant answer (Getting started). -
For browser agents, send two prompts to the same Durable Object name within the idle timeout and confirm the second turn reuses the tab (Browser).
-
You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about.