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
羽毛球分组比赛记分
小程序二维码

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

小夜