任何 Cloudflare Workers 项目都可以托管 Agent。添加一个 Durable Object,或使用现有对象,并在其上安装 Agents SDK Lifecycle。然后按需添加 Agents SDK 功能,例如状态、WebSocket、调度、MCP 客户端或 harness。
你无需更改 Worker 现有路由,也无需将 Durable Object 重写为某个框架类的子类。Lifecycle 会在你的 DurableObject 类中运行。
如果要开始新项目,请改为参阅构建你的第一个 Durable Agent。
- 一个包含 Wrangler 配置文件的 Workers 项目。
- 一个使用 SQLite 存储的 Durable Object 类,或新建一个类。Lifecycle 会将作业队列保存在 SQLite 中,因此无法在基于 KV 的 Durable Object上运行。
- 通过名称寻址的对象,例如使用
getByName()或idFromName()。Lifecycle 会从ctx.id.name读取对象名称;通过newUniqueId()或idFromString()创建的对象没有名称。
npm i agentsyarn add agentspnpm add agentsbun add agentsagents 软件包需要启用 nodejs_compat 兼容性标志。如果 Wrangler 配置中尚未添加,请现在添加:
{
"compatibility_flags": ["nodejs_compat"],
}compatibility_flags = [ "nodejs_compat" ]如果你要使用已有的 Durable Object,可跳过此步骤。
为新类添加绑定,并声明其使用 SQLite 存储。如果 Worker 使用 exports 字段,请在其中添加一项:
{
"durable_objects": {
"bindings": [{ "name": "NOTES", "class_name": "Notes" }],
},
"exports": {
"Notes": { "type": "durable-object", "storage": "sqlite" },
},
}[[durable_objects.bindings]]
name = "NOTES"
class_name = "Notes"
[exports.Notes]
type = "durable-object"
storage = "sqlite"如果 Worker 使用旧版 migrations 数组,请改为添加带有新标签的迁移。Worker 只会使用其中一种,不能同时使用两种:
{
"migrations": [
// ...your existing migrations
{ "tag": "v2", "new_sqlite_classes": ["Notes"] },
],
}[[migrations]]
tag = "v2"
new_sqlite_classes = [ "Notes" ]详情请参阅 Durable Object 类导出。从 Worker 的主模块导出该类,然后运行 npx wrangler types 更新 Env 接口。
在类中添加 lifecycle 字段,并调用 Lifecycle.install(this)。Lifecycle 会安装对象的 fetch、alarm 和 WebSocket 处理程序,在对象处理任何工作前启动一次,并将每个请求交给你的代码。
Lifecycle 只会安装该类尚未定义的处理程序。如果类保留自己的 fetch() 或 alarm(),则会运行这些处理程序,Lifecycle 也不会启动。请将这些代码移到 Lifecycle 钩子中:
| 现有代码 | 移至 |
|---|---|
构造函数中的设置,例如 blockConcurrencyWhile() |
onStart()。对象每次启动时都会运行一次;在其完成之前,Lifecycle 会暂停其他事件。 |
fetch(request) |
onRequest(request)。接收未由任何功能处理的每个请求。 |
alarm() 和 ctx.storage.setAlarm() |
Scheduler 功能或 onAlarm()。Lifecycle 管理对象的闹钟,并根据其作业队列重新设置闹钟。 |
webSocketMessage(), webSocketClose(), webSocketError() |
WebSockets 功能的处理程序。 |
例如,下面是一个存储笔记的 Durable Object:
import { DurableObject } from "cloudflare:workers";
export class Notes extends DurableObject {
constructor(ctx, env) {
super(ctx, env);
ctx.blockConcurrencyWhile(async () => {
this.ctx.storage.sql.exec(
"CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, text TEXT NOT NULL)",
);
});
}
add(text) {
this.ctx.storage.sql.exec("INSERT INTO notes (text) VALUES (?)", text);
}
list() {
return this.ctx.storage.sql
.exec("SELECT text FROM notes ORDER BY id")
.toArray()
.map((row) => row.text);
}
async fetch(request) {
if (request.method === "POST") {
this.add(await request.text());
}
return Response.json(this.list());
}
}import { DurableObject } from "cloudflare:workers";
export class Notes extends DurableObject<Env> {
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env);
ctx.blockConcurrencyWhile(async () => {
this.ctx.storage.sql.exec(
"CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, text TEXT NOT NULL)",
);
});
}
add(text: string): void {
this.ctx.storage.sql.exec("INSERT INTO notes (text) VALUES (?)", text);
}
list(): string[] {
return this.ctx.storage.sql
.exec<{ text: string }>("SELECT text FROM notes ORDER BY id")
.toArray()
.map((row) => row.text);
}
async fetch(request: Request): Promise<Response> {
if (request.method === "POST") {
this.add(await request.text());
}
return Response.json(this.list());
}
}安装 Lifecycle 后,构造函数设置会移至 onStart(),而 fetch() 会改为 onRequest():
import { DurableObject } from "cloudflare:workers";
import { Lifecycle } from "agents/lifecycle";
export class Notes extends DurableObject {
lifecycle = Lifecycle.install(this);
onStart() {
this.ctx.storage.sql.exec(
"CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, text TEXT NOT NULL)",
);
}
add(text) {
this.ctx.storage.sql.exec("INSERT INTO notes (text) VALUES (?)", text);
}
async list() {
// RPC calls do not go through fetch, so start the lifecycle first
await this.lifecycle.start();
return this.ctx.storage.sql
.exec("SELECT text FROM notes ORDER BY id")
.toArray()
.map((row) => row.text);
}
async onRequest(request) {
if (request.method === "POST") {
this.add(await request.text());
}
return Response.json(await this.list());
}
}import { DurableObject } from "cloudflare:workers";
import { Lifecycle } from "agents/lifecycle";
export class Notes extends DurableObject<Env> {
readonly lifecycle = Lifecycle.install(this);
onStart(): void {
this.ctx.storage.sql.exec(
"CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, text TEXT NOT NULL)",
);
}
add(text: string): void {
this.ctx.storage.sql.exec("INSERT INTO notes (text) VALUES (?)", text);
}
async list(): Promise<string[]> {
// RPC calls do not go through fetch, so start the lifecycle first
await this.lifecycle.start();
return this.ctx.storage.sql
.exec<{ text: string }>("SELECT text FROM notes ORDER BY id")
.toArray()
.map((row) => row.text);
}
async onRequest(request: Request): Promise<Response> {
if (request.method === "POST") {
this.add(await request.text());
}
return Response.json(await this.list());
}
}RPC 调用不会经过 fetch(),因此不会启动生命周期。在每个使用 capability 或使用 onStart() 所设置内容的 RPC 方法开头,调用 await this.lifecycle.start()。
并发调用会共用一次启动流程,启动完成后的调用则会立即返回。诸如 scheduler.set() 这样的功能方法会自行启动 Lifecycle。
每项功能都是 Agents SDK 中的一个类。将其创建为字段,并通过 .use() 将其添加到 Lifecycle。此示例添加 Scheduler 功能,使对象可以稍后添加笔记:
import { DurableObject } from "cloudflare:workers";
import { Lifecycle } from "agents/lifecycle";
import { Scheduler } from "agents/schedules";
export class Notes extends DurableObject {
scheduler = new Scheduler({
callbacks: {
remind: (payload) => {
this.add(`Reminder: ${payload.text}`);
},
},
});
lifecycle = Lifecycle.install(this).use(this.scheduler);
async remindLater(text, seconds) {
await this.scheduler.set(seconds, "remind", { text });
}
// onStart(), add(), list(), and onRequest() as before
}import { DurableObject } from "cloudflare:workers";
import { Lifecycle } from "agents/lifecycle";
import { Scheduler } from "agents/schedules";
export class Notes extends DurableObject<Env> {
readonly scheduler = new Scheduler({
callbacks: {
remind: (payload: { text: string }) => {
this.add(`Reminder: ${payload.text}`);
},
},
});
readonly lifecycle = Lifecycle.install(this).use(this.scheduler);
async remindLater(text: string, seconds: number): Promise<void> {
await this.scheduler.set(seconds, "remind", { text });
}
// onStart(), add(), list(), and onRequest() as before
}Lifecycle 会将计划存储在 SQLite 的作业队列中,并设置对象的闹钟。闹钟触发时,如果对象已被逐出内存,Lifecycle 会启动该对象并运行 remind。
通过 RPC 从 Worker 调用 remindLater():
const notes = env.NOTES.getByName("team");
await notes.remindLater("Stand-up", 60);const notes = env.NOTES.getByName("team");
await notes.remindLater("Stand-up", 60);其他功能的安装方式相同:
| 能力 | 导入 | 提供的功能 |
|---|---|---|
State |
agents/state |
一个存储在 SQLite 中并可选择同步到客户端的 JSON 值。 |
WebSockets |
agents/websockets |
可由 useAgent 和 AgentClient 连接的休眠 WebSocket 连接。 |
Scheduler |
agents/schedules |
延迟、定时、间隔和 cron 计划。 |
MCPClientManager |
agents/mcp/client |
与远程 MCP server 的连接。 |
PiHarness |
agents/harness/pi |
带有持久会话的 Pi Agent 循环。 |
功能会按添加顺序运行。有关编写自定义功能的信息,请参阅 Lifecycle。
Worker 可以像现在一样继续向对象发送请求,例如使用 env.NOTES.getByName(name).fetch(request)。Lifecycle 会处理来自任何 stub 的请求和 WebSocket 升级。
要使用 Agents SDK 客户端(agents/react 中的 useAgent 和 agents/client 中的 AgentClient),请使用 routeAgentRequest() 在 /agents/{binding}/{name} 提供对象服务。调用它时应放在现有路由之前:
import { routeAgentRequest } from "agents";
export { Notes } from "./notes";
// routeAgentRequest() matches every Durable Object binding in env.
// Only serve the ones that run the lifecycle.
const AGENT_BINDINGS = new Set(["NOTES"]);
function onlyAgents(_request, route) {
if (!AGENT_BINDINGS.has(route.className)) {
return new Response("Not found", { status: 404 });
}
}
export default {
async fetch(request, env) {
const agentResponse = await routeAgentRequest(request, env, {
onBeforeRequest: onlyAgents,
onBeforeConnect: onlyAgents,
});
if (agentResponse) return agentResponse;
// Your existing routes
return new Response("Not found", { status: 404 });
},
};import { routeAgentRequest } from "agents";
export { Notes } from "./notes";
// routeAgentRequest() matches every Durable Object binding in env.
// Only serve the ones that run the lifecycle.
const AGENT_BINDINGS = new Set(["NOTES"]);
function onlyAgents(_request: Request, route: { className: string }) {
if (!AGENT_BINDINGS.has(route.className)) {
return new Response("Not found", { status: 404 });
}
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const agentResponse = await routeAgentRequest(request, env, {
onBeforeRequest: onlyAgents,
onBeforeConnect: onlyAgents,
});
if (agentResponse) return agentResponse;
// Your existing routes
return new Response("Not found", { status: 404 });
},
} satisfies ExportedHandler<Env>;routeAgentRequest() 会将 env 中的每个 Durable Object 绑定映射到一个 URL。名为 NOTES 的绑定会在 /agents/notes/{name} 提供服务。如果不使用 onBeforeRequest 和 onBeforeConnect 检查,它也会转发发往 Worker 中其他 Durable Objects 的请求。你还可以使用这些钩子,在请求到达对象前检查身份验证。
如果你使用 Hono ↗,hono-agents 软件包中的 agentsMiddleware() 会代为调用 routeAgentRequest()。请传入相同选项:agentsMiddleware({ options: { onBeforeRequest, onBeforeConnect } })。
如果 Worker 提供静态资产,匹配资产的请求会在 Worker 运行前得到处理。为确保 /agents/* 始终交由 Worker 处理,请将其添加到 run_worker_first:
{
"assets": {
"directory": "./public",
"run_worker_first": ["/agents/*"],
},
}[assets]
directory = "./public"
run_worker_first = [ "/agents/*" ]npx wrangler deploy现有 Durable Objects 会保留其数据。Lifecycle 和 Agents SDK 功能会在对象的 SQLite 数据库中添加自己的表,表名以 cf_agents_ 开头;还会添加自己的存储键,键名以 cf_agents: 开头。Harness 使用自己的前缀,例如 Pi harness 使用 pi_。这些组件都不会访问你的表。
从类中移除 fetch()、alarm()、webSocketMessage()、webSocketClose() 和 webSocketError()。如果类已经定义了某个处理程序,Lifecycle 不会替换它。
使用 getByName() 或 idFromName() 寻址对象。通过 newUniqueId() 或 idFromString() 创建的对象没有名称。在本地开发时,请更新 Wrangler 并使用较新的 compatibility_date。
不要自行调用 ctx.storage.setAlarm() 或 ctx.storage.deleteAlarm()。Lifecycle 管理对象的闹钟,直接设置闹钟可能会取消 Lifecycle 的下一次唤醒。请改用 Scheduler 功能或 lifecycle.jobs。
- Lifecycle:请求路径、作业队列以及如何编写自定义功能。
- Pi harness:在同一生命周期中运行 Agent 循环及其工具。
- 测试你的 Agents:使用 Vitest 和 Workers 测试池编写测试。