Durable Agent 是安装了 Agents SDK Lifecycle 的 Durable Object。Lifecycle 会启动你添加到 object 的功能。最重要的是 harness:调用模型、运行 tool 并决定 agent 何时完成的 agent loop。
在本指南中,你将构建一个 agent,它会:
- 在 Durable Object 中运行 Pi harness,
- 处理存储在同一 object 中的 Cloudflare Computer workspace 文件,
- 通过
WebSockets功能与 client 通信。
你不需要 API key。agent 通过 AI binding 使用 Workers AI。
- 一个 Cloudflare 账户 ↗
- Node.js 22.19 或更高版本
-
创建一个 Worker 项目:
npm create cloudflare@latest -- my-agent --type=hello-world --lang=tsyarn create cloudflare my-agent --type=hello-world --lang=tspnpm create cloudflare@latest my-agent --type=hello-world --lang=ts -
转到项目目录并安装 Agents SDK、Pi 软件包和 Cloudflare Computer:
cd my-agentnpm i agents @earendil-works/pi-durable @earendil-works/pi-ai @earendil-works/chord @cloudflare/computeryarn add agents @earendil-works/pi-durable @earendil-works/pi-ai @earendil-works/chord @cloudflare/computerpnpm add agents @earendil-works/pi-durable @earendil-works/pi-ai @earendil-works/chord @cloudflare/computerbun add agents @earendil-works/pi-durable @earendil-works/pi-ai @earendil-works/chord @cloudflare/computerPi 软件包是
agents的可选 peer dependency,版本为~1.4.0。Pi Durable 是实验性功能,其 API 可能在次要版本中发生变化,因此每个agents版本仅支持一个 Pi 次要版本。请安装软件包管理器为agents解析出的版本。
将 AI binding 和基于 SQLite 的 Durable Object 添加到 Wrangler 配置文件:
{
"name": "my-agent",
"main": "src/index.ts",
"upload_source_maps": true,
// Set this to today's date
"compatibility_date": "2026-11-20",
"compatibility_flags": ["nodejs_compat"],
"ai": {
"binding": "AI",
},
"durable_objects": {
"bindings": [{ "name": "Assistant", "class_name": "Assistant" }],
},
"exports": {
"Assistant": { "type": "durable-object", "storage": "sqlite" },
},
}name = "my-agent"
main = "src/index.ts"
upload_source_maps = true
# Set this to today's date
compatibility_date = "2026-11-20"
compatibility_flags = [ "nodejs_compat" ]
[ai]
binding = "AI"
[[durable_objects.bindings]]
name = "Assistant"
class_name = "Assistant"
[exports.Assistant]
type = "durable-object"
storage = "sqlite"ai将 Workers AI binding 添加为env.AI。exports使用"storage": "sqlite"声明该类。生命周期及其功能将数据存储在每个对象的 SQLite 数据库中。请参阅 Durable Object 类导出。agents软件包需要nodejs_compat标志。
将 src/index.ts 替换为运行 Pi harness 的 Assistant Durable Object:
import { DurableObject } from "cloudflare:workers";
import { createModels } from "@earendil-works/pi-ai/models";
import { createRegistry, Harness } from "@earendil-works/pi-durable";
import { PiHarness } from "agents/harness/pi";
import { Lifecycle } from "agents/lifecycle";
import { createAI } from "agents/models/pi-ai";
import { routeAgentRequest } from "agents/routing";
export class Assistant extends DurableObject {
// Workers AI models, through the AI binding
ai = createAI({ binding: this.env.AI });
// Pi's tools and prompt sections. Create one per object.
registry = createRegistry();
// The harness: the Pi agent loop, stored in this object's database
harness = new PiHarness({
harness: ({ storage, context, onWake }) => {
const models = createModels();
models.setProvider(this.ai.provider);
return Harness.open(
storage,
{ models, registry: this.registry, onWake },
context,
);
},
defaults: { model: this.ai("@cf/zai-org/glm-5.3-flash") },
});
// The Lifecycle starts the harness inside the Durable Object
lifecycle = Lifecycle.install(this).use(this.harness);
async onRequest(request) {
if (request.method !== "POST") {
return Response.json(await this.harness.messages());
}
const { status, text } = await this.harness.prompt(await request.text());
return Response.json({ status, text });
}
}
export default {
async fetch(request, env) {
return (
(await routeAgentRequest(request, env)) ??
new Response("Not found", { status: 404 })
);
},
};import { DurableObject } from "cloudflare:workers";
import { createModels } from "@earendil-works/pi-ai/models";
import { createRegistry, Harness } from "@earendil-works/pi-durable";
import { PiHarness } from "agents/harness/pi";
import { Lifecycle } from "agents/lifecycle";
import { createAI } from "agents/models/pi-ai";
import { routeAgentRequest } from "agents/routing";
export class Assistant extends DurableObject<Env> {
// Workers AI models, through the AI binding
readonly ai = createAI({ binding: this.env.AI });
// Pi's tools and prompt sections. Create one per object.
readonly registry = createRegistry();
// The harness: the Pi agent loop, stored in this object's database
readonly harness = new PiHarness({
harness: ({ storage, context, onWake }) => {
const models = createModels();
models.setProvider(this.ai.provider);
return Harness.open(
storage,
{ models, registry: this.registry, onWake },
context,
);
},
defaults: { model: this.ai("@cf/zai-org/glm-5.3-flash") },
});
// The Lifecycle starts the harness inside the Durable Object
readonly lifecycle = Lifecycle.install(this).use(this.harness);
async onRequest(request: Request): Promise<Response> {
if (request.method !== "POST") {
return Response.json(await this.harness.messages());
}
const { status, text } = await this.harness.prompt(await request.text());
return Response.json({ status, text });
}
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
return (
(await routeAgentRequest(request, env)) ??
new Response("Not found", { status: 404 })
);
},
} satisfies ExportedHandler<Env>;各部分的作用如下:
Assistant扩展平台的DurableObject。每个命名实例都是一个 agent,拥有自己的 SQLite 数据库。PiHarness是 harness。它运行 Pi ↗ agent loop,将 transcript 存储在 object 数据库中,并在 object 被逐出内存后继续运行。- 来自
agents/models/pi-ai的createAI()将 Pi 连接到 Workers AI。defaults.model是新 session 启动时使用的模型。 Lifecycle.install(this)接管 object 的fetch和alarmhandler,.use(this.harness)添加 harness。不要在类上自行定义fetch()或alarm()。onRequest()处理没有任何功能处理的 HTTP 请求。POST发送 prompt 并等待答案。GET返回 transcript。routeAgentRequest()将/agents/assistant/:name的请求发送到名为:name的Assistant实例。有关详细信息,请参阅路由。
为 Env 接口生成类型:
npx wrangler types-
启动开发服务器:
npx wrangler devAIbinding 始终在远程运行,因此 Wrangler 首次运行时会要求你登录。 -
在另一个终端中,向名为
demo的 agent 发送 prompt:curl -X POST http://localhost:8787/agents/assistant/demo \ -d "What is 47 times 19? Reply with the number only."{ "status": "done", "text": "893" }模型回答时,
status为done;运行失败或停止时则为unanswered。 -
读取 transcript:
curl http://localhost:8787/agents/assistant/demo
transcript 位于 demo 实例的数据库中。向 /agents/assistant/another-name 发出的请求会访问另一个 agent,其 transcript 为空。
Cloudflare Computer Workspace 是持久文件系统。它将文件存储在同一 Durable Object 的 SQLite 数据库中,与 Pi transcript 相邻,因此文件也能在驱逐后继续存在。
createPiTools() 将 workspace 转换为模型可调用的 tool:read、ls、find、grep、write、edit 和 delete。harness 打开时,将它们安装到 Pi registry 中:
// ...
import { Workspace } from "@cloudflare/computer";
import { createPiTools } from "@cloudflare/computer/tools/pi-ai";
export class Assistant extends DurableObject {
ai = createAI({ binding: this.env.AI });
registry = createRegistry();
// A durable filesystem in the object's SQLite database
workspace = new Workspace({ storage: this.ctx.storage });
harness = new PiHarness({
harness: ({ storage, context, onWake }) => {
const { tools, execute } = createPiTools({ workspace: this.workspace });
this.registry.install({
name: "workspace",
tools: tools.map((tool) => ({
...tool,
async execute(args, api, ctx) {
const { content, isError } = await execute(
{ id: api.callId, name: tool.name, arguments: args },
{ abortSignal: ctx.abortSignal },
);
return { output: content, isError };
},
})),
});
const models = createModels();
models.setProvider(this.ai.provider);
return Harness.open(
storage,
{ models, registry: this.registry, onWake },
context,
);
},
defaults: { model: this.ai("@cf/zai-org/glm-5.3-flash") },
});
// lifecycle and onRequest() are unchanged
}// ...
import { Workspace } from "@cloudflare/computer";
import { createPiTools } from "@cloudflare/computer/tools/pi-ai";
export class Assistant extends DurableObject<Env> {
readonly ai = createAI({ binding: this.env.AI });
readonly registry = createRegistry();
// A durable filesystem in the object's SQLite database
readonly workspace = new Workspace({ storage: this.ctx.storage });
readonly harness = new PiHarness({
harness: ({ storage, context, onWake }) => {
const { tools, execute } = createPiTools({ workspace: this.workspace });
this.registry.install({
name: "workspace",
tools: tools.map((tool) => ({
...tool,
async execute(args, api, ctx) {
const { content, isError } = await execute(
{ id: api.callId, name: tool.name, arguments: args },
{ abortSignal: ctx.abortSignal },
);
return { output: content, isError };
},
})),
});
const models = createModels();
models.setProvider(this.ai.provider);
return Harness.open(
storage,
{ models, registry: this.registry, onWake },
context,
);
},
defaults: { model: this.ai("@cf/zai-org/glm-5.3-flash") },
});
// lifecycle and onRequest() are unchanged
}让 agent 使用它:
curl -X POST http://localhost:8787/agents/assistant/demo \
-d "Write a haiku about Durable Objects to haiku.md, then list the files."Pi 先调用 write,再调用 ls,并使用找到的内容回答。该文件会保留在 demo agent 的 workspace 中,供下一条 prompt 使用。有关其他 workspace 选项(例如运行 JavaScript),请参阅文件系统 tool。
到目前为止,你通过 HTTP 与 agent 通信,每次一个请求。WebSockets 功能会保持连接 open,让浏览器或其他 client 可以发送 prompt 并实时获得回复。空闲连接会休眠,因此 open 连接不会让 object 一直留在内存中。
添加 WebSockets field,并在 harness 之后安装它:
// ...
import { WebSockets } from "agents/websockets";
export class Assistant extends DurableObject {
// ai, registry, workspace, and harness are unchanged
// Clients send prompts and get replies over WebSockets
webSockets = new WebSockets({
handlers: {
onMessage: async (connection, message) => {
const { text } = await this.harness.prompt(String(message));
connection.send(text ?? "");
},
},
});
lifecycle = Lifecycle.install(this).use(this.harness).use(this.webSockets);
// onRequest() is unchanged
}// ...
import { WebSockets } from "agents/websockets";
export class Assistant extends DurableObject<Env> {
// ai, registry, workspace, and harness are unchanged
// Clients send prompts and get replies over WebSockets
readonly webSockets = new WebSockets({
handlers: {
onMessage: async (connection, message) => {
const { text } = await this.harness.prompt(String(message));
connection.send(text ?? "");
},
},
});
readonly lifecycle = Lifecycle.install(this)
.use(this.harness)
.use(this.webSockets);
// onRequest() is unchanged
}WebSockets 接受每个 WebSocket upgrade。HTTP 请求仍会到达 onRequest(),因此 curl 命令仍然有效。
使用 wscat ↗ 连接并输入 prompt:
npx wscat -c ws://localhost:8787/agents/assistant/demoConnected (press CTRL+C to quit)
< {"type":"cf_agent_identity","name":"demo","agent":"assistant"}
> What is in haiku.md?
< ...第一个 frame 是 agent 身份,useAgent 和 AgentClient 等 client 会替你读取。有关 React client,请参阅 client SDK。
以下是完整的 agent:
import { DurableObject } from "cloudflare:workers";
import { Workspace } from "@cloudflare/computer";
import { createPiTools } from "@cloudflare/computer/tools/pi-ai";
import { createModels } from "@earendil-works/pi-ai/models";
import { createRegistry, Harness } from "@earendil-works/pi-durable";
import { PiHarness } from "agents/harness/pi";
import { Lifecycle } from "agents/lifecycle";
import { createAI } from "agents/models/pi-ai";
import { routeAgentRequest } from "agents/routing";
import { WebSockets } from "agents/websockets";
export class Assistant extends DurableObject {
ai = createAI({ binding: this.env.AI });
registry = createRegistry();
// Tools: a durable filesystem in the object's SQLite database
workspace = new Workspace({ storage: this.ctx.storage });
// Harness: the Pi agent loop, with the workspace as its tools
harness = new PiHarness({
harness: ({ storage, context, onWake }) => {
const { tools, execute } = createPiTools({ workspace: this.workspace });
this.registry.install({
name: "workspace",
tools: tools.map((tool) => ({
...tool,
async execute(args, api, ctx) {
const { content, isError } = await execute(
{ id: api.callId, name: tool.name, arguments: args },
{ abortSignal: ctx.abortSignal },
);
return { output: content, isError };
},
})),
});
const models = createModels();
models.setProvider(this.ai.provider);
return Harness.open(
storage,
{ models, registry: this.registry, onWake },
context,
);
},
defaults: { model: this.ai("@cf/zai-org/glm-5.3-flash") },
});
// Capability: clients send prompts and get replies over WebSockets
webSockets = new WebSockets({
handlers: {
onMessage: async (connection, message) => {
const { text } = await this.harness.prompt(String(message));
connection.send(text ?? "");
},
},
});
// Runtime: the Lifecycle starts the harness and the capabilities, and
// handles the object's fetch, alarm, and WebSocket events
lifecycle = Lifecycle.install(this).use(this.harness).use(this.webSockets);
async onRequest(request) {
if (request.method !== "POST") {
return Response.json(await this.harness.messages());
}
const { status, text } = await this.harness.prompt(await request.text());
return Response.json({ status, text });
}
}
export default {
async fetch(request, env) {
return (
(await routeAgentRequest(request, env)) ??
new Response("Not found", { status: 404 })
);
},
};import { DurableObject } from "cloudflare:workers";
import { Workspace } from "@cloudflare/computer";
import { createPiTools } from "@cloudflare/computer/tools/pi-ai";
import { createModels } from "@earendil-works/pi-ai/models";
import { createRegistry, Harness } from "@earendil-works/pi-durable";
import { PiHarness } from "agents/harness/pi";
import { Lifecycle } from "agents/lifecycle";
import { createAI } from "agents/models/pi-ai";
import { routeAgentRequest } from "agents/routing";
import { WebSockets } from "agents/websockets";
export class Assistant extends DurableObject<Env> {
readonly ai = createAI({ binding: this.env.AI });
readonly registry = createRegistry();
// Tools: a durable filesystem in the object's SQLite database
readonly workspace = new Workspace({ storage: this.ctx.storage });
// Harness: the Pi agent loop, with the workspace as its tools
readonly harness = new PiHarness({
harness: ({ storage, context, onWake }) => {
const { tools, execute } = createPiTools({ workspace: this.workspace });
this.registry.install({
name: "workspace",
tools: tools.map((tool) => ({
...tool,
async execute(args, api, ctx) {
const { content, isError } = await execute(
{ id: api.callId, name: tool.name, arguments: args },
{ abortSignal: ctx.abortSignal },
);
return { output: content, isError };
},
})),
});
const models = createModels();
models.setProvider(this.ai.provider);
return Harness.open(
storage,
{ models, registry: this.registry, onWake },
context,
);
},
defaults: { model: this.ai("@cf/zai-org/glm-5.3-flash") },
});
// Capability: clients send prompts and get replies over WebSockets
readonly webSockets = new WebSockets({
handlers: {
onMessage: async (connection, message) => {
const { text } = await this.harness.prompt(String(message));
connection.send(text ?? "");
},
},
});
// Runtime: the Lifecycle starts the harness and the capabilities, and
// handles the object's fetch, alarm, and WebSocket events
readonly lifecycle = Lifecycle.install(this)
.use(this.harness)
.use(this.webSockets);
async onRequest(request: Request): Promise<Response> {
if (request.method !== "POST") {
return Response.json(await this.harness.messages());
}
const { status, text } = await this.harness.prompt(await request.text());
return Response.json({ status, text });
}
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
return (
(await routeAgentRequest(request, env)) ??
new Response("Not found", { status: 404 })
);
},
} satisfies ExportedHandler<Env>;npx wrangler deploy你的 agent 现在运行在 Cloudflare 全球网络上的 https://my-agent.<YOUR_SUBDOMAIN>.workers.dev/agents/assistant/demo。
任何知道该 URL 的人都可以与你的 agent 通信。分享之前,请在 Worker 中检查调用方身份。有关详细信息,请参阅身份验证。
- Pi harness:将事件 streaming 到 client、处理多个 session,并在驱逐后恢复。
- Pi extension:为模型提供更多 tool 和 system prompt section。
Scheduler:按计划运行 agent,例如每天早上制定计划。- 功能:可以添加到 Durable Object 的所有其他内容。