OpenAICloudflare Developer PlatformMar 23, 2026, 12:00 AM

Agents, Workers - Agents SDK v0.8.0: readable state, idempotent schedules, typed AgentClient, and Zod 4

A condensed section focused on the key takeaways first.

Original Post

Quick Digest

Summary

A condensed section focused on the key takeaways first.

openaienmodel: gpt-5-mini-2025-08-07

Agents SDK v0.8.0: readable state, idempotent schedules, typed AgentClient, and Zod 4

Key Points

  • agent.state is readable in useAgent and AgentClient
  • schedule(..., {idempotent:true}) prevents duplicate schedule rows
  • AgentClient gains full TypeScript inference and stub proxy

Summary

Agents SDK v0.8.0 adds readable agent state on both useAgent (React) and AgentClient (vanilla JS), introduces idempotent scheduling to avoid duplicate Durable Object schedule rows, brings full TypeScript inference and a stub proxy to AgentClient, and upgrades several packages to Zod v4. The release also includes reliability fixes (AI chat and keepAlive) and a new TanStack AI integration for @cloudflare/codemode.

Key Points

  • Readable state

    • useAgent and AgentClient expose a reactive state property (agent.state) populated from initialState or setState().
    • State starts undefined — use optional chaining (agent.state?.field) for safe access.
    • onStateUpdate remains supported and typed when using generics.
  • Idempotent schedule()

    • schedule(..., { idempotent: true }) deduplicates schedule rows by (type, callback, payload) to avoid accumulation across Durable Object restarts.
    • Cron schedules are idempotent by default; delayed/date schedules support opt-in idempotency.
    • Calling schedule repeatedly with the same parameters returns the existing row; pass { idempotent: false } to override.
    • New console warnings: missing idempotent in onStart(), and duplicate-row warnings when many stale rows are processed.
  • Typed AgentClient and RPC stubs

    • AgentClient accepts an optional agent generic for full call/stub inference; stub exposes RPC-style proxy methods.
    • State and onStateUpdate become typed from the agent type.
    • Advanced RPC types (AgentMethods, AgentStub, RPCMethods) are exported from agents/client.
  • Zod migration

    • agents, @cloudflare/ai-chat, and @cloudflare/codemode now require zod ^4.0.0; Zod v3 is no longer supported. Update dependencies accordingly.
  • Other notable changes

    • @cloudflare/ai-chat: serialization and duplicate-message bugs fixed (queued onChatMessage/_reply, stop behavior, tool call persistence).
    • keepAlive() / keepAliveWhile(): removed experimental tag; now use in-memory ref counting (no schedule rows) and share a single alarm cycle.
    • @cloudflare/codemode/tanstack-ai: new entry point to integrate TanStack AI's chat() as an alternative streaming adapter.

Migration & Upgrade

  • Run: npm i agents@latest @cloudflare/ai-chat@latest
  • Ensure your projects and dependencies use zod ^4.0.0 and update TypeScript typings where you adopt AgentClient generics.

Practical tips for engineers

  • Replace onStateUpdate-only patterns with agent.state and optional chaining for concise reads and partial state spreads for updates.
  • Make schedule calls in onStart() idempotent to avoid duplicate one-shot rows across restarts.
  • Add the agent generic to AgentClient for editor autocompletion and safer RPC usage.
  • Verify third-party libraries that depend on Zod and bump to v4 before upgrading the SDK.

Full Translation

Translations

A translation section that keeps the flow of the original article.

openaijamodel: gpt-5-mini-2025-08-07

Agents SDK v0.8.0:読み取り可能な状態、冪等なスケジュール、型付き AgentClient、Zod 4

Agents SDK v0.8.0: readable state, idempotent schedules, typed AgentClient, and Zod 4

公開日: 2026-03-23

最新の Agents SDK ↗ リリースでは、エージェントの状態が読み取り可能なプロパティとして公開され、Durable Object の再起動時にスケジュール行が重複して蓄積されるのを防ぐ冪等性オプション、AgentClient に対する完全な TypeScript 推論の導入(型付き AgentClient)、および Zod 4 への移行が含まれます。

useAgent と AgentClient の読み取り可能な状態

React の useAgent と Vanilla JS の AgentClient は、現在のエージェント状態を反映する state プロパティを持つようになりました。以前は状態を読むために onStateUpdate コールバックで手動で追跡する必要がありました。

  • agent.state はリアクティブです。サーバーからの更新やクライアント側の setState() 呼び出しによりコンポーネントが再レンダリングされます。
  • 初期は stateundefined で、接続時にサーバーが送る initialState または setState() 呼び出しで設定されます。
  • 安全にアクセスするためにオプショナルチェイニング(agent.state?.field)を使ってください。
  • 既存の onStateUpdate コールバックはこれまで通り動作し、state プロパティは追加的に利用できます。

React (useAgent) 例

// JavaScript
const agent = useAgent({ agent: "game-agent", name: "room-123" });
// 状態を直接読む — 別途 useState + onStateUpdate は不要
return <div>Score: {agent.state?.score}</div>;
// 部分更新のスプレッド
agent.setState({ ...agent.state, score: (agent.state?.score ?? 0) + 10 });

// TypeScript
const agent = useAgent<GameAgent, GameState>({ agent: "game-agent", name: "room-123" });
return <div>Score: {agent.state?.score}</div>;
agent.setState({ ...agent.state, score: (agent.state?.score ?? 0) + 10 });

Vanilla JS (AgentClient) 例

// JavaScript
const client = new AgentClient({ agent: "game-agent", name: "room-123", host: "your-worker.workers.dev" });
client.setState({ score: 100 });
console.log(client.state); // { score: 100 }

// TypeScript
const client = new AgentClient<GameAgent>({ agent: "game-agent", name: "room-123", host: "your-worker.workers.dev" });
client.setState({ score: 100 });
console.log(client.state); // { score: 100 }

冪等な schedule() の導入

schedule()idempotent オプションが追加され、(type, callback, payload) による重複排除を行います。これにより、onStart() のように Durable Object が再起動するたびに実行される箇所でスケジュール行が重複して蓄積されるのを防げます。Cron スケジュールはデフォルトで冪等です。

  • 同じコールバック、式、ペイロードで schedule("0 * * * *", "tick") を複数回呼ぶと、新しい行を作成せず既存の行を返します。
  • オーバーライドしたい場合は { idempotent: false } を渡してください。
  • 遅延(delay)や日時指定(date-scheduled)タイプはオプトインの冪等性をサポートします。

例(onStart 内で安全に呼べる):

import { Agent } from "agents";
class MyAgent extends Agent {
  async onStart() {
    // 再起動しても1行だけ作成される
    await this.schedule(60, "maintenance", undefined, { idempotent: true });
  }
}

さらに、一般的なミスを検出するための新しい警告が追加されました。

  • onStart() 内で { idempotent: true } なしに schedule() を呼ぶと、実行可能なガイダンスを含む console.warn が出力されます(コールバックごとに一度だけ。cron と明示的に idempotent が設定されている場合はスキップ)。
  • あるアラームサイクルで同じコールバックに対して10個以上の古いワンショット行が処理されると、SDK は console.warnschedule:duplicate_warning の diagnostics チャネルイベントを発行します。

型付けされた AgentClient(call 推論と stub プロキシ)

AgentClient はオプショナルなエージェント型パラメータを受け取るようになり、RPC 呼び出しに対して完全な型推論が行われます。これは useAgent ですでに提供されていた型付き体験に一致します。

// JavaScript
const client = new AgentClient({ agent: "my-agent", host: window.location.host });
// 型付き call — メソッド名の補完、引数と戻り値の推論
const value = await client.call("getValue");
// 型付き stub — 直接 RPC スタイルのプロキシ
await client.stub.getValue();
await client.stub.add(1, 2);

// TypeScript
const client = new AgentClient<MyAgent>({ agent: "my-agent", host: window.location.host });
const value = await client.call("getValue");
await client.stub.getValue();
await client.stub.add(1, 2);
  • 状態はエージェント型から自動推論されるため、onStateUpdate も型付きになります。
  • 既存の非型付きの利用は変更なしで動作します。
  • 高度な型付けシナリオのために、RPC 型ユーティリティ(AgentMethods, AgentStub, RPCMethods)が agents/client からエクスポートされます。

Zod 4 の要件

agents, @cloudflare/ai-chat, および @cloudflare/codemodezod ^4.0.0 を要求するようになりました。Zod v3 はサポート対象外です。

@cloudflare/ai-chat の修正

  • Turn serialization の修正 — onChatMessage()_reply() の処理がキュー化され、ユーザー要求、ツールの継続、saveMessages() が同時にストリーミングされないようにしました。
  • ストップ時の重複メッセージ — ストリーム中に stop をクリックしてもアシスタントのメッセージが2つに分割されなくなりました。
  • ツール呼び出し後の重複メッセージ — 孤立したクライアント ID が永続ストレージに漏れることを防ぎました。

keepAlive() / keepAliveWhile() の安定化

keepAlive() はもはや実験的ではありません。軽量なインメモリ参照カウントを使用するようになり、スケジュール行ではなく複数の同時呼び出しが単一のアラームサイクルを共有します。@experimental タグは削除されています。

@cloudflare/codemode: TanStack AI 統合

新しいエントリポイント @cloudflare/codemode/tanstack-ai により、Vercel AI SDK の streamText() に代わる選択肢として TanStack AI の chat() ↗ をサポートします。

// JavaScript / TypeScript
import { createCodeTool, tanstackTools } from "@cloudflare/codemode/tanstack-ai";
import { chat } from "@tanstack/ai";

const codeTool = createCodeTool({ tools: [tanstackTools(myServerTools)], executor });
const stream = chat({ adapter, tools: [codeTool], messages });

アップグレード

最新バージョンにアップデートするには:

Terminal window
npm i agents@latest @cloudflare/ai-chat@latest

リソース

  • API
  • Cloudflare サポートとドキュメント(Help Center / System Status / Compliance)

© 2026 Cloudflare, Inc. プライバシーポリシー | 利用規約

フィードバック: この記事は役に立ちましたか? Yes / No