Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
130 commits
Select commit Hold shift + click to select a range
7e13f05
feat: add detailed POC plan for /zai help command migration to Cloudf…
mistral-vibe Aug 6, 2026
b761fe5
docs: add quick start guide for POC implementation
mistral-vibe Aug 6, 2026
1da79ae
feat: add complete POC implementation for /zai help command
mistral-vibe Aug 6, 2026
070f0c2
docs: add POC implementation report with results and next steps
mistral-vibe Aug 6, 2026
2167865
added cloudflare skills
AndreiDrang Aug 6, 2026
814b502
Update README.md
AndreiDrang Aug 6, 2026
9d506d1
feat(poc): restructure into hybrid main and heavy workers
AndreiDrang Aug 6, 2026
ed312d1
build(poc): add makefile and prettier tooling
AndreiDrang Aug 6, 2026
838d502
build(poc): source worker secrets from cloudflare secrets store
AndreiDrang Aug 6, 2026
54a4d61
Update wrangler.toml
AndreiDrang Aug 6, 2026
260ab60
fix(poc): resolve secrets store bindings, handle empty 204 responses
AndreiDrang Aug 6, 2026
94b00e3
refactor(poc): restrict invocation to /zai prefix and credit author
AndreiDrang Aug 6, 2026
2afaa20
ci: remove legacy GitHub Action workflow
AndreiDrang Aug 6, 2026
7071f21
build(poc): add vitest, miniflare, and coverage test stack
AndreiDrang Aug 6, 2026
8d58ab4
test(poc): port vitest suite from tbel cf_workers
AndreiDrang Aug 6, 2026
07facf7
chore(plans): remove obsolete cloudflare migration planning docs
AndreiDrang Aug 7, 2026
d54f32d
feat(workers): add durable pr-preview storage with queue and cron
AndreiDrang Aug 7, 2026
737f9e8
docs(poc): rewrite readme for durable storage architecture
AndreiDrang Aug 7, 2026
4b6e148
fix(workers): reclassify llm commands as heavy
AndreiDrang Aug 7, 2026
548adb5
docs(okf): add knowledge bundle for poc workers
AndreiDrang Aug 7, 2026
934deee
feat(workers): standardize bot footer across all comments
AndreiDrang Aug 7, 2026
0cd06c1
refactor(pr-preview): render metadata-only brief and drop per-file stats
AndreiDrang Aug 7, 2026
edccb50
test(pr-preview): cover generate-once and update-on-sync
AndreiDrang Aug 7, 2026
fabff7d
docs(okf): document metadata-only preview and unified footer
AndreiDrang Aug 7, 2026
9f0ed34
docs(poc): sync README with metadata-only brief and footer
AndreiDrang Aug 7, 2026
76647f3
Update wrangler.toml
AndreiDrang Aug 7, 2026
20b7910
fix(comments): update existing preview comment on synchronize
AndreiDrang Aug 7, 2026
7d08f4b
feat(workers): refresh preview on pr title edit
AndreiDrang Aug 7, 2026
db85450
feat(workers): post lifecycle comment on pr close
AndreiDrang Aug 7, 2026
ff02f26
docs(okf): document closed lifecycle and edited action
AndreiDrang Aug 7, 2026
c14d261
docs(poc): sync readme with closed-state and title-edit
AndreiDrang Aug 7, 2026
14fe220
docs: add storage tier redesign plan
AndreiDrang Aug 7, 2026
8654844
refactor(workers): drop write-only kv/r2 from preview and make config…
AndreiDrang Aug 7, 2026
0aab18a
feat(workers): add pr-context key builders and github context readers
AndreiDrang Aug 7, 2026
02c6c42
feat(workers): register pr_context job kind and gather PR context eag…
AndreiDrang Aug 7, 2026
6fea880
feat(workers): read gathered pr context in review/impact/ask/explain
AndreiDrang Aug 7, 2026
2c923d2
docs: sync okf bundle and readme to the pr-context gather tier
AndreiDrang Aug 7, 2026
b2249ec
Update README.md
AndreiDrang Aug 7, 2026
9d5c40b
docs(poc): extract deferred llm pipeline into its own spec
AndreiDrang Aug 7, 2026
4d00d54
feat(workers): real /zai review via durable job + Z.ai client
AndreiDrang Aug 7, 2026
5b9daa3
Delete STORAGE_REDESIGN_PLAN.md
AndreiDrang Aug 7, 2026
5b55d83
Delete llm-pipeline.md
AndreiDrang Aug 7, 2026
5ad3266
fix(db): make 0004 pr_context migration D1-compatible (wipe-rebuild)
AndreiDrang Aug 7, 2026
90273e1
refactor(db): consolidate migrations 0001-0004 into a single 0001
AndreiDrang Aug 7, 2026
f794a82
fix(context): reconstruct PR diff from per-file patches on >300-file PRs
AndreiDrang Aug 7, 2026
b1a4508
fix(commands): correct stale "only /zai help" unsupported-command mes…
AndreiDrang Aug 7, 2026
8e941c1
refactor(storage): re-key PR context per-PR (not per-head) + full com…
AndreiDrang Aug 7, 2026
a954356
docs(okf): refresh bundle for per-PR context, live /zai review, migra…
AndreiDrang Aug 7, 2026
45717ad
feat(comments): refresh PR comments slice on issue_comment events
AndreiDrang Aug 7, 2026
e582a64
feat(comments): refresh PR description slice on pull_request.edited (…
AndreiDrang Aug 7, 2026
0814ecc
docs(okf): document incremental context-slice refresh (comments + des…
AndreiDrang Aug 7, 2026
1b0b374
docs(okf): note manifest.counts lag during incremental slice refresh
AndreiDrang Aug 7, 2026
04b4166
feat(workers): full-context /zai review via reusable LLM command scaf…
AndreiDrang Aug 8, 2026
6d13595
chore: remove obsolete heavy-commands plan doc
AndreiDrang Aug 8, 2026
f5f7cf0
refactor: focus bot on review and describe workers
AndreiDrang Aug 16, 2026
816a09e
upd glm versions
AndreiDrang Aug 16, 2026
cf5b006
Update wrangler.toml
AndreiDrang Aug 16, 2026
c132b56
Update wrangler.toml
AndreiDrang Aug 16, 2026
fd43c1e
fix: provide workers build scripts
AndreiDrang Aug 16, 2026
d204dd7
feat: restore zai help command
AndreiDrang Aug 16, 2026
7072c6d
test: cover help in unknown command response
AndreiDrang Aug 16, 2026
406348e
test: align PR event contract
AndreiDrang Aug 16, 2026
a8ae78f
test: repair storage state suite
AndreiDrang Aug 16, 2026
467a455
fix tests
AndreiDrang Aug 16, 2026
5a4cc62
feat: initialize structured PR context
AndreiDrang Aug 16, 2026
90f29e6
fix: avoid noisy R2 misses during context gather
AndreiDrang Aug 16, 2026
83f95cd
fix: reduce PR summary context timeouts
AndreiDrang Aug 16, 2026
137916a
refactor: remove PR summary risk assessment
AndreiDrang Aug 16, 2026
4e2f544
feat(context): add v2 per-file snapshot storage and service
AndreiDrang Aug 16, 2026
cf0e91b
feat(context): dual-write v2 snapshots during context gather
AndreiDrang Aug 16, 2026
1b03acb
feat(context): prefer v2 snapshots in summary and commands
AndreiDrang Aug 16, 2026
019c4ff
feat(context-tools): add llm tool registry over v2 snapshots
AndreiDrang Aug 16, 2026
7e620d2
docs(workers): cover v2 retention and storage bindings
AndreiDrang Aug 16, 2026
25262c2
refactor(context): drop v1 pr-context dual-write and legacy readers
AndreiDrang Aug 16, 2026
22f8b2e
docs(agents): add nested AGENTS.md guidance for workers
AndreiDrang Aug 16, 2026
e8c35fe
Update ARCHITECTURE.md
AndreiDrang Aug 16, 2026
ce58cc6
fix(context): index all pr files across github pagination
AndreiDrang Aug 17, 2026
aaefd46
refactor(context): expose metadata dtos and hide storage internals
AndreiDrang Aug 17, 2026
73f8b07
feat(agent): add tool-calling runner and z.ai chat transport
AndreiDrang Aug 17, 2026
8088c38
feat(review): defer diff loading to agent context tools
AndreiDrang Aug 17, 2026
c154048
fix(context): reject stale pr_context deliveries against newest pr head
AndreiDrang Aug 17, 2026
7433c50
docs(agents): sync guides with current layout and commands
AndreiDrang Aug 17, 2026
533849b
docs(okf): refresh bundle for v2 context tier and agent commands
AndreiDrang Aug 17, 2026
235ebc9
docs: add okf-knowledge guidance to AGENTS.md
AndreiDrang Aug 17, 2026
985ce98
feat(review): compose prompts from shared retrieval and trust policies
AndreiDrang Aug 17, 2026
3ffda37
refactor(context-tools): rewrite tool descriptions with semantic guid…
AndreiDrang Aug 17, 2026
b0f0d86
style(test): reformat pr-context bucket mocks
AndreiDrang Aug 17, 2026
596b8af
docs(architecture): refresh for agent loop and v3 job schema
AndreiDrang Aug 17, 2026
7593689
docs(okf): correct model fact and complete provenance
AndreiDrang Aug 17, 2026
5ca0983
test(main-worker): cover entrypoint, job enqueuer, and event planners
AndreiDrang Aug 17, 2026
26aa3b4
test(storage): cover job recovery and comment publication edges
AndreiDrang Aug 17, 2026
a9616db
test(shared): lift branch coverage on defensive and error paths
AndreiDrang Aug 17, 2026
3e923c2
test(coverage): gate per-glob thresholds and enable lcov reporting
AndreiDrang Aug 17, 2026
260a552
test(agent): verify concurrent tool results reach the next turn
AndreiDrang Aug 17, 2026
8e70b87
feat(review): enlarge prompt budget shares and flag binary files
AndreiDrang Aug 17, 2026
a16fe90
feat(agent): enable context tools for summaries
AndreiDrang Aug 22, 2026
35e4a1a
fix(review): bound agent retrieval and retries
AndreiDrang Aug 22, 2026
157b40a
fix(review): report tool limit in PR comment
AndreiDrang Aug 22, 2026
cd0482d
fix(context): omit false binary file markers
AndreiDrang Aug 22, 2026
28a3967
fix(comments): explain terminal LLM failures
AndreiDrang Aug 22, 2026
2abcdcb
fix(context): preserve review binary flags
AndreiDrang Aug 22, 2026
1aca251
test(review): expect detailed transport failure notice
AndreiDrang Aug 22, 2026
f948500
feat(review): prioritize high-risk retrieval and dedupe tool calls
AndreiDrang Aug 23, 2026
c671cd9
fix(agent): skip llm requests below the minimum viable timeout
AndreiDrang Aug 23, 2026
5655e9c
feat(review): add finalization time reserve and review metadata
AndreiDrang Aug 23, 2026
90b3d18
style: reformat prompts, handlers, and tests
AndreiDrang Aug 23, 2026
c364c1d
feat(agent): finalize reviews instead of failing at retrieval budgets
AndreiDrang Aug 23, 2026
ed4d847
feat(agent): add stage-aware llm timeouts and bounded retries
AndreiDrang Aug 23, 2026
400fa09
fix(webhooks): only run /zai commands on comment created actions
AndreiDrang Aug 23, 2026
063e660
fix(queue): re-delay early redeliveries and sweep stranded due jobs
AndreiDrang Aug 23, 2026
0f34ee7
fix(comments): wait out publication lease contention instead of silen…
AndreiDrang Aug 23, 2026
6045c9e
fix(help): only update bot-owned help comments
AndreiDrang Aug 23, 2026
5706d5d
chore(config): keep single custom-domain route for main worker
AndreiDrang Aug 23, 2026
9b5d2c9
docs(okf): document action gate, stranded-job sweep, publication wait…
AndreiDrang Aug 23, 2026
0a8a67e
test(comments): cover bot-ownership branches and simplify publication…
AndreiDrang Aug 23, 2026
3d0dc45
docs(okf): normalize heading levels and refresh command-routing descr…
AndreiDrang Aug 23, 2026
b53e34e
style(workers): reformat review-fix files
AndreiDrang Aug 23, 2026
20dbf83
chore(coverage): set uniform 70% floor including branches
AndreiDrang Aug 23, 2026
9812b6d
test(llm-command-runner): cover non-agent path, snapshot edges, and f…
AndreiDrang Aug 23, 2026
3736b36
test(context-service): cover manifest states, guards, and slice clamps
AndreiDrang Aug 23, 2026
9004e51
test(zai-client): cover transport edges, chat deadlines, and header p…
AndreiDrang Aug 23, 2026
04434d9
test(agent): cover runner protocol guards and context rendering edges
AndreiDrang Aug 23, 2026
0ade60d
test(storage): cover delivery races, github shapes, and prompt fallbacks
AndreiDrang Aug 23, 2026
dfb7706
chore(make): print per-column coverage averages after test runs
AndreiDrang Aug 23, 2026
cd7acbc
style(workers): reformat coverage test files
AndreiDrang Aug 23, 2026
49f777f
refactor(repo): move poc/ workspace to src/ with root npm project
AndreiDrang Aug 23, 2026
93912c8
docs(readme): merge workers README into root README
AndreiDrang Aug 23, 2026
7d2d332
docs(arch): rewrite ARCHITECTURE and AGENTS for src/ layout
AndreiDrang Aug 23, 2026
21d982a
docs(okf): refresh source paths and drop POC wording
AndreiDrang Aug 23, 2026
d5e6700
style(docs): normalize markdown formatting
AndreiDrang Aug 23, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
221 changes: 221 additions & 0 deletions .agents/skills/agents-sdk/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
---
name: agents-sdk
description: Build AI agents on Cloudflare Workers using the Agents SDK. Load when creating stateful agents, durable workflows, real-time WebSocket apps, scheduled tasks, MCP servers, chat applications, voice agents, or browser automation. Covers Agent class, state management, callable RPC, Workflows, durable execution, queues, retries, observability, and React hooks. Biases towards retrieval from Cloudflare docs over pre-trained knowledge.
---

# 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/

| Topic | Docs URL | Use for |
|-------|----------|---------|
| Getting started | [Quick start](https://developers.cloudflare.com/agents/getting-started/quick-start/) | First agent, project setup |
| Adding to existing project | [Add to existing project](https://developers.cloudflare.com/agents/getting-started/add-to-existing-project/) | Install into existing Workers app |
| Configuration | [Configuration](https://developers.cloudflare.com/agents/api-reference/configuration/) | `wrangler.jsonc`, bindings, assets, deployment |
| Agent class | [Agents API](https://developers.cloudflare.com/agents/api-reference/agents-api/) | Agent lifecycle, patterns, pitfalls |
| State | [Store and sync state](https://developers.cloudflare.com/agents/api-reference/store-and-sync-state/) | `setState`, `validateStateChange`, persistence |
| Routing | [Routing](https://developers.cloudflare.com/agents/api-reference/routing/) | URL patterns, `routeAgentRequest` |
| Callable methods | [Callable methods](https://developers.cloudflare.com/agents/api-reference/callable-methods/) | `@callable`, RPC, streaming, timeouts |
| Scheduling | [Schedule tasks](https://developers.cloudflare.com/agents/api-reference/schedule-tasks/) | `schedule()`, `scheduleEvery()`, cron |
| Workflows | [Run workflows](https://developers.cloudflare.com/agents/api-reference/run-workflows/) | `AgentWorkflow`, durable multi-step tasks |
| HTTP/WebSockets | [WebSockets](https://developers.cloudflare.com/agents/api-reference/websockets/) | Lifecycle hooks, hibernation |
| Chat agents | [Chat agents](https://developers.cloudflare.com/agents/api-reference/chat-agents/) | `AIChatAgent`, streaming, tools, persistence |
| Client SDK | [Client SDK](https://developers.cloudflare.com/agents/api-reference/client-sdk/) | `useAgent`, `useAgentChat`, React hooks |
| Client tools | [Client tools](https://developers.cloudflare.com/agents/api-reference/client-tools/) | Client-side tools, `autoContinueAfterToolResult` |
| Server-driven messages | [Trigger patterns](https://developers.cloudflare.com/agents/api-reference/trigger-patterns/) | `saveMessages`, `waitUntilStable`, server-initiated turns |
| Resumable streaming | [Resumable streaming](https://developers.cloudflare.com/agents/api-reference/resumable-streaming/) | Stream recovery on disconnect |
| Email | [Email](https://developers.cloudflare.com/agents/api-reference/email/) | Email routing, secure reply resolver |
| MCP client | [MCP client](https://developers.cloudflare.com/agents/api-reference/mcp-client-api/) | Connecting to MCP servers |
| MCP server | [MCP server](https://developers.cloudflare.com/agents/api-reference/mcp-agent-api/) | Building MCP servers with `McpAgent` |
| MCP transports | [MCP transports](https://developers.cloudflare.com/agents/api-reference/mcp-transports/) | Streamable HTTP, SSE, RPC transport options |
| Securing MCP servers | [Securing MCP](https://developers.cloudflare.com/agents/api-reference/securing-mcp-servers/) | OAuth, proxy MCP, hardening |
| Human-in-the-loop | [Human-in-the-loop](https://developers.cloudflare.com/agents/concepts/human-in-the-loop/) | Approval flows, `needsApproval`, workflows |
| Durable execution | [Durable execution](https://developers.cloudflare.com/agents/api-reference/durable-execution/) | `runFiber()`, `stash()`, surviving DO eviction |
| Queue | [Queue](https://developers.cloudflare.com/agents/api-reference/queue-tasks/) | Built-in FIFO queue, `queue()` |
| Retries | [Retries](https://developers.cloudflare.com/agents/api-reference/retries/) | `this.retry()`, backoff/jitter |
| Observability | [Observability](https://developers.cloudflare.com/agents/api-reference/observability/) | Diagnostics-channel events |
| Push notifications | [Push notifications](https://developers.cloudflare.com/agents/api-reference/push-notifications/) | Web Push + VAPID from agents |
| Webhooks | [Webhooks](https://developers.cloudflare.com/agents/api-reference/webhooks/) | Receiving external webhooks |
| Cross-domain auth | [Cross-domain auth](https://developers.cloudflare.com/agents/api-reference/cross-domain-authentication/) | WebSocket auth, tokens, CORS |
| Readonly connections | [Readonly](https://developers.cloudflare.com/agents/api-reference/readonly-connections/) | `shouldConnectionBeReadonly` |
| Voice | [Voice](https://developers.cloudflare.com/agents/api-reference/voice/) | Experimental STT/TTS, `withVoice` |
| Browse the web | [Browser tools](https://developers.cloudflare.com/agents/api-reference/browse-the-web/) | Experimental CDP browser automation |
| Think | [Think](https://developers.cloudflare.com/agents/api-reference/think/) | Experimental higher-level chat agent class |
| Migrations | [AI SDK v5](https://developers.cloudflare.com/agents/guides/migration-to-ai-sdk-v5/), [AI SDK v6](https://developers.cloudflare.com/agents/guides/migration-to-ai-sdk-v6/) | 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 `McpAgent`
- **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<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 })
};
```

## 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

```tsx
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>
);
}
```

## 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
63 changes: 63 additions & 0 deletions .agents/skills/agents-sdk/references/browse-the-web.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# Browse the Web (Experimental)

Fetch https://developers.cloudflare.com/agents/api-reference/browse-the-web/ 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<Env> {
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" });
```
92 changes: 92 additions & 0 deletions .agents/skills/agents-sdk/references/callable.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
# Callable Methods

Fetch https://developers.cloudflare.com/agents/api-reference/callable-methods/ for complete documentation.

## Overview

`@callable()` exposes agent methods to clients via WebSocket RPC.

```typescript
import { Agent, callable } from "agents";

export class MyAgent extends Agent<Env, State> {
@callable()
async greet(name: string): Promise<string> {
return `Hello, ${name}!`;
}

@callable()
async processData(data: unknown): Promise<Result> {
// 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<Env, State> {
@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 |
Loading
Loading