agents-sdk Skill:在 Cloudflare 上构建有状态 AI Agent

前言

用 AI 编程助手写「会记状态、能定时跑任务、还能对外提供工具」的 Agent 时,最容易翻车的不是模型调用本身,而是运行时约定:状态怎么持久化、WebSocket 怎么连、RPC 方法怎么暴露、Durable Object 的 binding / migration 怎么配。Cloudflare Agents SDK 把这些能力放在 Workers 与 Durable Objects 上,API 面宽、文档更新也快,助手若只靠训练时的旧知识,很容易写出过时的装饰器配置、错误的路由,或把实验特性当成稳定 API。

Cloudflare 官方仓库 cloudflare/skills 里提供了名为 agents-sdk 的 Agent Skill。它不是替代 agents npm 包,而是一套在创建有状态 Agent、调度任务、MCP 服务、流式聊天等场景时自动加载的操作指引:要求助手优先检索 Cloudflare Agents 文档,再按当前 API 写代码与 wrangler.jsonc

这是什么

agents-sdk 是 Cloudflare 维护的 Agent Skill(SKILL.md 通用格式),面向在 Cloudflare Workers 上使用 Agents SDK 的开发任务。官方描述触发场景包括:有状态 Agent、durable workflows、实时 WebSocket、定时任务、MCP 服务器、聊天应用、语音 Agent、浏览器自动化等;覆盖 Agent 类、状态管理、@callable RPC、Workflows、durable execution、队列、重试、可观测性以及 React hooks。

该 Skill 有一个明确原则:Prefer retrieval over pre-training。也就是说,写 Agents SDK 相关代码时,应优先从 Cloudflare Agents 文档 取最新信息,而不是依赖模型内置记忆。Skill 内还按主题给出了文档索引表(快速开始、配置、状态、路由、调度、MCP、客户端 SDK 等),方便助手按任务跳转。

它遵循 Agent Skills 开放标准,可在 Claude Code、Cursor、OpenCode、OpenAI Codex、Pi 等支持该标准的工具中使用。

核心功能与亮点

根据官方 SKILL.md,Agents SDK(以及该 Skill 引导助手正确使用的能力)主要包括:

  1. 持久状态:基于 SQLite,通过 setState 写入并自动同步到已连接客户端;也可用 this.sql 做实例内查询。
  2. 可调用 RPC:用 @callable() 把方法暴露给客户端,经 WebSocket 调用;支持流式 RPC。
  3. 调度:一次性延迟(schedule)、cron、以及间隔任务(scheduleEvery)。
  4. Workflows 与 durable executionAgentWorkflow 做多步后台任务;runFiber() / stash() 用于能扛住 Durable Object 驱逐的长任务。
  5. 队列与重试:内置 FIFO queue()this.retry() 带指数退避与 jitter。
  6. MCP:既可作 MCP 客户端连接外部服务器,也可用 McpAgent 自建 MCP 服务器(含传输与安全相关文档入口)。
  7. 聊天与前端AIChatAgent(可恢复流、消息持久化、工具);React 侧 useAgentuseAgentChat
  8. 其它集成:邮件收发、Webhook、Web Push、可观测性(diagnostics_channel);语音、浏览器工具、Think 等标为 experimental,使用前需对照文档。

Skill 还会把助手拉到常见坑上,例如:不要在 tsconfig 里开 experimentalDecorators(会破坏 @callable);不要改旧的 migration,只追加新 tag;每个 Agent 类需要独立的 DO binding 与 migration 条目。

安装与启用

Skill 本身是指示文件;真正跑 Agent 仍依赖项目里安装的 agents 包,以及正确的 Wrangler / Durable Objects 配置。

1. 安装 Cloudflare Skills(含 agents-sdk)

官方 README 给出多种方式,任选其一即可。

npx skills 安装整个仓库(也可只装 agents-sdk):

npx skills add https://github.com/cloudflare/skills
# 仅安装 agents-sdk 时:
# npx skills add https://github.com/cloudflare/skills --skill agents-sdk

Claude Code(插件市场):

/plugin marketplace add cloudflare/skills
/plugin install cloudflare@cloudflare

Cursor:可从 Cursor Marketplace 安装,或在 Settings > Rules > Add Rule > Remote Rule (Github) 中添加 cloudflare/skills

手动拷贝(官方目录对照):

工具 Skill 目录
Claude Code ~/.claude/skills/
Cursor ~/.cursor/skills/
OpenCode ~/.config/opencode/skills/
OpenAI Codex ~/.codex/skills/
Pi ~/.pi/agent/skills/

例如:

git clone https://github.com/cloudflare/skills.git
cp -r skills/skills/agents-sdk ~/.cursor/skills/

安装后,当你让助手「写一个有状态 Agent」「加 @callable」「做 MCP server」「配置 schedule」等,匹配到触发条件时会自动加载;也可在对话里明确要求使用 agents-sdk skill。仓库还提供斜杠命令 /cloudflare:build-agent/cloudflare:build-mcp,用于脚手架式搭建。

2. 确认 Agents SDK 依赖

Skill 要求先核对 npm 包是否已安装:

npm ls agents   # 应能看到 agents 包
# 未安装时:
npm install agents

若做聊天 Agent,官方示例依赖还包括:

npm install agents @cloudflare/ai-chat ai @ai-sdk/react

典型用法示例

下面示例均来自官方 Skill 文档,可直接在 Workers 项目中对照复现。

Wrangler 最小配置

{
  "compatibility_flags": ["nodejs_compat"],
  "durable_objects": {
    "bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }]
  },
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }]
}

需要 Workers AI 时可再增加 "ai": { "binding": "AI" }。每个 Agent 类都要有自己的 binding 与 migration;历史 migration 只追加、不回改。

最小 Agent:状态 + RPC + 路由

import { Agent, routeAgentRequest, callable } from "agents";

type State = { count: number };

export class Counter extends Agent<Env, State> {
  initialState = { count: 0 };

  validateStateChange(nextState: State, source: Connection | "server") {
    if (nextState.count < 0) throw new Error("Count cannot be negative");
  }

  onStateUpdate(state: State, source: Connection | "server") {
    console.log("State updated:", state);
  }

  @callable()
  increment() {
    this.setState({ count: this.state.count + 1 });
    return this.state.count;
  }
}

export default {
  fetch: (req, env) =>
    routeAgentRequest(req, env) ?? new Response("Not found", { status: 404 })
};

默认路由形态为 /agents/{agent-name}/{instance-name},例如类名 Counter 对应 /agents/counter/user-123。服务端也可用 getAgentByName(env.MyAgent, "instance-id")agent.fetch(request) 做自定义入口。

核心 API 速查

任务 API
读状态 this.state.count
写状态 this.setState({ count: 1 })
SQL this.sql`SELECT * FROM users WHERE id = ${id}`
延迟调度 await this.schedule(60, "task", payload)
Cron await this.schedule("0 * * * *", "task", payload)
间隔调度 await this.scheduleEvery(30, "poll")
RPC @callable() myMethod() { ... }
流式 RPC @callable({ streaming: true }) stream(res) { ... }
Workflow await this.runWorkflow("ProcessingWorkflow", params)
Durable fiber await this.runFiber("name", async (ctx) => { ... })
入队 this.queue("handler", payload)
重试 await this.retry(fn, { maxAttempts: 5 })
广播 this.broadcast(message)

React 客户端

import { useAgent } from "agents/react";

function App() {
  const [state, setLocalState] = useState({ count: 0 });

  const agent = useAgent({
    agent: "Counter",
    name: "my-instance",
    onStateUpdate: (newState) => setLocalState(newState),
    onIdentity: (name, agentType) => console.log(`Connected to ${name}`)
  });

  return (
    <button onClick={() => agent.setState({ count: state.count + 1 })}>
      Count: {state.count}
    </button>
  );
}

更完整的聊天、MCP、Workflow、人机确认(human-in-the-loop)等,Skill 通过 references/ 下分主题文档(如 mcp.mdworkflows.mdstreaming-chat.md)引导助手继续检索官方说明,而不是凭记忆拼 API。

适用场景与注意事项

适合:

  • 用 AI 助手在 Cloudflare Workers 上新建或改造有状态 Agent(计数器、会话、协作房间等)
  • 需要调度、队列、可恢复长任务,或把 Agent 做成 MCP 工具提供者 / 消费者
  • 前端要用 useAgent / useAgentChat 做实时状态同步与流式聊天
  • 希望助手在动手前先对齐官方文档与当前 agents 包约定,而不是背旧示例

注意:

  • Skill 指导的是「怎么正确用 Agents SDK」;账号、计费、配额与 Durable Objects 限制仍以 Cloudflare 控制台与官方文档为准。
  • 不要开启 TypeScript experimentalDecorators@callable 依赖正确的装饰器转换(官方 Quick start 也强调 Vite 侧需正确处理装饰器)。
  • migration 只增不改;Agent 类与 DO binding 一一对应。
  • 语音、浏览器自动化、Think 等在 Skill 中标明为 experimental,接入前应再查对应文档页。
  • Agents SDK 与「模型编排框架」关注点不同:前者侧重持久运行时、状态与边缘基础设施;具体推理循环仍可按项目选择 Workers AI 或其他模型提供方。
  • 第三方镜像站上的安装命令若与官方 README 不一致,以 cloudflare/skills 仓库为准。

小结

agents-sdk 把 Cloudflare Agents SDK 的文档索引、安装核对、Wrangler / DO 配置约定,以及状态、RPC、调度、MCP、React 客户端等可复现示例,固化成 Agent 可加载的操作手册:先检索、再落代码,避免用过时知识硬写边缘 Agent。对已经在用或准备上 Cloudflare 有状态 Agent 的开发者来说,把它装进 Cursor / Claude Code / Codex 等工具,能明显减少配置与 API 用法上的低级错误。

官方地址:

  • Skill 目录:https://github.com/cloudflare/skills/tree/main/skills/agents-sdk
  • 仓库说明与安装:https://github.com/cloudflare/skills
  • Agents 文档:https://developers.cloudflare.com/agents/
  • Agents SDK 代码仓库:https://github.com/cloudflare/agents
羽毛球分组比赛记分
小程序二维码

欢迎使用《羽毛球分组比赛记分》微信小程序

小夜