From c23a9114b77b9ca8bea35f72279b1b347ec1e7c2 Mon Sep 17 00:00:00 2001 From: CompleteDotTech <5861166+CompleteDotTech@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:42:43 -0500 Subject: [PATCH] Install Cloudflare Agents SDK skill Vendor the project-local skill and the upstream Apache 2.0 license. Upstream: https://github.com/cloudflare/skills/tree/47dfc2ce969bf62acf8bc231198ade4bb02712e0/skills/agents-sdk --- .agents/skills/agents-sdk/LICENSE | 202 +++++++++++++++++ .agents/skills/agents-sdk/SKILL.md | 206 ++++++++++++++++++ .../agents-sdk/references/browse-the-web.md | 63 ++++++ .../skills/agents-sdk/references/callable.md | 92 ++++++++ .../agents-sdk/references/client-sdk.md | 11 + .../skills/agents-sdk/references/codemode.md | 110 ++++++++++ .../agents-sdk/references/configuration.md | 72 ++++++ .../references/durable-execution.md | 51 +++++ .agents/skills/agents-sdk/references/email.md | 146 +++++++++++++ .../references/human-in-the-loop.md | 10 + .agents/skills/agents-sdk/references/mcp.md | 13 ++ .../agents-sdk/references/observability.md | 44 ++++ .../agents-sdk/references/queue-retries.md | 18 ++ .../skills/agents-sdk/references/routing.md | 75 +++++++ .../references/server-driven-messages.md | 7 + .../agents-sdk/references/skill-feedback.md | 41 ++++ .../agents-sdk/references/state-scheduling.md | 15 ++ .../agents-sdk/references/streaming-chat.md | 16 ++ .agents/skills/agents-sdk/references/think.md | 112 ++++++++++ .agents/skills/agents-sdk/references/voice.md | 68 ++++++ .../agents-sdk/references/webhooks-push.md | 86 ++++++++ .../skills/agents-sdk/references/workflows.md | 21 ++ 22 files changed, 1479 insertions(+) create mode 100644 .agents/skills/agents-sdk/LICENSE create mode 100644 .agents/skills/agents-sdk/SKILL.md create mode 100644 .agents/skills/agents-sdk/references/browse-the-web.md create mode 100644 .agents/skills/agents-sdk/references/callable.md create mode 100644 .agents/skills/agents-sdk/references/client-sdk.md create mode 100644 .agents/skills/agents-sdk/references/codemode.md create mode 100644 .agents/skills/agents-sdk/references/configuration.md create mode 100644 .agents/skills/agents-sdk/references/durable-execution.md create mode 100644 .agents/skills/agents-sdk/references/email.md create mode 100644 .agents/skills/agents-sdk/references/human-in-the-loop.md create mode 100644 .agents/skills/agents-sdk/references/mcp.md create mode 100644 .agents/skills/agents-sdk/references/observability.md create mode 100644 .agents/skills/agents-sdk/references/queue-retries.md create mode 100644 .agents/skills/agents-sdk/references/routing.md create mode 100644 .agents/skills/agents-sdk/references/server-driven-messages.md create mode 100644 .agents/skills/agents-sdk/references/skill-feedback.md create mode 100644 .agents/skills/agents-sdk/references/state-scheduling.md create mode 100644 .agents/skills/agents-sdk/references/streaming-chat.md create mode 100644 .agents/skills/agents-sdk/references/think.md create mode 100644 .agents/skills/agents-sdk/references/voice.md create mode 100644 .agents/skills/agents-sdk/references/webhooks-push.md create mode 100644 .agents/skills/agents-sdk/references/workflows.md diff --git a/.agents/skills/agents-sdk/LICENSE b/.agents/skills/agents-sdk/LICENSE new file mode 100644 index 0000000..7a4a3ea --- /dev/null +++ b/.agents/skills/agents-sdk/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/.agents/skills/agents-sdk/SKILL.md b/.agents/skills/agents-sdk/SKILL.md new file mode 100644 index 0000000..46dc611 --- /dev/null +++ b/.agents/skills/agents-sdk/SKILL.md @@ -0,0 +1,206 @@ +--- +name: agents-sdk +description: Build, debug, or review Cloudflare Agents SDK applications using the agents package. +--- + +# Cloudflare Agents SDK + +Your knowledge of the Agents SDK may be outdated. **Prefer retrieval over pre-training** for any Agents SDK task. + +## Retrieval Sources + +Cloudflare docs: https://developers.cloudflare.com/agents/index.md + +| Topic | Docs URL | Use for | +|-------|----------|---------| +| Getting started | [Quick start](https://developers.cloudflare.com/agents/getting-started/quick-start/index.md) | First agent, project setup | +| Adding to existing project | [Add to existing project](https://developers.cloudflare.com/agents/getting-started/add-to-existing-project/index.md) | Install into existing Workers app | +| Configuration | [Configuration](https://developers.cloudflare.com/agents/runtime/operations/configuration/index.md) | `wrangler.jsonc`, bindings, assets, deployment | +| Agent class | [Agents API](https://developers.cloudflare.com/agents/runtime/agents-api/index.md) | Agent lifecycle, patterns, pitfalls | +| State | [Store and sync state](https://developers.cloudflare.com/agents/runtime/lifecycle/state/index.md) | `setState`, `validateStateChange`, persistence | +| Routing | [Routing](https://developers.cloudflare.com/agents/runtime/communication/routing/index.md) | URL patterns, `routeAgentRequest` | +| Callable methods | [Callable methods](https://developers.cloudflare.com/agents/runtime/lifecycle/callable-methods/index.md) | `@callable`, RPC, streaming, timeouts | +| Scheduling | [Schedule tasks](https://developers.cloudflare.com/agents/runtime/execution/schedule-tasks/index.md) | `schedule()`, `scheduleEvery()`, cron | +| Workflows | [Run workflows](https://developers.cloudflare.com/agents/runtime/execution/run-workflows/index.md) | `AgentWorkflow`, durable multi-step tasks | +| HTTP/WebSockets | [WebSockets](https://developers.cloudflare.com/agents/runtime/communication/websockets/index.md) | Lifecycle hooks, hibernation | +| Chat agents | [Chat agents](https://developers.cloudflare.com/agents/communication-channels/chat/chat-agents/index.md) | `AIChatAgent`, streaming, tools, persistence | +| Client SDK | [Client SDK](https://developers.cloudflare.com/agents/communication-channels/chat/client-sdk/index.md) | `useAgent`, `AgentClient`, state, RPC, HTTP | +| Client tools | [Client tools](https://developers.cloudflare.com/agents/harnesses/think/client-tools/index.md) | Client-side tools, `autoContinueAfterToolResult` | +| Server-driven messages | [Autonomous responses](https://developers.cloudflare.com/agents/communication-channels/chat/autonomous-responses/index.md) | `saveMessages`, `waitUntilStable`, server-initiated turns | +| Resumable streaming | [Chat agents](https://developers.cloudflare.com/agents/communication-channels/chat/chat-agents/index.md#resumable-streaming) | Stream recovery on disconnect | +| Email | [Email](https://developers.cloudflare.com/agents/communication-channels/email/index.md) | Email routing, secure reply resolver | +| MCP client | [MCP client](https://developers.cloudflare.com/agents/model-context-protocol/apis/client-api/index.md) | Connecting to MCP servers | +| MCP server | [MCP server](https://developers.cloudflare.com/agents/model-context-protocol/apis/handler-api/index.md) | Building MCP servers with `createMcpHandler` | +| MCP transports | [MCP transports](https://developers.cloudflare.com/agents/model-context-protocol/protocol/transport/index.md) | Streamable HTTP, SSE, RPC transport options | +| Securing MCP servers | [Securing MCP](https://developers.cloudflare.com/agents/model-context-protocol/guides/securing-mcp-server/index.md) | OAuth, proxy MCP, hardening | +| Human-in-the-loop | [Human-in-the-loop](https://developers.cloudflare.com/agents/concepts/agentic-patterns/human-in-the-loop/index.md) | Workflow approvals, elicitation, timeout handling | +| Durable execution | [Durable execution](https://developers.cloudflare.com/agents/runtime/execution/durable-execution/index.md) | `runFiber()`, `stash()`, surviving DO eviction | +| Queue | [Queue](https://developers.cloudflare.com/agents/runtime/execution/queue-tasks/index.md) | Built-in FIFO queue, `queue()` | +| Retries | [Retries](https://developers.cloudflare.com/agents/runtime/execution/retries/index.md) | `this.retry()`, backoff/jitter | +| Observability | [Observability](https://developers.cloudflare.com/agents/runtime/operations/observability/index.md) | Diagnostics-channel events | +| Push notifications | [Push notifications](https://developers.cloudflare.com/agents/communication-channels/webhooks/push-notifications/index.md) | Web Push + VAPID from agents | +| Webhooks | [Webhooks](https://developers.cloudflare.com/agents/communication-channels/webhooks/index.md) | Receiving external webhooks | +| Cross-domain auth | [Cross-domain auth](https://developers.cloudflare.com/agents/runtime/operations/cross-domain-authentication/index.md) | WebSocket auth, tokens, CORS | +| Readonly connections | [Readonly](https://developers.cloudflare.com/agents/runtime/communication/readonly-connections/index.md) | `shouldConnectionBeReadonly` | +| Voice | [Voice](https://developers.cloudflare.com/agents/communication-channels/voice/index.md) | Experimental STT/TTS, `withVoice` | +| Browse the web | [Browser tools](https://developers.cloudflare.com/agents/tools/browser/index.md) | Experimental CDP browser automation | +| Think | [Think](https://developers.cloudflare.com/agents/harnesses/think/index.md) | Experimental higher-level chat agent class | +| Migrations | [AI SDK v5](https://github.com/cloudflare/agents/blob/main/docs/agents/migration-to-ai-sdk-v5.md), [AI SDK v6](https://github.com/cloudflare/agents/blob/main/docs/agents/migration-to-ai-sdk-v6.md) | Upgrading `@cloudflare/ai-chat` | + +## Capabilities + +The Agents SDK provides: + +- **Persistent state** — SQLite-backed, auto-synced to clients via `setState` +- **Callable RPC** — `@callable()` methods invoked over WebSocket +- **Scheduling** — One-time, recurring (`scheduleEvery`), and cron tasks +- **Workflows** — Durable multi-step background processing via `AgentWorkflow` +- **Durable execution** — `runFiber()` / `stash()` for work that survives DO eviction +- **Queue** — Built-in FIFO queue with retries via `queue()` +- **Retries** — `this.retry()` with exponential backoff and jitter +- **MCP integration** — Connect to MCP servers or build your own with `createMcpHandler` +- **Email handling** — Receive and reply to emails with secure routing +- **Streaming chat** — `AIChatAgent` with resumable streams, message persistence, tools +- **Server-driven messages** — `saveMessages`, `waitUntilStable` for proactive agent turns +- **React hooks** — `useAgent`, `useAgentChat` for client apps +- **Observability** — `diagnostics_channel` events for state, RPC, schedule, lifecycle +- **Push notifications** — Web Push + VAPID delivery from agents +- **Webhooks** — Receive and verify external webhooks +- **Voice** (experimental) — STT/TTS via `@cloudflare/voice` +- **Browser tools** (experimental) — CDP-powered browsing via `agents/browser` +- **Think** (experimental) — Higher-level chat agent via `@cloudflare/think` + +## FIRST: Verify Installation + +```bash +npm ls agents # Should show agents package +``` + +If not installed: +```bash +npm install agents +``` + +For chat agents: +```bash +npm install agents @cloudflare/ai-chat ai @ai-sdk/react +``` + +## Wrangler Configuration + +```jsonc +{ + "compatibility_flags": ["nodejs_compat"], + "durable_objects": { + "bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }] + }, + "migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }] +} +``` + +**Gotchas:** +- Do NOT enable `experimentalDecorators` in tsconfig (breaks `@callable`) +- Never edit old migrations — always add new tags +- Each agent class needs its own DO binding + migration entry +- Add `"ai": { "binding": "AI" }` for Workers AI + +## Agent Class + +```typescript +import { Agent, routeAgentRequest, callable } from "agents"; + +type State = { count: number }; + +export class Counter extends Agent { + 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 }) +}; +``` + +## Routing + +Requests route to `/agents/{agent-name}/{instance-name}`: + +| Class | URL | +|-------|-----| +| `Counter` | `/agents/counter/user-123` | +| `ChatRoom` | `/agents/chat-room/lobby` | + +Client: `useAgent({ agent: "Counter", name: "user-123" })` + +Custom routing: use `getAgentByName(env.MyAgent, "instance-id")` then `agent.fetch(request)`. + +## Core APIs + +| Task | API | +|------|-----| +| Read state | `this.state.count` | +| Write state | `this.setState({ count: 1 })` | +| SQL query | `` this.sql`SELECT * FROM users WHERE id = ${id}` `` | +| Schedule (delay) | `await this.schedule(60, "task", payload)` | +| Schedule (cron) | `await this.schedule("0 * * * *", "task", payload)` | +| Schedule (interval) | `await this.scheduleEvery(30, "poll")` | +| RPC method | `@callable() myMethod() { ... }` | +| Streaming RPC | `@callable({ streaming: true }) stream(res) { ... }` | +| Start workflow | `await this.runWorkflow("ProcessingWorkflow", params)` | +| Durable fiber | `await this.runFiber("name", async (ctx) => { ... })` | +| Enqueue work | `this.queue("handler", payload)` | +| Retry with backoff | `await this.retry(fn, { maxAttempts: 5 })` | +| Broadcast to clients | `this.broadcast(message)` | +| Get connections | `this.getConnections(tag?)` | + +## React Client + +Read [client-sdk.md](references/client-sdk.md) for client selection and current connection examples. For chat UI and tools, also read [streaming-chat.md](references/streaming-chat.md). + +## References + +### Core +- **[references/state-scheduling.md](references/state-scheduling.md)** — State persistence, scheduling, SQL +- **[references/callable.md](references/callable.md)** — RPC methods, streaming, timeouts +- **[references/routing.md](references/routing.md)** — URL patterns, custom routing, `getAgentByName` +- **[references/configuration.md](references/configuration.md)** — Wrangler config, bindings, Vite setup + +### Chat & Streaming +- **[references/streaming-chat.md](references/streaming-chat.md)** — AIChatAgent, resumable streams, tools +- **[references/client-sdk.md](references/client-sdk.md)** — `useAgent`, `useAgentChat`, `AgentClient` +- **[references/server-driven-messages.md](references/server-driven-messages.md)** — Trigger patterns, `saveMessages` +- **[references/human-in-the-loop.md](references/human-in-the-loop.md)** — Approval flows, `needsApproval` + +### Background Processing +- **[references/workflows.md](references/workflows.md)** — Durable Workflows integration +- **[references/durable-execution.md](references/durable-execution.md)** — `runFiber`, `stash`, surviving eviction +- **[references/queue-retries.md](references/queue-retries.md)** — Built-in queue, retry with backoff + +### Integrations +- **[references/mcp.md](references/mcp.md)** — MCP client and server, transports, securing +- **[references/email.md](references/email.md)** — Email routing and handling +- **[references/webhooks-push.md](references/webhooks-push.md)** — Webhooks, push notifications +- **[references/observability.md](references/observability.md)** — Diagnostics-channel events + +### Experimental +- **[references/think.md](references/think.md)** — `@cloudflare/think` higher-level chat agent +- **[references/voice.md](references/voice.md)** — `@cloudflare/voice` STT/TTS +- **[references/codemode.md](references/codemode.md)** — Code Mode for tool orchestration +- **[references/browse-the-web.md](references/browse-the-web.md)** — CDP browser tools + +## Skill feedback + +If the user reports that this skill gave incorrect or outdated guidance, or is missing information, read [references/skill-feedback.md](references/skill-feedback.md). diff --git a/.agents/skills/agents-sdk/references/browse-the-web.md b/.agents/skills/agents-sdk/references/browse-the-web.md new file mode 100644 index 0000000..fec5890 --- /dev/null +++ b/.agents/skills/agents-sdk/references/browse-the-web.md @@ -0,0 +1,63 @@ +# Browse the Web (Experimental) + +Fetch https://developers.cloudflare.com/agents/tools/browser/index.md for complete documentation. + +CDP-powered browser tools that let agents scrape, screenshot, and interact with web pages. + +## Setup + +```jsonc +// wrangler.jsonc +{ + "browser": { "binding": "BROWSER" }, + "worker_loaders": [{ "binding": "LOADER" }], + "compatibility_flags": ["nodejs_compat"] +} +``` + +## Usage with AI SDK + +```typescript +import { createBrowserTools } from "agents/browser/ai"; + +export class MyAgent extends AIChatAgent { + async onChatMessage(onFinish) { + const browserTools = createBrowserTools({ + browser: this.env.BROWSER, + loader: this.env.LOADER + }); + + const result = streamText({ + model: openai("gpt-4o"), + messages: await convertToModelMessages(this.messages), + tools: { ...myTools, ...browserTools }, + onFinish + }); + return result.toUIMessageStreamResponse(); + } +} +``` + +## Available Tools + +| Tool | Purpose | +|------|---------| +| `browser_search` | Search the web and return results | +| `browser_execute` | Navigate to URL, execute JS, return results | + +The LLM writes async JavaScript IIFEs that run in a fresh browser session. + +## When to Use + +- Need a real browser (JS rendering, screenshots, interaction) → browser tools +- Just need HTML/API data → use `fetch()` instead (faster, cheaper) + +## Low-Level API + +```typescript +import { connectBrowser, CdpSession } from "agents/browser"; + +const browser = await connectBrowser(this.env.BROWSER); +const cdp = new CdpSession(browser); +await cdp.send("Page.navigate", { url: "https://example.com" }); +``` diff --git a/.agents/skills/agents-sdk/references/callable.md b/.agents/skills/agents-sdk/references/callable.md new file mode 100644 index 0000000..af21d17 --- /dev/null +++ b/.agents/skills/agents-sdk/references/callable.md @@ -0,0 +1,92 @@ +# Callable Methods + +Fetch https://developers.cloudflare.com/agents/runtime/lifecycle/callable-methods/index.md for complete documentation. + +## Overview + +`@callable()` exposes agent methods to clients via WebSocket RPC. + +```typescript +import { Agent, callable } from "agents"; + +export class MyAgent extends Agent { + @callable() + async greet(name: string): Promise { + return `Hello, ${name}!`; + } + + @callable() + async processData(data: unknown): Promise { + // Long-running work + return result; + } +} +``` + +## Client Usage + +```typescript +// Basic call +const greeting = await agent.call("greet", ["World"]); + +// With timeout +const result = await agent.call("processData", [data], { + timeout: 5000 // 5 second timeout +}); +``` + +## Streaming Responses + +```typescript +import { Agent, callable, StreamingResponse } from "agents"; + +export class MyAgent extends Agent { + @callable({ streaming: true }) + async streamResults(stream: StreamingResponse, query: string) { + for await (const item of fetchResults(query)) { + stream.send(JSON.stringify(item)); + } + stream.close(); + } + + @callable({ streaming: true }) + async streamWithError(stream: StreamingResponse) { + try { + // ... work + } catch (error) { + stream.error(error.message); // Signal error to client + return; + } + stream.close(); + } +} +``` + +Client with streaming: + +```typescript +await agent.call("streamResults", ["search term"], { + stream: { + onChunk: (data) => console.log("Chunk:", data), + onDone: () => console.log("Complete"), + onError: (error) => console.error("Error:", error) + } +}); +``` + +## Introspection + +```typescript +// Get list of callable methods on an agent +const methods = await agent.call("getCallableMethods", []); +// Returns: ["greet", "processData", "streamResults", ...] +``` + +## When to Use + +| Scenario | Use | +|----------|-----| +| Browser/mobile calling agent | `@callable()` | +| External service calling agent | `@callable()` | +| Worker calling agent (same codebase) | DO RPC directly | +| Agent calling another agent | `getAgentByName()` + DO RPC | diff --git a/.agents/skills/agents-sdk/references/client-sdk.md b/.agents/skills/agents-sdk/references/client-sdk.md new file mode 100644 index 0000000..366dc2c --- /dev/null +++ b/.agents/skills/agents-sdk/references/client-sdk.md @@ -0,0 +1,11 @@ +# Client SDK + +Choose `useAgent` for React state/RPC, `AgentClient` for other WebSocket clients, and `agentFetch` for one-off HTTP requests. Add `useAgentChat` when the UI needs chat messages and streaming. Check installed package versions before adapting current examples. + +| Task | Documentation | +|------|---------------| +| Connect, sync state, call RPC, or send HTTP requests | [Client SDK](https://developers.cloudflare.com/agents/communication-channels/chat/client-sdk/index.md) — hooks, vanilla JS, typed calls, streaming callbacks, and connection options | +| Build chat UI | [Chat agents](https://developers.cloudflare.com/agents/communication-channels/chat/chat-agents/index.md) — `useAgentChat`, message rendering, status, and tool interactions | +| Authenticate across origins | [Cross-domain authentication](https://developers.cloudflare.com/agents/runtime/operations/cross-domain-authentication/index.md) — token validation and WebSocket authentication | + +Keep client instance selection consistent with server routing. For authentication, account for token refresh on reconnect and query caching. Close manually created `AgentClient` connections when finished; React hooks manage their own cleanup. diff --git a/.agents/skills/agents-sdk/references/codemode.md b/.agents/skills/agents-sdk/references/codemode.md new file mode 100644 index 0000000..980b6b5 --- /dev/null +++ b/.agents/skills/agents-sdk/references/codemode.md @@ -0,0 +1,110 @@ +# Codemode (Experimental) + +Fetch https://developers.cloudflare.com/agents/tools/codemode/api-reference/index.md for complete documentation. + +Codemode lets LLMs write and execute code that orchestrates your tools, instead of calling them one at a time. The LLM gets a single "write code" tool; generated JavaScript runs in an isolated Worker sandbox. + +## When to Use + +| Scenario | Use Codemode? | +|----------|---------------| +| Single tool call | No — standard tool calling is simpler | +| Chained tool calls with logic | Yes | +| Conditional logic across tools | Yes | +| MCP multi-server workflows | Yes | +| Simple Q&A chat | No | + +## Setup + +### Wrangler Config + +```jsonc +{ + "worker_loaders": [{ "binding": "LOADER" }], + "compatibility_flags": ["nodejs_compat"] +} +``` + +### Install + +```bash +npm install @cloudflare/codemode ai zod +``` + +## Usage + +```typescript +import { createCodeTool } from "@cloudflare/codemode/ai"; +import { DynamicWorkerExecutor } from "@cloudflare/codemode"; +import { streamText, tool, convertToModelMessages } from "ai"; +import { z } from "zod"; + +const tools = { + getWeather: tool({ + description: "Get weather for a location", + inputSchema: z.object({ location: z.string() }), + execute: async ({ location }) => `Weather: ${location} 72°F` + }), + sendEmail: tool({ + description: "Send an email", + inputSchema: z.object({ to: z.string(), subject: z.string(), body: z.string() }), + execute: async ({ to, subject, body }) => `Email sent to ${to}` + }) +}; + +export class MyAgent extends Agent { + async onChatMessage() { + const executor = new DynamicWorkerExecutor({ + loader: this.env.LOADER + }); + + const codemode = createCodeTool({ tools, executor }); + + const result = streamText({ + model, + system: "You are a helpful assistant.", + messages: await convertToModelMessages(this.messages), + tools: { codemode } + }); + + return result.toUIMessageStreamResponse(); + } +} +``` + +## With MCP Tools + +```typescript +const codemode = createCodeTool({ + tools: { + ...myTools, + ...this.mcp.getAITools() + }, + executor +}); +``` + +## How It Works + +1. `createCodeTool` generates TypeScript type definitions from your tools +2. The LLM writes an async arrow function calling `codemode.toolName(args)` +3. Code runs in an isolated Worker sandbox via `DynamicWorkerExecutor` +4. Tool calls route back to the host via Workers RPC +5. External `fetch()` is blocked by default — sandbox can only call your tools + +## Network Isolation + +```typescript +const executor = new DynamicWorkerExecutor({ + loader: env.LOADER, + globalOutbound: null // default — fully isolated + // globalOutbound: env.MY_SERVICE // route through a Fetcher +}); +``` + +## Limitations + +- Experimental — API may change +- `needsApproval` tools execute immediately in sandbox (no approval pause yet) +- JavaScript execution only +- Requires `worker_loaders` binding diff --git a/.agents/skills/agents-sdk/references/configuration.md b/.agents/skills/agents-sdk/references/configuration.md new file mode 100644 index 0000000..1f76797 --- /dev/null +++ b/.agents/skills/agents-sdk/references/configuration.md @@ -0,0 +1,72 @@ +# Configuration + +Fetch https://developers.cloudflare.com/agents/runtime/operations/configuration/index.md for complete documentation. + +## Wrangler Config (`wrangler.jsonc`) + +```jsonc +{ + "name": "my-agent", + "main": "src/index.ts", + "compatibility_date": "2025-01-28", + "compatibility_flags": ["nodejs_compat"], + "durable_objects": { + "bindings": [ + { "name": "MyAgent", "class_name": "MyAgent" }, + { "name": "ChatAgent", "class_name": "ChatAgent" } + ] + }, + "migrations": [ + { "tag": "v1", "new_sqlite_classes": ["MyAgent", "ChatAgent"] } + ], + "ai": { "binding": "AI" }, + "assets": { + "directory": "./dist/client", + "binding": "ASSETS", + "not_found_handling": "single-page-application", + "run_worker_first": true + } +} +``` + +## Key Rules + +- Every agent class needs a DO binding AND a `new_sqlite_classes` migration entry +- `nodejs_compat` is required +- Never edit old migrations — add a new tag (e.g. `v2`) for new classes +- Do NOT enable `experimentalDecorators` in tsconfig — it breaks `@callable` +- For Workers AI locally, set `"ai": { "binding": "AI", "remote": true }` in `.dev.vars` or config +- Use `wrangler secret put` for secrets, never hardcode them + +## Vite Setup + +```typescript +import { defineConfig } from "vite"; +import react from "@vitejs/plugin-react"; +import { cloudflare } from "@cloudflare/vite-plugin"; +import { agents } from "agents/vite"; + +export default defineConfig({ + plugins: [react(), cloudflare(), agents()] +}); +``` + +## Type Generation + +```bash +npx wrangler types +``` + +This generates `env.d.ts` with typed bindings. Regenerate after changing `wrangler.jsonc`. + +## tsconfig + +Extend the agents tsconfig for correct settings: + +```jsonc +{ + "extends": ["agents/tsconfig"], + "include": ["src/**/*.ts", "src/**/*.tsx"], + "compilerOptions": { "paths": { "~/*": ["./src/*"] } } +} +``` diff --git a/.agents/skills/agents-sdk/references/durable-execution.md b/.agents/skills/agents-sdk/references/durable-execution.md new file mode 100644 index 0000000..1cc817e --- /dev/null +++ b/.agents/skills/agents-sdk/references/durable-execution.md @@ -0,0 +1,51 @@ +# Durable Execution + +Fetch https://developers.cloudflare.com/agents/runtime/execution/durable-execution/index.md for complete documentation. + +Fibers let agent work survive Durable Object eviction. Progress is checkpointed to SQLite; on recovery, you decide what to do. + +## `runFiber` + +```typescript +export class MyAgent extends Agent { + async onRequest(request: Request) { + await this.runFiber("process-data", async (ctx) => { + const step1 = await fetchData(); + ctx.stash({ step: 1, data: step1 }); + + const step2 = await transform(step1); + ctx.stash({ step: 2, result: step2 }); + + this.setState({ result: step2 }); + }); + return new Response("Started"); + } + + async onFiberRecovered(ctx) { + const checkpoint = ctx.stash; + if (checkpoint.step === 1) { + const step2 = await transform(checkpoint.data); + this.setState({ result: step2 }); + } + } +} +``` + +## Key APIs + +| API | Purpose | +|-----|---------| +| `this.runFiber(name, fn)` | Start a named fiber | +| `ctx.stash` / `this.stash` | Read latest checkpoint | +| `ctx.stash = data` | Write checkpoint (JSON-serializable) | +| `onFiberRecovered(ctx)` | Called on DO restart if fiber was in-flight | +| `keepAlive()` | Prevent hibernation while fiber runs | +| `keepAliveWhile(fn)` | Keep alive for duration of async function | + +## Important + +- `stash` replaces the entire checkpoint — not a merge +- The lambda is NOT restored on recovery — only the stash data is. You must re-derive what to do in `onFiberRecovered` +- No auto-retry on throw — handle errors yourself +- For long-running pipelines with automatic retries, use Workflows instead +- Filter concurrent fibers by `ctx.name` in `onFiberRecovered` diff --git a/.agents/skills/agents-sdk/references/email.md b/.agents/skills/agents-sdk/references/email.md new file mode 100644 index 0000000..bd800ca --- /dev/null +++ b/.agents/skills/agents-sdk/references/email.md @@ -0,0 +1,146 @@ +# Email Handling + +Fetch https://developers.cloudflare.com/agents/communication-channels/email/index.md for complete documentation. + +## Overview + +Agents receive and reply to emails via Cloudflare Email Routing. + +## Wrangler Configuration + +```jsonc +{ + "durable_objects": { + "bindings": [{ "name": "EmailAgent", "class_name": "EmailAgent" }] + }, + "migrations": [{ "tag": "v1", "new_sqlite_classes": ["EmailAgent"] }], + "send_email": [ + { "name": "SEB", "destination_address": "reply@yourdomain.com" } + ] +} +``` + +## Basic Email Handler + +```typescript +import { Agent } from "agents"; +import { type AgentEmail } from "agents/email"; +import PostalMime from "postal-mime"; + +export class EmailAgent extends Agent { + async onEmail(email: AgentEmail) { + const raw = await email.getRaw(); + const parsed = await PostalMime.parse(raw); + + console.log("From:", email.from); + console.log("Subject:", parsed.subject); + + await this.replyToEmail(email, { + fromName: "My Agent", + subject: `Re: ${parsed.subject}`, + body: "Thanks for your email!" + }); + } +} +``` + +## Routing Emails + +```typescript +import { routeAgentRequest, routeAgentEmail } from "agents"; +import { createAddressBasedEmailResolver } from "agents/email"; + +export default { + async email(message, env) { + await routeAgentEmail(message, env, { + resolver: createAddressBasedEmailResolver("EmailAgent") + }); + }, + + async fetch(request, env) { + return routeAgentRequest(request, env) ?? new Response("Not found", { status: 404 }); + } +}; +``` + +## Resolvers + +### Address-Based (Inbound Mail) + +Routes based on recipient address: + +```typescript +import { createAddressBasedEmailResolver } from "agents/email"; + +const resolver = createAddressBasedEmailResolver("EmailAgent"); +// support@example.com → EmailAgent, instance "support" +// NotificationAgent+user123@example.com → NotificationAgent, instance "user123" +``` + +### Secure Reply (Reply Flows) + +Verifies replies are authentic using HMAC-SHA256 signatures: + +```typescript +import { createSecureReplyEmailResolver } from "agents/email"; + +const resolver = createSecureReplyEmailResolver(env.EMAIL_SECRET, { + maxAge: 7 * 24 * 60 * 60, // 7 days (default: 30 days) + onInvalidSignature: (email, reason) => { + console.warn(`Invalid signature from ${email.from}: ${reason}`); + } +}); +``` + +Sign outbound emails to enable secure reply routing: + +```typescript +await this.replyToEmail(email, { + fromName: "My Agent", + body: "Thanks!", + secret: this.env.EMAIL_SECRET // Signs headers for secure reply routing +}); +``` + +### Catch-All (Single Instance) + +Routes all emails to one agent instance: + +```typescript +import { createCatchAllEmailResolver } from "agents/email"; + +const resolver = createCatchAllEmailResolver("EmailAgent", "default"); +``` + +### Combining Resolvers + +```typescript +async email(message, env) { + const secureReply = createSecureReplyEmailResolver(env.EMAIL_SECRET); + const addressBased = createAddressBasedEmailResolver("EmailAgent"); + + await routeAgentEmail(message, env, { + resolver: async (email, env) => { + // Try secure reply first + const result = await secureReply(email, env); + if (result) return result; + // Fall back to address-based + return addressBased(email, env); + } + }); +} +``` + +## Utilities + +```typescript +import { isAutoReplyEmail } from "agents/email"; + +async onEmail(email: AgentEmail) { + if (isAutoReplyEmail(email.headers)) { + // Skip auto-replies (vacation, out-of-office, etc.) + return; + } + // Process email... +} +``` diff --git a/.agents/skills/agents-sdk/references/human-in-the-loop.md b/.agents/skills/agents-sdk/references/human-in-the-loop.md new file mode 100644 index 0000000..d92aa53 --- /dev/null +++ b/.agents/skills/agents-sdk/references/human-in-the-loop.md @@ -0,0 +1,10 @@ +# Human-in-the-Loop + +Choose the approval layer based on where execution must pause, then fetch its current documentation: + +| Need | Documentation | +|------|---------------| +| Approve chat tool execution or run a browser-side tool | [Chat agents](https://developers.cloudflare.com/agents/communication-channels/chat/chat-agents/index.md) — `needsApproval`, approval responses, client tools, and custom denial messages | +| Pause a durable background task or collect MCP input | [Human-in-the-loop patterns](https://developers.cloudflare.com/agents/concepts/agentic-patterns/human-in-the-loop/index.md) — workflow approval, timeout handling, and elicitation | + +Distinguish approval responses from client tool outputs. When returning a custom tool error, check whether an explicit continuation is needed. Handle workflow approval timeouts before executing the gated action. Check installed SDK versions before adapting examples. diff --git a/.agents/skills/agents-sdk/references/mcp.md b/.agents/skills/agents-sdk/references/mcp.md new file mode 100644 index 0000000..dd2a4ad --- /dev/null +++ b/.agents/skills/agents-sdk/references/mcp.md @@ -0,0 +1,13 @@ +# MCP Integration + +For new servers, prefer `createMcpHandler` over the deprecated `McpAgent`. For existing servers, check the installed SDK version and state/session requirements before choosing a migration path. + +Read the relevant current documentation for implementation details and supported dependency versions: + +| Task | Documentation | +|------|---------------| +| Build a server | [Handler API](https://developers.cloudflare.com/agents/model-context-protocol/apis/handler-api/index.md) — server factories, Worker entrypoint, dependencies, and examples | +| Migrate an existing server | [MCP SDK v2 migration](https://developers.cloudflare.com/agents/model-context-protocol/guides/migrate-to-mcp-sdk-v2/index.md) — stateless migration and temporary legacy paths | +| Connect to servers and use their tools | [Client API](https://developers.cloudflare.com/agents/model-context-protocol/apis/client-api/index.md) — connections, OAuth, tools, resources, and retries | +| Choose a transport | [Transports](https://developers.cloudflare.com/agents/model-context-protocol/protocol/transport/index.md) — remote HTTP and existing RPC integrations | +| Secure a server | [Securing MCP servers](https://developers.cloudflare.com/agents/model-context-protocol/guides/securing-mcp-server/index.md) — OAuth and proxy security | diff --git a/.agents/skills/agents-sdk/references/observability.md b/.agents/skills/agents-sdk/references/observability.md new file mode 100644 index 0000000..fc4814d --- /dev/null +++ b/.agents/skills/agents-sdk/references/observability.md @@ -0,0 +1,44 @@ +# Observability + +Fetch https://developers.cloudflare.com/agents/runtime/operations/observability/index.md for complete documentation. + +Agents emit structured events via Node.js `diagnostics_channel`. Subscribe in development or forward via Tail Workers in production. + +## Subscribe to Events + +```typescript +import { subscribe } from "agents/observability"; + +subscribe("agents:rpc", (event) => { + console.log(`RPC call: ${event.payload.method}`); +}); + +subscribe("agents:state", (event) => { + console.log(`State change on ${event.agent}`); +}); +``` + +## Available Channels + +| Channel | Events | +|---------|--------| +| `agents:state` | State changes | +| `agents:rpc` | `@callable` invocations | +| `agents:message` | WebSocket messages | +| `agents:schedule` | Schedule triggers | +| `agents:lifecycle` | Agent start, connect, disconnect | +| `agents:workflow` | Workflow progress, completion, errors | +| `agents:mcp` | MCP server connections, tool calls | +| `agents:email` | Email received | + +## Per-Agent Override + +```typescript +export class MyAgent extends Agent { + observability = undefined; // disable for this agent +} +``` + +## Production: Tail Workers + +In production, events appear as `diagnosticsChannelEvents` on the Tail Worker `event` object. Attach a Tail Worker to your agent's Worker to forward events to your observability platform. diff --git a/.agents/skills/agents-sdk/references/queue-retries.md b/.agents/skills/agents-sdk/references/queue-retries.md new file mode 100644 index 0000000..8d9ddfc --- /dev/null +++ b/.agents/skills/agents-sdk/references/queue-retries.md @@ -0,0 +1,18 @@ +# Queue & Retries + +Read the current Cloudflare documentation for queue management, retry options, defaults, and callback examples. + +| Task | Documentation | +|------|---------------| +| Enqueue, inspect, and remove background work; understand sequential processing and failure handling | [Queue tasks](https://developers.cloudflare.com/agents/runtime/execution/queue-tasks/index.md) | +| Retry an operation or configure retries for queued and scheduled callbacks | [Retries](https://developers.cloudflare.com/agents/runtime/execution/retries/index.md) | +| Delay recovery or run work on a recurring schedule | [Schedule tasks](https://developers.cloudflare.com/agents/runtime/execution/schedule-tasks/index.md) | + +Keep these execution choices in mind when using the linked guides: + +- Use the built-in queue for sequential background work. Retries block later queue items; use scheduling for long recovery waits. +- Retry delays keep the Durable Object active. Choose retry budgets with execution cost and latency in mind. +- Queued items are removed after their retry budget is exhausted; there is no built-in dead-letter queue. Record failures explicitly when the application needs recovery or auditing. +- The selective retry predicate is available on `this.retry()`, not serialized queue or schedule options. Handle non-retryable errors in those callbacks. + +See [state-scheduling.md](state-scheduling.md) for choosing schedule modes and persisting application state. diff --git a/.agents/skills/agents-sdk/references/routing.md b/.agents/skills/agents-sdk/references/routing.md new file mode 100644 index 0000000..b1cf4ad --- /dev/null +++ b/.agents/skills/agents-sdk/references/routing.md @@ -0,0 +1,75 @@ +# Routing + +Fetch https://developers.cloudflare.com/agents/runtime/communication/routing/index.md for complete documentation. + +## Default URL Pattern + +`/agents/{kebab-class-name}/{instance-name}` + +```typescript +import { routeAgentRequest } from "agents"; + +export default { + fetch: (req, env) => + routeAgentRequest(req, env) ?? new Response("Not found", { status: 404 }) +}; +``` + +| Class | URL | +|-------|-----| +| `Counter` | `/agents/counter/user-123` | +| `ChatRoom` | `/agents/chat-room/lobby` | +| `MyAgent` | `/agents/my-agent/default` | + +Subpaths after the instance name (e.g. `/agents/my-agent/default/api/data`) route to `onRequest`. + +## Custom Routing with `getAgentByName` + +```typescript +import { getAgentByName } from "agents"; + +export default { + async fetch(req, env) { + const url = new URL(req.url); + if (url.pathname.startsWith("/api/")) { + const agent = getAgentByName(env.MyAgent, "singleton"); + return agent.fetch(req); + } + return routeAgentRequest(req, env); + } +}; +``` + +## Options + +```typescript +routeAgentRequest(req, env, { + cors: true, + prefix: "/api/agents", + locationHint: "enam", + jurisdiction: "eu", + props: { userId: "123" }, + onBeforeConnect: async (req) => { /* auth check */ }, + onBeforeRequest: async (req) => { /* auth check */ } +}); +``` + +`props` are delivered to `onStart(props)` on first access. + +## Client Side + +```tsx +useAgent({ + agent: "MyAgent", + name: "instance-1", + host: "https://my-worker.workers.dev", + basePath: "/api/agents", + path: "/custom-subpath" +}); +``` + +## Common Mistakes + +- Class name `MyAgent` becomes kebab `my-agent` in URLs — match exactly +- "Namespace not found" error = the `class_name` in wrangler doesn't match your exported class +- If `sendIdentityOnConnect: false`, the `ready` promise on the client may never resolve — use state sync instead diff --git a/.agents/skills/agents-sdk/references/server-driven-messages.md b/.agents/skills/agents-sdk/references/server-driven-messages.md new file mode 100644 index 0000000..b86315d --- /dev/null +++ b/.agents/skills/agents-sdk/references/server-driven-messages.md @@ -0,0 +1,7 @@ +# Server-Driven Messages + +Read [Autonomous responses](https://developers.cloudflare.com/agents/communication-channels/chat/autonomous-responses/index.md) for scheduled, webhook, email, and agent-triggered turns, message schemas, response hooks, and client streaming status. + +Choose `saveMessages` to persist messages and request a model response, or `persistMessages` to update context without starting a turn. Use `onChatResponse` to react to turns regardless of their trigger. For webhooks that need a quick acknowledgement, consult the documented `submitMessages` path. + +Before reading conversation history or calling `saveMessages` from non-chat entry points, await `waitUntilStable` and handle a timeout without proceeding as if the conversation were stable. Prefer the functional `saveMessages` form when calls can queue, so each update uses the latest history. diff --git a/.agents/skills/agents-sdk/references/skill-feedback.md b/.agents/skills/agents-sdk/references/skill-feedback.md new file mode 100644 index 0000000..91744ba --- /dev/null +++ b/.agents/skills/agents-sdk/references/skill-feedback.md @@ -0,0 +1,41 @@ +# Skill feedback + +GitHub issues are public: anyone can read an issue once it is posted. Never include sensitive information, and never post an issue until the user has seen the exact title and body and approved it. + +Use this when the user reports that the `agents-sdk` skill gave incorrect or outdated guidance, is missing information, or could be improved. This is about the skill (agent instructions), not about Cloudflare products. + +## What not to include + +The issue is drafted from the conversation, so remove the following before drafting and describe the problem in general terms instead: + +- Credentials, API tokens, secrets, and passwords +- Account IDs, zone IDs, and other resource identifiers +- Customer or personal data, such as names, email addresses, and IP addresses +- Internal hostnames and URLs +- Private code, configuration, and logs + +## Steps + +1. **Ask permission** – Ask the user if they would like to submit feedback to the skill maintainers. If they decline, move on. + +2. **Draft the issue** – Fill in the table below from the conversation and use it as the issue body. Always identify which specific file and section caused the problem. Leave out everything listed in [What not to include](#what-not-to-include). + +3. **Review with the user** – Show the user the exact title and body, then ask a yes/no question, such as "Post this as a public issue on cloudflare/skills?" Submit only after the user answers yes. If they ask for changes, apply them and ask again. If they answer no, do not post. Agreeing to send feedback in step 1 is not approval of the text. + +4. **Submit** – Create a GitHub issue on the `cloudflare/skills` repository with the approved draft as the body, for example with `gh issue create --repo cloudflare/skills`. The title must follow this format: `skill-feedback: agents-sdk: `. + +5. **Share the result** – Share the issue URL with the user after submission. If submission fails, give the user the approved title and body, and this link to create the issue manually: + +## Issue body + +| Field | Value | +|-------|-------| +| Type | `bug` (incorrect guidance), `outdated`, `missing`, or `improvement` | +| Skill | `agents-sdk` | +| Source | File and section, e.g. `SKILL.md` > "Section name" or `references/.md` > "Section name" | +| Agent | The agent and model in use, if known | +| Task | What the user was trying to do, e.g. "deploy a preview" | +| Expected | What should have happened, e.g. "Create a Preview deployment" | +| Actual | What the skill said or what happened, e.g. "Unknown option: --preview" | +| Impact | The effect on the user, e.g. "Time spent finding the correct syntax" | +| Suggested fix | How the skill should change; leave blank if unsure | diff --git a/.agents/skills/agents-sdk/references/state-scheduling.md b/.agents/skills/agents-sdk/references/state-scheduling.md new file mode 100644 index 0000000..d40e0da --- /dev/null +++ b/.agents/skills/agents-sdk/references/state-scheduling.md @@ -0,0 +1,15 @@ +# State & Scheduling + +Read the current Cloudflare documentation before implementing state, SQL, or scheduling; check installed SDK versions when adapting an existing agent. + +| Task | Documentation | +|------|---------------| +| Define state, validate updates, choose state versus SQL, and query SQLite | [Store and sync state](https://developers.cloudflare.com/agents/runtime/lifecycle/state/index.md) | +| Synchronize state with React or vanilla JavaScript clients | [Client SDK](https://developers.cloudflare.com/agents/communication-channels/chat/client-sdk/index.md) | +| Select delayed, date-based, cron, or interval execution; manage schedules and callbacks | [Schedule tasks](https://developers.cloudflare.com/agents/runtime/execution/schedule-tasks/index.md) | +| Configure schedule retry behavior | [Retries](https://developers.cloudflare.com/agents/runtime/execution/retries/index.md) | +| Handle lifecycle events, connections, and hibernation | [WebSockets](https://developers.cloudflare.com/agents/runtime/communication/websockets/index.md) | + +Use synchronized state for data clients need immediately, and SQL for larger collections, history, or queries. Reject invalid updates in the validation hook; state-change notifications are for reacting to accepted updates. Use the state documentation for current hook names and behavior. + +Choose a one-time delay or date for work that runs once, cron for calendar recurrence, and an interval for a fixed cadence. For queued work and retry tradeoffs, see [queue-retries.md](queue-retries.md). diff --git a/.agents/skills/agents-sdk/references/streaming-chat.md b/.agents/skills/agents-sdk/references/streaming-chat.md new file mode 100644 index 0000000..5248b47 --- /dev/null +++ b/.agents/skills/agents-sdk/references/streaming-chat.md @@ -0,0 +1,16 @@ +# Streaming Chat with AIChatAgent + +Use `AIChatAgent` for persisted conversations with streaming and tools; use callable streaming RPC for non-chat output. Before adapting an existing app, check its installed `agents`, `@cloudflare/ai-chat`, and AI SDK versions against the current docs. + +Read the relevant documentation before implementing: + +| Task | Documentation | +|------|---------------| +| Build a chat agent | [Chat agent example](https://developers.cloudflare.com/agents/examples/chat-agent/index.md) — setup, provider, server, and UI | +| Implement or customize chat | [Chat agents](https://developers.cloudflare.com/agents/communication-channels/chat/chat-agents/index.md) — message format, tools, custom streams, persistence, concurrency, cancellation, and recovery | +| Connect a client | [Client guidance](client-sdk.md) — React, vanilla JS, HTTP, and authentication | +| Stream non-chat results | [Callable methods](https://developers.cloudflare.com/agents/runtime/lifecycle/callable-methods/index.md) — server and client streaming RPC | +| Trigger background turns | [Server-driven messages](server-driven-messages.md) | +| Add approvals | [Human-in-the-loop](human-in-the-loop.md) | + +Forward the request abort signal to the model call so cancellation stops generation. When customizing streams, verify persistence and completion behavior for the installed version. Treat client reconnection and Durable Object eviction as separate recovery cases. diff --git a/.agents/skills/agents-sdk/references/think.md b/.agents/skills/agents-sdk/references/think.md new file mode 100644 index 0000000..ce5d430 --- /dev/null +++ b/.agents/skills/agents-sdk/references/think.md @@ -0,0 +1,112 @@ +# Think (Experimental) + +Fetch https://developers.cloudflare.com/agents/harnesses/think/index.md for complete documentation. + +`@cloudflare/think` — a higher-level chat agent class that handles the `streamText` loop, tool execution, and message persistence for you. You provide `getModel()` and `getSystemPrompt()`; Think handles the rest. + +```bash +npm install @cloudflare/think +``` + +## Minimal Agent + +```typescript +import { Think } from "@cloudflare/think"; +import { createWorkersAI } from "workers-ai-provider"; +import { routeAgentRequest } from "agents"; + +export class MyAgent extends Think { + getModel() { + return createWorkersAI({ binding: this.env.AI })("@cf/meta/llama-4-scout-17b-16e-instruct"); + } + + getSystemPrompt() { + return "You are a helpful assistant."; + } +} + +export default { + fetch: (req, env) => routeAgentRequest(req, env) +}; +``` + +## Wrangler Config + +```jsonc +{ + "compatibility_flags": ["nodejs_compat", "experimental"], + "durable_objects": { + "bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }] + }, + "migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }], + "ai": { "binding": "AI" } +} +``` + +**Note:** Think requires the `experimental` compatibility flag. + +## Custom Tools + +```typescript +import { tool } from "ai"; +import { z } from "zod"; + +export class MyAgent extends Think { + getTools() { + return { + getWeather: tool({ + description: "Get weather", + parameters: z.object({ city: z.string() }), + execute: async ({ city }) => `72°F in ${city}` + }) + }; + } +} +``` + +## Lifecycle Hooks + +| Hook | When | Use for | +|------|------|---------| +| `configureSession()` | Agent starts | Set up memory, context providers | +| `beforeTurn(ctx)` | Before each LLM call | Per-turn model/tools/system prompt; return `TurnConfig` | +| `onChunk(chunk)` | Each streaming chunk | Progress tracking | +| `onChatResponse(result)` | After LLM turn completes | Chaining, follow-up `saveMessages` | +| `onChatError(error)` | On LLM error | Error handling | + +```typescript +async beforeTurn(ctx: TurnContext): Promise { + if (ctx.continuation) { + return { model: cheaperModel }; + } + return {}; +} +``` + +## Sub-Agents + +```typescript +const child = this.subAgent(SpecialistAgent, "specialist-1"); +await child.chat("Analyze this data...", (chunk) => { + // stream callback +}); +``` + +## Client + +Same React hooks as `AIChatAgent`: + +```tsx +const agent = useAgent({ agent: "MyAgent", name: "session-1" }); +const { messages, input, handleInputChange, handleSubmit } = useAgentChat({ agent }); +``` + +## Think vs AIChatAgent + +| | Think | AIChatAgent | +|-|-------|-------------| +| `streamText` loop | Built-in | You write it | +| Tool execution | Automatic | You wire it | +| Customization | Override hooks | Full control in `onChatMessage` | +| Built-in tools | Workspace, execute, browser | None | +| Compatibility flag | Requires `experimental` | Standard | diff --git a/.agents/skills/agents-sdk/references/voice.md b/.agents/skills/agents-sdk/references/voice.md new file mode 100644 index 0000000..388079d --- /dev/null +++ b/.agents/skills/agents-sdk/references/voice.md @@ -0,0 +1,68 @@ +# Voice (Experimental) + +Fetch https://developers.cloudflare.com/agents/communication-channels/voice/index.md for complete documentation. + +`@cloudflare/voice` — real-time speech-to-text and text-to-speech for agents. Audio streams over WebSocket. + +```bash +npm install @cloudflare/voice +``` + +## Server + +```typescript +import { Agent } from "agents"; +import { withVoice, WorkersAITTS, WorkersAINova3STT } from "@cloudflare/voice"; + +export class VoiceAgent extends withVoice(Agent) { + transcriber = new WorkersAINova3STT(this); + tts = new WorkersAITTS(this); + + async onTurn(transcript: string, context: VoiceTurnContext) { + const result = streamText({ + model: createWorkersAI({ binding: this.env.AI })("@cf/meta/llama-4-scout-17b-16e-instruct"), + messages: [ + { role: "system", content: "You are a voice assistant." }, + ...context.conversationHistory, + { role: "user", content: transcript } + ] + }); + + for await (const chunk of result.textStream) { + if (context.signal.aborted) break; + context.speak(chunk); + } + } +} +``` + +## Lifecycle Hooks + +| Hook | Purpose | +|------|---------| +| `onTurn(transcript, ctx)` | Handle transcribed speech (required) | +| `beforeCallStart(conn)` | Auth/validation before call starts | +| `onCallStart(conn)` | Call connected | +| `onCallEnd(conn)` | Call disconnected | +| `onInterrupt()` | User interrupted agent speech | + +## Client (React) + +```tsx +import { useVoiceAgent } from "@cloudflare/voice/react"; + +function VoiceUI() { + const { isConnected, isSpeaking, connect, disconnect } = useVoiceAgent({ + agent: "VoiceAgent", + name: "session-1" + }); + + return ; +} +``` + +## STT/TTS Providers + +Workers AI (default), Deepgram, ElevenLabs — install the provider package and swap the `transcriber`/`tts` properties. diff --git a/.agents/skills/agents-sdk/references/webhooks-push.md b/.agents/skills/agents-sdk/references/webhooks-push.md new file mode 100644 index 0000000..8430523 --- /dev/null +++ b/.agents/skills/agents-sdk/references/webhooks-push.md @@ -0,0 +1,86 @@ +# Webhooks & Push Notifications + +## Webhooks + +Fetch https://developers.cloudflare.com/agents/communication-channels/webhooks/index.md for complete documentation. + +Route external webhooks to agent instances via `onRequest`: + +```typescript +export default { + async fetch(req: Request, env: Env) { + const url = new URL(req.url); + if (url.pathname.startsWith("/webhooks/")) { + const entityId = url.pathname.split("/")[2]; + const agent = getAgentByName(env.MyAgent, entityId); + return agent.fetch(req); + } + return routeAgentRequest(req, env); + } +}; +``` + +In the agent: + +```typescript +export class MyAgent extends Agent { + async onRequest(request: Request) { + const signature = request.headers.get("X-Signature"); + if (!verifySignature(signature, await request.text(), this.env.WEBHOOK_SECRET)) { + return new Response("Unauthorized", { status: 401 }); + } + const payload = JSON.parse(await request.text()); + this.queue("processWebhook", payload); + return new Response("OK", { status: 202 }); + } +} +``` + +**Tips:** Respond quickly (200/202), verify signatures, deduplicate with stored event IDs, use `queue()` for async processing. + +## Push Notifications + +Fetch https://developers.cloudflare.com/agents/communication-channels/webhooks/push-notifications/index.md for complete documentation. + +Web Push via VAPID from agents. Store subscriptions in agent state, send via `web-push`. + +```bash +npm install web-push +``` + +```typescript +import webpush from "web-push"; + +export class NotifyAgent extends Agent { + @callable() + async subscribe(subscription: PushSubscription) { + this.setState({ + ...this.state, + subscriptions: [...this.state.subscriptions, subscription] + }); + } + + async sendReminder(payload: { message: string }, schedule: Schedule) { + for (const sub of this.state.subscriptions) { + try { + await webpush.sendNotification(sub, JSON.stringify({ + title: "Reminder", + body: payload.message + }), { + vapidDetails: { + subject: "mailto:you@example.com", + publicKey: this.env.VAPID_PUBLIC_KEY, + privateKey: this.env.VAPID_PRIVATE_KEY + } + }); + } catch (err) { + if (err.statusCode === 404 || err.statusCode === 410) { + // Remove expired subscription + } + } + } + } +} +``` + +VAPID keys: generate with `npx web-push generate-vapid-keys`, store as secrets. diff --git a/.agents/skills/agents-sdk/references/workflows.md b/.agents/skills/agents-sdk/references/workflows.md new file mode 100644 index 0000000..a434a8b --- /dev/null +++ b/.agents/skills/agents-sdk/references/workflows.md @@ -0,0 +1,21 @@ +# Workflows Integration + +Use Agents for interactive communication and state management. Add a Workflow when a task needs durable multi-step execution, independent retries, or waits for external approval. Choose based on recovery needs; consult [Run Workflows](https://developers.cloudflare.com/agents/runtime/execution/run-workflows/index.md) before implementing the integration. + +## Read for the task + +| Task | Documentation | +| --- | --- | +| Define a typed `AgentWorkflow`, start it from an Agent, and configure bindings | [Quick start](https://developers.cloudflare.com/agents/runtime/execution/run-workflows/index.md#quick-start) | +| Call back into the originating Agent and understand durable versus non-durable helpers | [AgentWorkflow class](https://developers.cloudflare.com/agents/runtime/execution/run-workflows/index.md#agentworkflow-class) | +| Send events, query instances, pause, resume, terminate, or delete tracked workflows | [Agent workflow methods](https://developers.cloudflare.com/agents/runtime/execution/run-workflows/index.md#agent-workflow-methods) | +| Receive progress, completion, errors, and custom events | [Lifecycle callbacks](https://developers.cloudflare.com/agents/runtime/execution/run-workflows/index.md#lifecycle-callbacks) | +| Approve or reject a waiting task | [Human-in-the-loop approval](https://developers.cloudflare.com/agents/runtime/execution/run-workflows/index.md#human-in-the-loop-approval) | +| Persist Workflow results into Agent state | [State synchronization](https://developers.cloudflare.com/agents/runtime/execution/run-workflows/index.md#state-synchronization) | +| Define steps, parameters, retries, and returned values | [Workers API](https://developers.cloudflare.com/workflows/build/workers-api/index.md) | + +## Design checks + +Keep external side effects within durable steps, make retried operations idempotent, and persist the values needed after recovery through step results. Use the [Rules of Workflows](https://developers.cloudflare.com/workflows/build/rules-of-workflows/index.md) to choose step boundaries. + +Progress reports and client broadcasts may repeat on retry. Use the documented durable step helpers for persistent Agent state changes and completion reporting; see [bidirectional communication](https://developers.cloudflare.com/agents/runtime/execution/run-workflows/index.md#bidirectional-communication).