diff --git a/public/__redirects b/public/__redirects index 163b1af4b5d..4c47d794241 100644 --- a/public/__redirects +++ b/public/__redirects @@ -365,7 +365,6 @@ /agents/agentic-payments/mpp/ /agents/tools/payments/mpp/ 301 /agents/guides/ /agents/model-context-protocol/guides/ 301 /agents/concepts/agent-class/ /agents/agent-class/internals/ 301 -/agents/concepts/memory/ /agents/concepts/conversation-state-and-memory/ 301 /agents/getting-started/prompting/ /workers/get-started/prompting/ 301 /agents/platform/prompting/ /workers/get-started/prompting/ 301 /agents/platform/prompt.txt/ /workers/prompt.txt 301 @@ -388,6 +387,8 @@ /agents/tools/payments/mpp/charge-for-http-content/ /agents/tools/payments/mpp-charge-for-http-content/ 301 /agents/tools/payments/mpp/protect-an-origin/ /agents/tools/payments/mpp-charge-for-http-content/ 301 /agents/agentic-payments/mpp/charge-for-http-content/ /agents/tools/payments/mpp-charge-for-http-content/ 301 +/agents/concepts/calling-llms/ /agents/concepts/models/ 301 +/agents/concepts/conversation-state-and-memory/ /agents/concepts/memory/ 301 # ai-audit /ai-audit/features/detect-ai-crawlers/ /ai-crawl-control/features/analyze-ai-crawlers/ 301 diff --git a/src/content/changelog/durable-objects/2026-06-19-outbound-connections-keep-dos-alive.mdx b/src/content/changelog/durable-objects/2026-06-19-outbound-connections-keep-dos-alive.mdx index 629d882268e..ffaaa27d194 100644 --- a/src/content/changelog/durable-objects/2026-06-19-outbound-connections-keep-dos-alive.mdx +++ b/src/content/changelog/durable-objects/2026-06-19-outbound-connections-keep-dos-alive.mdx @@ -18,7 +18,7 @@ With this change, each active outbound connection prevents eviction. Once all ou ![Timeline showing the same outbound stream completing because the active connection keeps the Durable Object alive, with the inactivity window starting only after the connection closes](~/assets/images/durable-objects/outbound-connection-after.svg) -If you are [building agents on Cloudflare](/agents/), this is especially relevant. An agent that streams tokens from an LLM while [calling models](/agents/concepts/calling-llms/), or that performs [long-running tasks](/agents/concepts/agentic-patterns/long-running-agents/) over an outbound connection, now stays alive for the duration of that connection instead of being evicted mid-stream. +If you are [building agents on Cloudflare](/agents/), this is especially relevant. An agent that streams tokens from an LLM while [calling models](/agents/concepts/models/), or that performs [long-running tasks](/agents/concepts/agentic-patterns/long-running-agents/) over an outbound connection, now stays alive for the duration of that connection instead of being evicted mid-stream. **Limits:** diff --git a/src/content/docs/agents/concepts/agentic-patterns/human-in-the-loop.mdx b/src/content/docs/agents/concepts/agentic-patterns/human-in-the-loop.mdx index 69499d5b5a4..684d6f786f5 100644 --- a/src/content/docs/agents/concepts/agentic-patterns/human-in-the-loop.mdx +++ b/src/content/docs/agents/concepts/agentic-patterns/human-in-the-loop.mdx @@ -1,595 +1,91 @@ --- title: Human-in-the-loop patterns -pcx_content_type: how-to +pcx_content_type: concept sidebar: order: 2 -description: Implement human-in-the-loop functionality using Workflow approvals, durable Code Mode approvals, and MCP elicitation. +description: Pause an agent for a person's approval or input, with tool approvals, MCP elicitation, durable Code Mode approvals, and Workflow approvals. products: - agents --- -import { TypeScriptExample, WranglerConfig, LinkCard } from "~/components"; +import { LinkCard } from "~/components"; -Human-in-the-loop (HITL) patterns add approval or input at different layers of an Agent. You can respond to an MCP server request, hold application work in a durable Workflow, or approve a connector call before model-generated code invokes a tool. +Human-in-the-loop (HITL) patterns pause an agent until a person approves an action or answers a question. The agent then continues where it stopped. -## Why human-in-the-loop? +## Why human-in-the-loop -- **Compliance**: Regulatory requirements may mandate human approval for certain actions -- **Safety**: High-stakes operations (payments, deletions, external communications) need oversight -- **Quality**: Human review catches errors AI might miss -- **Trust**: Users feel more confident when they can approve critical actions +- **Safety**: high-stakes actions, such as payments, deletions, and outgoing emails, need oversight. +- **Compliance**: regulations may require a person to approve some actions. +- **Quality**: a person catches mistakes the model makes. +- **Trust**: users are more confident when they approve the actions that matter. -### Common use cases +## Kinds of pause -Common uses include financial approvals, content moderation, bulk data operations, approval before side-effecting tool calls, and access-control changes. +A pause happens at one of four layers. Choose the pattern by who asks for the pause, and how long it can last: -## Choosing a pattern +| Pattern | Who asks for the pause | Typical wait | Where it is implemented | +| ------------------ | ----------------------------------------- | ---------------- | ----------------------------- | +| Tool approval | The agent developer, per tool | Seconds to hours | The harness | +| MCP elicitation | The developer of an MCP server | Minutes | The MCP client capability | +| Code Mode approval | The agent developer, per connector method | Until it expires | The durable Code Mode runtime | +| Workflow approval | The agent developer, per process | Days to months | Cloudflare Workflows | -Choose the pattern based on who introduces the pause and where it occurs: +## Tool approval -| Pattern | Approval layer | Initiated by | Typical wait | Key API | -| ---------------------- | ------------------------------------------ | --------------------------- | ----------------------- | ------------------------------------------- | -| **MCP elicitation** | MCP request handled by your Agent client | MCP server developer | Minutes | `configureElicitationHandlers()` | -| **Workflow approval** | Durable application task or tool operation | Agent application developer | Months or years | `waitForApproval()` | -| **Code Mode approval** | Connector call in model-generated code | Code Mode Agent developer | Until configured expiry | `requiresApproval`, `approve()`, `reject()` | +The model asks for a tool call, and the harness holds it until a person decides. The turn settles as waiting for input. When the answer arrives, the harness runs the call or tells the model it was refused, and the turn continues. -## Workflow-based approval +- In [Think](/agents/harnesses/think/tools/#tool-approval), set `needsApproval` on a tool. Think sends the call to the client, and pauses the conversation until the client responds. +- In the [Pi harness](/agents/harnesses/pi/), your code decides when to ask, for example in a tool that returns early. Submit the outcome to the session as input labelled with your own entry kind, such as `app.approval`, so the transcript records who approved it. -Use [Cloudflare Workflows](/workflows/) when your application needs to hold a task or tool operation for as long as approval requires. `waitForApproval()` creates a durable gate backed by Cloudflare Workflows, so the wait can continue for months or longer without keeping an Agent running. - -### Basic pattern - - - -```ts -import { Agent } from "agents"; -import { AgentWorkflow } from "agents/workflows"; -import type { AgentWorkflowEvent, AgentWorkflowStep } from "agents/workflows"; - -type ExpenseParams = { - amount: number; - description: string; - requestedBy: string; -}; - -export class ExpenseWorkflow extends AgentWorkflow< - ExpenseAgent, - ExpenseParams -> { - async run(event: AgentWorkflowEvent, step: AgentWorkflowStep) { - const expense = event.payload; - - // Step 1: Validate the expense - const validated = await step.do("validate", async () => { - if (expense.amount <= 0) { - throw new Error("Invalid expense amount"); - } - return { ...expense, validatedAt: Date.now() }; - }); - - // Step 2: Report that we are waiting for approval - await this.reportProgress({ - step: "approval", - status: "pending", - message: `Awaiting approval for $${expense.amount}`, - }); - - // Step 3: Wait for human approval (pauses the workflow) - const approval = await this.waitForApproval<{ approvedBy: string }>(step, { - timeout: "7 days", - }); - - console.log(`Approved by: ${approval?.approvedBy}`); - - // Step 4: Process the approved expense - const result = await step.do("process", async () => { - return { expenseId: crypto.randomUUID(), ...validated }; - }); - - await step.reportComplete(result); - return result; - } -} -``` - - - -### Agent methods for approval - -The agent provides methods to approve or reject waiting workflows: - - - -```ts -import { Agent, callable } from "agents"; - -type PendingApproval = { - workflowId: string; - amount: number; - description: string; - requestedBy: string; - requestedAt: number; -}; - -type ExpenseState = { - pendingApprovals: PendingApproval[]; -}; - -export class ExpenseAgent extends Agent { - initialState: ExpenseState = { - pendingApprovals: [], - }; - - // Approve a waiting workflow - @callable() - async approve(workflowId: string, approvedBy: string): Promise { - await this.approveWorkflow(workflowId, { - reason: "Expense approved", - metadata: { approvedBy, approvedAt: Date.now() }, - }); - - // Update state to reflect approval - this.setState({ - ...this.state, - pendingApprovals: this.state.pendingApprovals.filter( - (p) => p.workflowId !== workflowId, - ), - }); - } - - // Reject a waiting workflow - @callable() - async reject(workflowId: string, reason: string): Promise { - await this.rejectWorkflow(workflowId, { reason }); - - this.setState({ - ...this.state, - pendingApprovals: this.state.pendingApprovals.filter( - (p) => p.workflowId !== workflowId, - ), - }); - } - - // Track workflow progress to update pending approvals - async onWorkflowProgress( - workflowName: string, - workflowId: string, - progress: unknown, - ): Promise { - const p = progress as { step: string; status: string; message?: string }; - - if (p.step === "approval" && p.status === "pending") { - // Add to pending approvals list for UI display - this.setState({ - ...this.state, - pendingApprovals: [ - ...this.state.pendingApprovals, - { - workflowId, - amount: 0, // Would come from workflow params - description: p.message || "", - requestedBy: "user", - requestedAt: Date.now(), - }, - ], - }); - } - } -} -``` - - - -### Timeout handling - -Set timeouts to prevent workflows from waiting indefinitely: - - - -```ts -const approval = await this.waitForApproval<{ approvedBy: string }>(step, { - timeout: "7 days", // Also supports: "1 hour", "30 minutes", etc. -}); - -if (!approval) { - // Timeout expired - escalate or auto-reject - await step.reportError("Approval timeout - escalating to manager"); - throw new Error("Approval timeout"); -} -``` - - - -### Escalation with scheduling - -Use `schedule()` to set up escalation reminders: - - - -```ts -import { Agent, callable } from "agents"; - -class ExpenseAgent extends Agent { - @callable() - async submitForApproval(expense: ExpenseParams): Promise { - // Start the approval workflow - const workflowId = await this.runWorkflow("EXPENSE_WORKFLOW", expense); - - // Schedule reminder after 4 hours - await this.schedule(Date.now() + 4 * 60 * 60 * 1000, "sendReminder", { - workflowId, - }); - - // Schedule escalation after 24 hours - await this.schedule(Date.now() + 24 * 60 * 60 * 1000, "escalateApproval", { - workflowId, - }); - - return workflowId; - } - - async sendReminder(payload: { workflowId: string }) { - const workflow = this.getWorkflow(payload.workflowId); - if (workflow?.status === "waiting") { - // Send reminder notification - console.log("Reminder: approval still pending"); - } - } - - async escalateApproval(payload: { workflowId: string }) { - const workflow = this.getWorkflow(payload.workflowId); - if (workflow?.status === "waiting") { - // Escalate to manager - console.log("Escalating to manager"); - } - } -} -``` - - - -### Audit trail with SQL - -Use `this.sql` to maintain an immutable audit trail: - - - -```ts -import { Agent, callable } from "agents"; - -class ExpenseAgent extends Agent { - async onStart() { - // Create audit table - this.sql` - CREATE TABLE IF NOT EXISTS approval_audit ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - workflow_id TEXT NOT NULL, - decision TEXT NOT NULL CHECK(decision IN ('approved', 'rejected')), - decided_by TEXT NOT NULL, - decided_at INTEGER NOT NULL, - reason TEXT - ) - `; - } - - @callable() - async approve( - workflowId: string, - userId: string, - reason?: string, - ): Promise { - // Record the decision in SQL (immutable audit log) - this.sql` - INSERT INTO approval_audit (workflow_id, decision, decided_by, decided_at, reason) - VALUES (${workflowId}, 'approved', ${userId}, ${Date.now()}, ${reason || null}) - `; - - // Process the approval - await this.approveWorkflow(workflowId, { - reason: reason || "Approved", - metadata: { approvedBy: userId }, - }); - } -} -``` - - - -### Configuration - - - -```jsonc -{ - "name": "expense-approval", - "main": "src/index.ts", - "upload_source_maps": true, - "compatibility_date": "$today", - "compatibility_flags": ["nodejs_compat"], - "durable_objects": { - "bindings": [{ "name": "EXPENSE_AGENT", "class_name": "ExpenseAgent" }], - }, - "workflows": [ - { - "name": "expense-workflow", - "binding": "EXPENSE_WORKFLOW", - "class_name": "ExpenseWorkflow", - }, - ], - "migrations": [{ "tag": "v1", "new_sqlite_classes": ["ExpenseAgent"] }], -} -``` - - +The pending call is stored in the agent's SQLite database, so it survives hibernation and disconnects. The person can answer from another device, hours later. ## MCP elicitation -MCP elicitation lets an MCP server developer decide that a tool call needs more information or an out-of-band interaction. Your Agent acts as the MCP client: it presents the request to the user and returns their response. These interactions typically complete within minutes. - -Form mode collects structured, non-sensitive input. URL mode asks the user to open an out-of-band flow, such as third-party authorization or payment. - -Configure the user-facing handlers in `onStart()`: - - - -```ts -import { Agent } from "agents"; -import type { ElicitRequest, ElicitResult } from "agents/mcp/client"; - -export class MyAgent extends Agent { - onStart() { - this.mcp.configureElicitationHandlers({ - form: (request, serverId) => - this.forwardElicitationToUser(request, serverId), - url: (request, serverId) => - this.forwardElicitationToUser(request, serverId), - }); - } - - private forwardElicitationToUser( - request: ElicitRequest, - serverId: string, - ): Promise { - // Present the request in your UI and resolve after the user responds. - throw new Error( - `Implement elicitation for ${serverId}: ${request.params.message}`, - ); - } -} -``` - - - -For the complete form, URL, and browser forwarding patterns, refer to [MCP client elicitation](/agents/model-context-protocol/apis/client-api/#elicitation). For the server side, refer to [Elicitation with a stateless handler](/agents/model-context-protocol/apis/handler-api/#elicitation-with-a-stateless-handler). - -## Durable Code Mode approvals - -Use the [durable Code Mode runtime](/agents/tools/codemode/durable-runtime/) for coding agents and other Agents that use the Code Mode pattern. Mark a connector method with `requiresApproval: true` to pause model-generated code before it invokes the underlying tool. - -The following example marks a GitHub MCP tool as approval-gated, adds the connector to a durable runtime, and exposes methods that a UI can use to inspect, approve, or reject the pending action: - - - -```ts -import { AIChatAgent } from "@cloudflare/ai-chat"; -import { - createCodemodeRuntime, - DynamicWorkerExecutor, - McpConnector, - type CodemodeRuntimeHandle, - type ConnectorTool, - type McpConnectionLike, - type PendingAction, -} from "@cloudflare/codemode"; -import { callable } from "agents"; -import { convertToModelMessages, stepCountIs, streamText } from "ai"; -import { model } from "./model"; - -class GitHubConnector extends McpConnector { - private connection: McpConnectionLike; - - constructor( - ctx: DurableObjectState, - env: Env, - connection: McpConnectionLike, - ) { - super(ctx, env); - this.connection = connection; - } - - override name() { - return "github"; - } - - protected override createConnection() { - return this.connection; - } - - protected override tool(name: string, tool: ConnectorTool): ConnectorTool { - if (name === "create_issue") { - return { ...tool, requiresApproval: true }; - } - return tool; - } -} - -export class CodingAgent extends AIChatAgent { - private runtime(): CodemodeRuntimeHandle { - const server = this.mcp - .listServers() - .find((item) => item.name === "GitHub"); - if (!server) throw new Error("GitHub MCP server is not registered."); - - const connection = this.mcp.mcpConnections[server.id]; - if (!connection) throw new Error("GitHub MCP connection is unavailable."); - - return createCodemodeRuntime({ - ctx: this.ctx, - executor: new DynamicWorkerExecutor({ loader: this.env.LOADER }), - connectors: [new GitHubConnector(this.ctx, this.env, connection)], - }); - } - - async onChatMessage() { - const result = streamText({ - model, - messages: await convertToModelMessages(this.messages), - tools: { codemode: this.runtime().tool() }, - stopWhen: stepCountIs(10), - }); - - return result.toUIMessageStreamResponse(); - } +An MCP server can ask for more information during a tool call. The agent is the MCP client, so it shows the request to the user and returns the answer: - @callable() - async pendingApprovals(): Promise { - return this.runtime().pending(); - } +- **Form mode** collects structured input that is not sensitive. +- **URL mode** asks the user to open a separate flow, such as an authorization or a payment page. - @callable() - async approveExecution(executionId: string) { - return this.runtime().approve({ executionId }); - } +Set the handlers with `configureElicitationHandlers()` on the [MCP client](/agents/runtime/capabilities/mcp-client-manager/). For the server side, refer to [Elicitation with a stateless handler](/agents/model-context-protocol/apis/handler-api/#elicitation-with-a-stateless-handler). - @callable() - async rejectExecution(executionId: string, seq: number): Promise { - return this.runtime().reject({ executionId, seq }); - } -} -``` +## Durable Code Mode approval - +With [Code Mode](/agents/tools/codemode/), the model writes code that calls tools. Mark a connector method with `requiresApproval: true`, and the [durable Code Mode runtime](/agents/tools/codemode/durable-runtime/) pauses the code before that call. -When generated code calls `github.create_issue()`, the runtime records the pending method and arguments, then pauses before the MCP tool executes. Approval starts another pass with the same source code and execution ID. Previously completed calls replay from the durable log, the approved call executes, and the generated code continues. +When the person approves, the runtime runs the same code again. Calls that already completed replay from a durable log instead of running twice. The approved call then runs, and the code continues. For more information, refer to [Approvals through abort and replay](/agents/tools/codemode/how-it-works/#approvals-through-abort-and-replay). -Pending approvals and execution history survive request completion and Durable Object hibernation. For the execution and replay model, refer to [Approvals through abort and replay](/agents/tools/codemode/how-it-works/#approvals-through-abort-and-replay). +## Workflow approval -## Build Workflow approval UIs +For a process that can wait for a long time, use [Cloudflare Workflows](/agents/concepts/workflows/). A Workflow step waits for an approval event. The wait can last for months, and the agent does not stay in memory. -### Pending approvals list +On the `Agent` class, `waitForApproval()` in an `AgentWorkflow`, and `approveWorkflow()` and `rejectWorkflow()` on the agent, implement this pattern. For an example, refer to [Run Workflows](/agents/agent-class/run-workflows/#human-in-the-loop-approval). -Use the agent's state to display pending approvals in your UI: +## Timeouts and escalation -```tsx -import { useAgent } from "agents/react"; +A pause should not last forever. When the agent asks for approval, use the [Scheduler](/agents/runtime/capabilities/scheduler/) to schedule a check. If no one has answered by then, remind the person, escalate to someone else, or reject the action. -function PendingApprovals() { - const { state, agent } = useAgent({ - agent: "expense-agent", - name: "main", - }); - - if (!state?.pendingApprovals?.length) { - return

No pending approvals

; - } - - return ( -
- {state.pendingApprovals.map((item) => ( -
-

${item.amount}

-

{item.description}

-

Requested by {item.requestedBy}

- -
- - -
-
- ))} -
- ); -} -``` - -## Add multiple Workflow approvers - -For sensitive operations requiring multiple approvers: - - - -```ts -import { Agent, callable } from "agents"; - -type MultiApproval = { - workflowId: string; - requiredApprovals: number; - currentApprovals: Array<{ userId: string; approvedAt: number }>; - rejections: Array<{ userId: string; rejectedAt: number; reason: string }>; -}; - -type State = { - pendingMultiApprovals: MultiApproval[]; -}; - -class MultiApprovalAgent extends Agent { - @callable() - async approveMulti(workflowId: string, userId: string): Promise { - const approval = this.state.pendingMultiApprovals.find( - (p) => p.workflowId === workflowId, - ); - if (!approval) throw new Error("Approval not found"); - - // Check if user already approved - if (approval.currentApprovals.some((a) => a.userId === userId)) { - throw new Error("Already approved by this user"); - } - - // Add this user's approval - approval.currentApprovals.push({ userId, approvedAt: Date.now() }); - - // Check if we have enough approvals - if (approval.currentApprovals.length >= approval.requiredApprovals) { - // Execute the approved action - await this.approveWorkflow(workflowId, { - metadata: { approvers: approval.currentApprovals }, - }); - return true; - } - - this.setState({ ...this.state }); - return false; // Still waiting for more approvals - } -} -``` - - +For `Agent` class examples of these patterns, refer to [MCP client](/agents/runtime/capabilities/mcp-client-manager/) for elicitation, [Scheduler](/agents/runtime/capabilities/scheduler/) for reminders and escalation, the [client SDK](/agents/agent-class/communication-channels/chat/client-sdk/) for a list of pending approvals, [State](/agents/agent-class/state/) for an audit trail, and [Run Workflows](/agents/agent-class/run-workflows/) for Workflow approvals, timeouts, and multiple approvers. ## Best practices -1. **Define clear approval criteria** — Only require confirmation for actions with meaningful consequences (payments, emails, data changes) -2. **Provide detailed context** — Show users exactly what the action will do, including all arguments -3. **Implement timeouts** — Use `schedule()` to escalate or auto-reject after reasonable periods -4. **Maintain audit trails** — Use `this.sql` to record all approval decisions for compliance -5. **Handle connection drops** — Store pending approvals in agent state so they survive disconnections -6. **Graceful degradation** — Provide fallback behavior if approvals are rejected - -## Next steps +1. **Ask only when it matters.** Require approval for actions with real consequences, such as payments, emails, and data changes. +2. **Show the full action.** Show exactly what the action will do, including every argument. +3. **Set a timeout.** Escalate or reject after a reasonable time. +4. **Keep an audit trail.** Record each decision, who made it, and when, in the agent's database. +5. **Plan for a refusal.** Tell the model what happened, so it can choose another path. - +## Related resources { href="/agents/tools/codemode/durable-runtime/" description="Pause model-generated code for approval before connector calls." /> + + diff --git a/src/content/docs/agents/concepts/agentic-patterns/index.mdx b/src/content/docs/agents/concepts/agentic-patterns/index.mdx index 8545f41a04c..d18c59f20d8 100644 --- a/src/content/docs/agents/concepts/agentic-patterns/index.mdx +++ b/src/content/docs/agents/concepts/agentic-patterns/index.mdx @@ -3,7 +3,7 @@ pcx_content_type: concept title: Agentic patterns description: Implement common AI agent patterns like prompt chaining, routing, parallelization, and orchestrator-workers on Cloudflare. sidebar: - order: 99 + order: 12 head: [] products: - agents diff --git a/src/content/docs/agents/concepts/agentic-patterns/long-running-agents.mdx b/src/content/docs/agents/concepts/agentic-patterns/long-running-agents.mdx index 8e99398d8fc..697455c85ba 100644 --- a/src/content/docs/agents/concepts/agentic-patterns/long-running-agents.mdx +++ b/src/content/docs/agents/concepts/agentic-patterns/long-running-agents.mdx @@ -1,7 +1,7 @@ --- title: Long-running agents pcx_content_type: concept -description: Build agents that persist for days, weeks, or months — surviving restarts, waking on demand, and managing work that spans far longer than any single request. +description: Design agents that persist for days, weeks, or months, surviving restarts, waking on demand, and managing work that spans far longer than any single request. tags: - AI sidebar: @@ -10,698 +10,132 @@ products: - agents --- -Build agents that persist for days, weeks, or months — surviving restarts, waking on demand, and managing work that spans far longer than any single request. +A long-running agent persists for days, weeks, or months. It does not run all that time. It exists all that time, and runs when something happens. The short version: -- Agents are durable identities, not always-on processes. -- State, SQL data, schedules, and fiber checkpoints survive hibernation and restarts. -- In-memory variables, timers, open fetches, and local closures do not survive eviction. -- Use `keepAlive()` for active work measured in minutes, `runFiber()` when work needs recovery, `startFiber()` when callers need durable acceptance and status, and Workflows for heavyweight multi-step jobs. -- Use sub-agents when one parent coordinates many long-lived child contexts. +- An agent is a durable identity, not an always-on process. +- Anything stored in SQLite survives hibernation and restarts. Memory, timers, and open requests do not. +- The Lifecycle's job queue wakes the agent for work that must continue. +- The harness recovers a turn that an eviction cut short. +- Hand heavy multi-step processes to Cloudflare Workflows. -## Why Cloudflare for long-running agents +## Why Durable Objects fit long-running agents -Agents spend most of their time waiting. Waiting for user input (seconds to days), LLM responses (seconds to minutes), tool results (seconds to hours), human approvals (hours to days), or scheduled wake-ups (minutes to months). On a traditional VM or container, you pay for all that idle time. An agent that is 99% dormant and 1% active still costs you 100% of a server. +Agents spend most of their time waiting: for user input, model responses, tool results, approvals, or a scheduled time. On a virtual machine or a container, you pay for all that idle time. -Durable Objects invert this model. An agent exists as an addressable entity with persistent state, but consumes zero compute when hibernated. When something happens — an HTTP request, a WebSocket message, a scheduled alarm, an inbound email — the platform wakes the agent, loads its state from SQLite, and hands it the event. The agent does its work, then goes back to sleep. +A Durable Object consumes no compute while it hibernates. When something happens, such as a request, a WebSocket message, an alarm, or an email, the platform wakes the object, and it loads its state from SQLite. The agent does its work, then goes back to sleep. -This is the [actor model](https://en.wikipedia.org/wiki/Actor_model): each agent has an identity, durable state, and wakes on message. You do not manage servers, routing, health checks, or restart logic. The platform handles placement, scaling, and recovery. +| | Virtual machines or containers | Durable Objects | +| ----------------------------------------- | ---------------------------------- | -------------------------------- | +| Idle cost | Full compute cost, always | None while hibernated | +| Scaling | Provision and manage capacity | Automatic, per agent | +| State | An external database | Built-in SQLite | +| Recovery | Process managers and health checks | The platform restarts the object | +| Identity and routing | Load balancers and sticky sessions | Built in, from name to agent | +| 10,000 agents, each active 1% of the time | 10,000 always-on instances | About 100 active at any moment | -The economics follow directly: - -| | VMs / Containers | Durable Objects | -| --------------------------------------------- | ---------------------------------------------- | --------------------------------- | -| **Idle cost** | Full compute cost, always | Zero (hibernated) | -| **Scaling** | Provision and manage capacity | Automatic, per-agent | -| **State** | External database required | Built-in SQLite | -| **Recovery** | You build it (process managers, health checks) | Platform restarts, state survives | -| **Identity / routing** | You build it (load balancers, sticky sessions) | Built-in (name to agent) | -| **10,000 agents, each active 1% of the time** | 10,000 always-on instances | ~100 active at any moment | - -For agents — which are inherently bursty, stateful, and long-lived — this is a natural fit. - -## The lifecycle of a long-running agent - -A long-running agent is not a process that runs continuously. It is an entity that **exists** continuously but **runs** intermittently. Understanding the lifecycle is key to building agents that work reliably over long timelines. +## The life of a long-running agent ```txt -Wake → onStart() → handle events → idle (~2 min) → hibernation - ▲ │ - └──────────────── alarm or request wakes agent ────────┘ - -Eviction (crash / redeploy) can happen at any point. -State persists in SQLite. Agent restarts on next event. -``` - -### What survives - -- **`this.state`** — persisted to SQLite on every `setState()` call -- **`this.sql` data** — all SQLite tables you create -- **Scheduled tasks** — stored in SQLite, trigger alarms to wake the agent -- **Connection state** — `connection.setState()` data for each WebSocket client -- **Fiber checkpoints and ledgers** — `stash()` data from `runFiber()` and retained `startFiber()` status rows - -Any higher-level abstractions built on SQLite also survive, since they share the same durable storage. - -### What does not survive - -- **In-memory variables** — class fields not stored via `setState()` or `this.sql` -- **Running timers** — `setTimeout`, `setInterval` are lost on hibernation/eviction -- **Open fetch requests** — in-flight HTTP calls are abandoned -- **Local closures** — callbacks and promise chains are lost - -The implication: any work that matters must be persisted or recoverable. The SDK provides primitives for this — schedules, fibers, queues — but understanding the boundary between "in-memory" and "durable" is essential. - -## Running example: a project manager agent - -Throughout this doc, we build up a project manager agent that: - -- Lives for the duration of a project (weeks or months) -- Tracks tasks, assigns work to sub-agents, and reports progress -- Wakes up on schedule to check deadlines and send reminders -- Reacts to external events (webhooks from GitHub, emails from team members) -- Handles long-running operations (CI pipelines, code reviews, deployments) -- Survives any number of restarts and evictions along the way - -```ts -import { Agent } from "agents"; - -type ProjectState = { - name: string; - status: "planning" | "active" | "review" | "complete"; - tasks: Task[]; - plan: Plan | null; -}; - -type Task = { - id: string; - title: string; - status: "pending" | "in_progress" | "blocked" | "complete"; - assignee?: string; - dueDate?: string; - completedAt?: number; - externalJobId?: string; -}; - -export class ProjectManager extends Agent { - initialState: ProjectState = { - name: "", - status: "planning", - tasks: [], - plan: null, - }; -} -``` - -The `Plan` type is introduced in [Planning as a durability strategy](#planning-as-a-durability-strategy). We add capabilities to this agent section by section. - -## Waking up: how agents get activated - -A hibernated agent can be woken by any of these sources: - -| Wake source | How it works | Example | -| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------- | -| **HTTP request** | Any request to the agent's URL triggers `onRequest()` | A webhook from GitHub | -| **WebSocket connection** | A client connects, triggering `onConnect()` | A team member opens the dashboard | -| **RPC call** | Another Worker or agent calls a method via [service binding](/workers/runtime-apis/bindings/service-bindings/) or [`@callable`](/agents/agent-class/callable-methods/) | A coordinator agent delegates a task | -| **Scheduled alarm** | A stored schedule fires, triggering your callback | Daily standup reminder at 9am | -| **Email** | An inbound email triggers `onEmail()` | A team member replies to a status email | - -The pattern extends naturally to any event source that can reach a Worker — anything from telephony webhooks to chat platform bots. An external signal arrives, the platform wakes the agent, and the agent handles it. - -The agent does not need to be "started" or "deployed" separately for each wake source — they all route to the same Durable Object instance. The agent's identity (its name) is the routing key. - -```ts -export class ProjectManager extends Agent { - async onStart() { - // Daily deadline check at 9am UTC — idempotent, safe across restarts - await this.schedule( - "0 9 * * *", - "checkDeadlines", - {}, - { - idempotent: true, - }, - ); - - // Progress sync every 30 minutes - await this.scheduleEvery(1800, "syncProgress"); - } - - async onRequest(request: Request): Promise { - const url = new URL(request.url); - - if (url.pathname.endsWith("/github-webhook")) { - const event = await request.json(); - await this.handleGitHubEvent(event); - return new Response("OK"); - } - - return Response.json({ - project: this.state.name, - status: this.state.status, - }); - } - - async checkDeadlines() { - /* ... find overdue tasks, broadcast alerts ... */ - } - async syncProgress() { - /* ... check on sub-agents, update task statuses ... */ - } -} -``` +Wake → onStart() → handle events → idle → hibernation + ▲ │ + └────────── alarm or request wakes it ───────┘ -## Staying alive during long work - -Sometimes an agent needs to do work that takes longer than the idle eviction window (~70–140 seconds). Streaming an LLM response, orchestrating a multi-step tool chain, or waiting on a slow API all risk the agent being evicted mid-flight. - -`keepAlive()` prevents this by creating a heartbeat that resets the inactivity timer: - -```ts -export class ProjectManager extends Agent { - async generateProjectPlan(goal: string) { - const result = await this.keepAliveWhile(async () => { - const plan = await this.callLLM(`Create a project plan for: ${goal}`); - const tasks = await this.callLLM( - `Break this into tasks: ${JSON.stringify(plan)}`, - ); - return { plan, tasks }; - }); - - this.setState({ - ...this.state, - status: "active", - plan: result.plan, - tasks: result.tasks, - }); - } -} +Eviction (crash or deploy) can happen at any point. +State persists in SQLite. The agent restarts on the next event. ``` -`keepAliveWhile()` is the recommended approach — it guarantees the heartbeat is cleaned up when the work finishes (or throws). For manual control, `keepAlive()` returns a disposer: +What survives: -```ts -const dispose = await this.keepAlive(); -try { - await longWork(); -} finally { - dispose(); -} -``` +- Every table in the object's SQLite database, including the harness transcript and capability tables. +- Jobs in the Lifecycle's job queue, and the alarm that runs them. +- Per-connection WebSocket state. +- Files on the agent's [workspace](/agents/concepts/workspace/). -### When keepAlive is not enough +What does not survive: -`keepAlive` is for work measured in minutes, not hours. For truly long-running operations, use a different strategy: +- Class fields that are not stored. +- Timers, such as `setTimeout()`. +- In-flight `fetch()` requests and streams. +- Closures and promise chains. -| Duration | Strategy | -| ---------------- | ------------------------------------------------------- | -| Seconds | Normal request handling | -| Minutes | `keepAlive()` / `keepAliveWhile()` | -| Minutes | `startFiber()` when retryable acceptance matters | -| Minutes to hours | [Workflows](/agents/agent-class/run-workflows/) | -| Hours to days | Async pattern: start job, hibernate, wake on completion | +Any work that matters must be stored or recoverable. For the mechanisms, refer to [Durable agents](/agents/concepts/durable-agents/). -## Surviving crashes: fibers and recovery +## Wake on events -An agent can be evicted at any time — a deploy, a platform restart, or hitting resource limits. If the agent was mid-task, that work is lost unless it was checkpointed. +A long-running agent wakes for: -[`runFiber()`](/agents/agent-class/durable-execution/) provides crash-recoverable execution. It persists a row in SQLite for the duration of the work, and lets you `stash()` intermediate state. If the agent is evicted, the fiber row survives, and `onFiberRecovered()` is called on the next activation. +- **A schedule.** The [Scheduler](/agents/runtime/capabilities/scheduler/) wakes it after a delay, at a time, or on a cron expression, such as a daily status report. +- **A request.** A webhook, an HTTP call, or an RPC call from another Worker. +- **A message.** A WebSocket message, a chat message, or an email. +- **Its own work.** A harness or capability that pushed a job to the queue. -Use [`startFiber()`](/agents/agent-class/durable-execution/#startfiber) when the important boundary is durable acceptance. It adds an idempotency key, retained status records, inspection, cancellation, and cleanup on top of the same fiber machinery. By default it returns after acceptance. Pass `waitForCompletion: true` when the request should stay open until the accepted job reaches a terminal status. This is a good fit for webhooks where the provider may retry delivery and the agent must avoid starting duplicate visible side effects. +## Wait for slow work -```ts -export class ProjectManager extends Agent { - async executeTask(task: Task) { - await this.runFiber(`task:${task.id}`, async (ctx) => { - const resources = await this.gatherResources(task); - ctx.stash({ phase: "prepared", resources, task }); +Some work outlasts a single activation, such as a CI run that takes 20 minutes. Do not hold the agent in memory while it waits: - const result = await this.runSubAgent(task, resources); - ctx.stash({ phase: "executed", result, task }); +- **Webhook callback.** Start the work, store its ID, and let the agent hibernate. The external service calls the agent back when it finishes. +- **Polling.** Schedule a check every few minutes. Each check reads the status, stores it, and schedules the next check until the work finishes. +- **Workflow.** Start a Workflow for the slow work, and let it call the agent back with the result. - await this.updateTaskStatus(task.id, "complete", result); - }); - } - - async onFiberRecovered(ctx: FiberRecoveryContext) { - if (!ctx.name.startsWith("task:")) return; - const { phase, task } = ctx.snapshot as { phase: string; task: Task }; - - if (phase === "prepared") { - await this.executeTask(task); - } else if (phase === "executed") { - await this.updateTaskStatus( - task.id, - "complete", - (ctx.snapshot as { result: unknown }).result, - ); - } - } -} -``` +## Reconstruct context after a long wait -The pattern is: **checkpoint before expensive work, recover from the last checkpoint.** This is not automatic replay — you decide what recovery means for your domain. +When the result arrives, the model's original reasoning is gone from memory. Three approaches restore it: -:::note[Testing recovery locally] +- **Replay the transcript.** The harness stores the conversation. Submit the result as new input, and the harness sends the whole history to the model. In the Pi harness, label the input with your own entry kind, such as `app.ci_result`, so the transcript shows where it came from. +- **Store a continuation note.** Before the wait, store a short note of what the agent was doing, and what to do with the result. On wake, build a focused prompt from the note. +- **Use the plan.** If the agent keeps a structured plan in its database, the plan says where it is: "step 3 of 7, the CI run finished." This is the most robust approach. -In `wrangler dev`, fiber recovery works identically to production. Kill the wrangler process (Ctrl-C or SIGKILL), restart it, and recovery fires automatically. SQLite and alarm state persist to disk between restarts. +## Plan as a durability strategy -::: - -For the full API reference — `FiberContext`, `FiberRecoveryContext`, concurrent fibers, inline vs fire-and-forget patterns — refer to [Durable Execution](/agents/agent-class/durable-execution/). - -## Handling long async operations - -The project manager frequently kicks off work that takes far longer than any single activation — a CI pipeline runs for 20 minutes, a design review takes a day, a video asset takes hours to generate. The agent should not stay alive for any of this. Instead, it starts the work, persists the job ID in state, and hibernates. When the result arrives — via a callback, a poll, or a workflow completion — the agent wakes, correlates the result, and moves on. - -### Pattern: webhook callback - -The project manager starts a CI pipeline for a task. The pipeline takes 20 minutes. Rather than holding a connection open, the agent registers its own URL as the callback and goes to sleep: - -```ts -export class ProjectManager extends Agent { - async startCIPipeline(task: Task) { - const response = await fetch("https://ci.example.com/api/pipelines", { - method: "POST", - body: JSON.stringify({ - repo: "org/project", - branch: "main", - callback_url: `${this.url}/ci-callback?taskId=${task.id}`, - }), - }); - - const { pipelineId } = await response.json(); - this.updateTask(task.id, { - status: "in_progress", - externalJobId: pipelineId, - }); - } - - async onRequest(request: Request): Promise { - const url = new URL(request.url); - if (url.pathname.endsWith("/ci-callback")) { - const taskId = url.searchParams.get("taskId"); - const result = await request.json(); - this.updateTask(taskId, { - status: result.status === "success" ? "complete" : "blocked", - }); - return new Response("OK"); - } - // ... other routes - } -} -``` - -### Pattern: polling with schedule - -Not every external service supports callbacks. When the project manager submits a video asset for generation, it needs to check back periodically until the job completes: - -```ts -export class ProjectManager extends Agent { - async startVideoGeneration(task: Task) { - const response = await fetch("https://video-api.example.com/generate", { - method: "POST", - body: JSON.stringify({ prompt: task.title }), - }); - const { jobId } = await response.json(); - this.updateTask(task.id, { status: "in_progress", externalJobId: jobId }); - await this.schedule(60, "pollExternalJob", { - taskId: task.id, - jobId, - attempt: 1, - }); - } - - async pollExternalJob(payload: { - taskId: string; - jobId: string; - attempt: number; - }) { - const response = await fetch( - `https://video-api.example.com/status/${payload.jobId}`, - ); - const status = await response.json(); - - if (status.state === "complete" || status.state === "failed") { - this.updateTask(payload.taskId, { - status: status.state === "complete" ? "complete" : "blocked", - }); - return; - } - - const nextDelay = Math.min(60 * payload.attempt, 600); - await this.schedule(nextDelay, "pollExternalJob", { - ...payload, - attempt: payload.attempt + 1, - }); - } -} -``` - -### Pattern: workflow delegation - -A production deployment involves multiple steps that must each retry independently — build, test, stage, promote. The project manager should not manage these steps internally; it delegates to a [Workflow](/agents/agent-class/run-workflows/) that handles retries and step sequencing: - -```ts -export class ProjectManager extends Agent { - async startDeployment(task: Task) { - const instanceId = await this.runWorkflow("DEPLOY_WORKFLOW", { - taskId: task.id, - environment: "production", - }); - this.updateTask(task.id, { - status: "in_progress", - externalJobId: instanceId, - }); - } - - async onWorkflowComplete( - workflowName: string, - instanceId: string, - result?: unknown, - ) { - const task = this.state.tasks.find((t) => t.externalJobId === instanceId); - if (task) this.updateTask(task.id, { status: "complete" }); - } -} -``` +A structured plan is both progress for users and a recovery mechanism. Store the plan as rows, one per step, with a status. After any interruption, the agent reads the plan, finds the first unfinished step, and continues. The plan also gives the model a compact context, so it does not need the full history. -## Reconstructing context after a long wait - -The CI pipeline finishes 20 minutes later. The webhook wakes the project manager. The task status is updated. But now what? If the agent was using an LLM to orchestrate work — deciding which task to run next, drafting a status report, reasoning about blockers — it needs to pick up that reasoning thread. The original prompt, the in-flight tool call, the chain of thought — all gone from memory. - -This is the fundamental challenge of long-running AI agents. Most frameworks assume tool calls complete within the LLM's timeout and do not address this directly. - -Three approaches work today: - -**Replay the full conversation history.** `AIChatAgent` persists all messages in SQLite. When the result arrives, append it to the history and re-invoke the LLM. This is the simplest approach but re-processes the entire context window. - -**Stash a continuation summary.** Before hibernating, persist a compact description of what the agent was doing and what to do with the result: - -```ts -ctx.stash({ - task: "Waiting for CI results", - onSuccess: "Mark task complete, move to next step in plan", - onFailure: "Notify team, schedule retry in 1 hour", - relevantContext: { taskId, planStep: 3 }, -}); -``` - -On recovery, use the stash to construct a focused prompt rather than replaying everything. - -**Use the plan as context.** If the agent has a structured plan, the plan itself provides sufficient context: "I am on step 3 of 7, the step was 'run CI pipeline', the result just arrived." This is the most robust approach for long-running agents — the plan is both a recovery mechanism and a context reconstruction strategy. Refer to the next section. - -## Planning as a durability strategy - -A structured plan is not just useful for showing progress to users — it is a durability mechanism. An agent with a plan can recover from any interruption by looking at where it left off. - -```ts -type Plan = { - goal: string; - steps: PlanStep[]; - currentStep: number; - createdAt: string; - updatedAt: string; -}; - -type PlanStep = { - id: string; - description: string; - status: "pending" | "in_progress" | "complete" | "failed" | "skipped"; - result?: unknown; -}; - -export class ProjectManager extends Agent { - async createPlan(goal: string) { - const steps = await this.keepAliveWhile(async () => { - return this.callLLM(` - Break down this project goal into concrete steps. - Return a JSON array of { id, description } objects. - Goal: ${goal} - `); - }); - - this.setState({ - ...this.state, - plan: { - goal, - steps: steps.map((s: { id: string; description: string }) => ({ - ...s, - status: "pending" as const, - })), - currentStep: 0, - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - }, - }); - - await this.schedule(0, "executeNextStep"); - } - - async executeNextStep() { - const { plan } = this.state; - if (!plan || plan.currentStep >= plan.steps.length) { - this.setState({ ...this.state, status: "complete" }); - return; - } - - const step = plan.steps[plan.currentStep]; - - try { - const result = await this.keepAliveWhile(() => this.executeStep(step)); - - const updatedSteps = plan.steps.map((s) => - s.id === step.id ? { ...s, status: "complete" as const, result } : s, - ); - this.setState({ - ...this.state, - plan: { - ...plan, - steps: updatedSteps, - currentStep: plan.currentStep + 1, - updatedAt: new Date().toISOString(), - }, - }); - - await this.schedule(0, "executeNextStep"); - } catch (error) { - const updatedSteps = plan.steps.map((s) => - s.id === step.id ? { ...s, status: "failed" as const } : s, - ); - this.setState({ - ...this.state, - plan: { - ...plan, - steps: updatedSteps, - updatedAt: new Date().toISOString(), - }, - }); - } - } -} -``` - -This pattern has several advantages for long-running agents: - -- **Recovery is trivial** — on restart, check `plan.currentStep` and resume -- **Progress is visible** — clients see which steps are done and what is next -- **Re-planning is possible** — if a step fails or requirements change, the agent can revise the remaining steps without losing completed work -- **Human oversight** — the plan is a natural approval checkpoint ("here is what I am going to do — proceed?") -- **Context reconstruction** — the plan tells the LLM where it is, what happened, and what to do next, without replaying the full conversation - -## Delegating to sub-agents - -A project manager does not do everything itself. It delegates specialized work to sub-agents — each with their own identity, state, and lifecycle. - -```ts -export class ProjectManager extends Agent { - async delegateTask(task: Task) { - const researcher = await this.subAgent( - ResearchAgent, - `research-${task.id}`, - ); - - const findings = await researcher.research(task.title); - - this.updateTask(task.id, { status: "complete" }); - return findings; - } -} -``` - -Sub-agents have their own state, schedules, durable fibers, and lifecycle. They are colocated under the parent, but each child stores its own SQLite data and runs callbacks with the child as `this`. - -Because facets do not have independent alarm slots, the top-level parent owns the physical Durable Object alarm. The Agents SDK records which sub-agent owns each schedule or fiber recovery lease, wakes the parent, and routes the callback back into the child. The parent does not need to stay active while the sub-agent works — it can start the work, hibernate, and be woken by the child-owned schedule or recovery check. - -For the full `subAgent()` API — typed RPC stubs, client routing, access control, storage isolation, and alarm-backed APIs — refer to [Sub-agents](/agents/agent-class/sub-agents/). For AI-specific sub-agent streaming (running full LLM turns through a child agent), refer to [Think: Sub-agent RPC](/agents/harnesses/think/sub-agents/). ## Recovering interrupted LLM streams -The patterns above handle the project manager's coordination work — scheduling, delegating, polling. But the project manager also uses an LLM directly: generating plans, summarizing progress, drafting status emails. Those LLM calls stream tokens over a connection that cannot be resumed if the agent is evicted mid-response. - -For chat-oriented agents built on `AIChatAgent` or `Think`, this is an even sharper problem — the user watches the response stream in real time and sees it stop mid-sentence. Durable recovery wraps every chat turn in a `runFiber`. This provides automatic `keepAlive` during streaming and a recovery hook when the agent restarts: - -```ts -import { AIChatAgent } from "@cloudflare/ai-chat"; -import type { - ChatRecoveryContext, - ChatRecoveryOptions, -} from "@cloudflare/ai-chat"; - -class ProjectChat extends AIChatAgent { - override async onChatRecovery( - ctx: ChatRecoveryContext, - ): Promise { - // ctx.partialText — text generated before eviction - // ctx.recoveryData — whatever you stashed via this.stash() - // ctx.messages — full conversation history - // ctx.createdAt — when the interrupted turn started - return {}; - } -} -``` +A model response streams over a connection. An eviction in the middle of a response cuts the stream, and the user sees the response stop mid-sentence. -The right recovery strategy depends on the LLM provider: - -| Provider | Strategy | How it works | Token cost | -| ---------------------- | ----------------------------------- | ----------------------------------------------------------------------------- | ---------- | -| Workers AI | Continue from partial | `continueLastTurn()` — model continues via assistant prefill | Low | -| OpenAI (Responses API) | Retrieve completed response | Stash `responseId` during streaming, retrieve on recovery | Zero | -| Anthropic | Synthetic continuation | Persist partial, send a synthetic user message asking the model to continue | Medium | -| Other | Try prefill, fall back to synthetic | `continueLastTurn()` if the provider supports it, synthetic message otherwise | Varies | - -Use `ctx.createdAt` to suppress stale recoveries. For example, if a recovered chat turn is older than a few minutes, you may persist the partial answer but skip automatic continuation to avoid surprising the user with an old response. - -`AIChatAgent` and [`Think`](/agents/harnesses/think/) always use durable recovery. The default path persists partial output and continues or retries the turn when safe. Override `onChatRecovery` when a provider has a better recovery strategy. Configure `chatRecovery = { maxAttempts, terminalMessage, onExhausted }` to tune the terminal experience. - -If the agent is interrupted before any assistant stream chunks are written, there is no partial assistant message to continue. When the latest persisted message is still the unanswered user message from that turn, chat recovery retries the turn automatically unless `onChatRecovery` returns `{ continue: false }`. - -## Managing state over time - -An agent that runs for months accumulates data: conversation history, timeline events, completed tasks, schedule records. Without management, this grows unbounded. - -### Housekeeping - -Schedule periodic cleanup to prune old data and archive completed work: - -```ts -export class ProjectManager extends Agent { - async onStart() { - await this.schedule("0 0 * * *", "housekeeping", {}, { idempotent: true }); - } - - async housekeeping() { - const cutoff = Date.now() - 30 * 24 * 60 * 60 * 1000; - const toArchive = this.state.tasks.filter( - (t) => t.status === "complete" && (t.completedAt ?? 0) < cutoff, - ); - for (const task of toArchive) { - this - .sql`INSERT INTO archived_tasks (id, data) VALUES (${task.id}, ${JSON.stringify(task)})`; - } - this.setState({ - ...this.state, - tasks: this.state.tasks.filter( - (t) => !toArchive.some((a) => a.id === t.id), - ), - }); - - this.deleteWorkflows({ - status: ["complete", "errored"], - createdBefore: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), - }); - } -} -``` +The harness recovers the turn: + +- The [Pi harness](/agents/harnesses/pi/) stores what Pi committed, and a job wakes the object after an eviction. Pi then resumes the session's work from its stored state. +- [Think](/agents/harnesses/think/recovery/) and `AIChatAgent` store the partial output, then continue or retry the turn when the agent restarts. -### Conversation history management +The best recovery depends on the model provider. Some providers can continue from the partial text. Others need the partial answer stored, and a new request that asks the model to continue. For a turn that started long ago, store the partial answer, but skip the automatic continuation, so the user is not surprised by an old response. -For agents that use `AIChatAgent`, conversation history can grow large over extended lifespans. Without management, a 3-month conversation will exhaust the LLM's context window long before the project ends. +## Manage data over time -Strategies for managing conversation size: +An agent that runs for months accumulates data: transcripts, completed tasks, and logs. -- **Sliding window** — keep only the last N messages in the active context. Simple and predictable. -- **Summarization** — periodically summarize older messages and replace them with a compact summary. Original messages can remain in SQLite for audit. -- **Selective retention** — retain messages that contain decisions, approvals, and key context while pruning routine exchanges. +- **Housekeeping.** Schedule a daily job that archives completed work and deletes old rows. +- **Transcript size.** Compact older messages into a summary, so the prompt fits in the model's context window. Keep the original messages in storage for audit. +- **End of life.** When the agent's purpose is complete, cancel its schedules, archive what you need to R2 or D1, and delete its storage. An agent that might be needed again can just stay idle, at no cost. -## End of life +## When to use Workflows vs agent-internal patterns -A long-running agent eventually completes its purpose. The project ships, the investigation concludes, the monitoring window closes. Clean up explicitly: +| | Inside the agent | Workflows | +| -------------- | ----------------------------------------------------- | ------------------------------------ | +| Best for | The agent's own rhythm: deadlines, reminders, syncing | Independent multi-step pipelines | +| Durability | SQLite and the job queue | The Workflows engine | +| Retries | Job retries, and retries in your code | Per-step retries with backoff | +| Human approval | Store the pending action, and wait for an answer | A step that waits for an event | +| Complexity | Lower: everything is in the agent | Higher: a separate class and binding | -```ts -export class ProjectManager extends Agent { - async completeProject() { - const schedules = await this.listSchedules(); - for (const schedule of schedules) { - await this.cancelSchedule(schedule.id); - } +A pragmatic rule: if the work is the agent managing itself, such as checking deadlines or sending reminders, use schedules and the job queue. If the work is a pipeline that could fail and retry on its own, such as a deployment or a report, use a [Workflow](/agents/concepts/workflows/). - this.setState({ ...this.state, status: "complete" }); +## On the `Agent` class - // All SQLite data, schedules, and state are permanently deleted - await this.destroy(); - } -} -``` +The `Agent` class has its own APIs for long-running work: -`this.destroy()` is permanent. If you may need the agent's data later, archive it to an external store (R2, D1, or an API call) before destroying. For agents that might be reactivated, simply mark them as complete and let them hibernate — they cost nothing when idle. +| API | Purpose | +| ------------------------------------ | ------------------------------------------- | +| `setState()` and `this.sql` | Store state across activations | +| `schedule()` and `scheduleEvery()` | Wake the agent at future times | +| `keepAlive()` and `keepAliveWhile()` | Keep the agent in memory during active work | +| `runFiber()` and `stash()` | Checkpoint and recover long tasks | +| `startFiber()` | Accept, inspect, and cancel durable jobs | +| `runWorkflow()` | Start a Workflow and track it | +| `destroy()` | Delete the agent and all its data | -## When to use Workflows vs agent-internal patterns +For more information, refer to [Durable execution on the Agent class](/agents/agent-class/durable-execution/), [Schedule tasks](/agents/agent-class/schedule-tasks/), and [Run Workflows](/agents/agent-class/run-workflows/). -Both Workflows and agent-internal primitives (schedules, fibers, queues) support long-running work. The right choice depends on the nature of the work: - -| | Agent-internal | Workflows | -| ------------------ | ------------------------------------------------------ | ---------------------------------------- | -| **Best for** | Agent-centric work: scheduling, polling, state updates | Independent multi-step pipelines | -| **Durability** | SQLite (survives eviction) | Workflow engine (survives everything) | -| **Retries** | `this.retry()`, schedule-level retries | Per-step retries with backoff | -| **Max duration** | Minutes per activation (with `keepAlive`) | 30 minutes per step, unlimited steps | -| **Human approval** | Build it yourself (state + WebSocket) | Built-in `waitForApproval()` | -| **Complexity** | Lower — everything is in the agent | Higher — separate class, wrangler config | - -A pragmatic rule: if the work is about the agent managing its own lifecycle (checking deadlines, syncing state, sending reminders), use schedules and fibers. If the work is a discrete pipeline that could fail and retry independently (deploy, data processing, report generation), use a Workflow. - -The project manager agent uses both: schedules for its own rhythms (daily standups, progress syncs), and Workflows for heavyweight operations (deployments, CI pipelines). - -## Summary - -Long-running agents on Cloudflare are not long-running processes. They are durable entities that wake, work, and sleep — potentially over weeks or months. The key primitives: - -| Primitive | Purpose | -| -------------------------------------- | -------------------------------------------- | -| **`setState()` / `this.sql`** | Persist state across activations | -| **`schedule()` / `scheduleEvery()`** | Wake the agent at future times | -| **`keepAlive()` / `keepAliveWhile()`** | Prevent eviction during active work | -| **`runFiber()` / `stash()`** | Checkpoint and recover long tasks | -| **`startFiber()`** | Durably accept, inspect, and cancel jobs | -| **`chatRecovery`** | Recover interrupted LLM streams | -| **`onRequest()` / `onEmail()` / RPC** | Wake on external events | -| **`runWorkflow()`** | Delegate heavyweight multi-step work | -| **`subAgent()`** | Delegate specialized work to child agents | -| **Structured plans in state** | Enable recovery, visibility, and re-planning | - -For the project manager agent, these compose into an agent that: - -1. **Plans** — breaks goals into steps, persists the plan in state -2. **Executes** — runs steps one at a time, hibernating between them -3. **Reacts** — wakes on webhooks, emails, and schedules -4. **Recovers** — resumes from the last checkpoint after any interruption -5. **Delegates** — hands off work to sub-agents and Workflows -6. **Maintains** — prunes old data, archives completed work, manages its own lifecycle -7. **Ends** — cleans up and destroys itself when the project is done - -The agent does not need to run continuously to do any of this. It just needs to exist. - -## Related - -- [Durable Execution](/agents/agent-class/durable-execution/) — `runFiber()`, `startFiber()`, `stash()`, and crash recovery -- [Schedule tasks](/agents/agent-class/schedule-tasks/) — delayed, cron, and interval tasks -- [Retries](/agents/agent-class/retries/) — retry options and patterns -- [Workflows](/agents/agent-class/run-workflows/) — durable multi-step processing -- [Store and sync state](/agents/agent-class/state/) — `setState()` and persistence -- [WebSockets](/agents/agent-class/websockets/) — lifecycle hooks and hibernation -- [Callable methods](/agents/agent-class/callable-methods/) — RPC via `@callable` and service bindings -- [Email routing](/agents/agent-class/communication-channels/email/) — receiving inbound email -- [Webhooks](/agents/agent-class/communication-channels/webhooks/) — receiving external events -- [Human in the loop](/agents/concepts/agentic-patterns/human-in-the-loop/) — approval flows +For `Agent` class examples of these patterns, refer to [Scheduler](/agents/runtime/capabilities/scheduler/) for polling, recurring work, and housekeeping, [State](/agents/runtime/capabilities/state/) for a plan in state, [Webhooks](/agents/agent-class/communication-channels/webhooks/) for callbacks, [Durable execution on the Agent class](/agents/agent-class/durable-execution/) for continuation notes, and [Run Workflows](/agents/agent-class/run-workflows/) for delegating to a Workflow. diff --git a/src/content/docs/agents/concepts/calling-llms.mdx b/src/content/docs/agents/concepts/calling-llms.mdx deleted file mode 100644 index c44b532585b..00000000000 --- a/src/content/docs/agents/concepts/calling-llms.mdx +++ /dev/null @@ -1,225 +0,0 @@ ---- -title: Calling LLMs -description: Call large language models from within a stateful Cloudflare Agent with persistent context and autonomous scheduling. -pcx_content_type: concept -tags: - - AI -sidebar: - order: 6 -products: - - agents ---- - -import { TypeScriptExample, LinkCard } from "~/components"; - -Agents change how you work with LLMs. In a stateless Worker, every request starts from scratch — you reconstruct context, call a model, return the response, and forget everything. An Agent keeps state between calls, stays connected to clients over WebSocket, and can call models on its own schedule without a user present. - -This page covers the patterns that become possible when your LLM calls happen inside a stateful Agent. For provider setup and code examples, refer to [Using AI Models](/agents/agent-class/using-ai-models/). - -## State as context - -Every Agent has a built-in [SQL database](/agents/agent-class/state/) and key-value state. Instead of passing an entire conversation history from the client on every request, the Agent stores it and builds prompts from its own storage. - - - -```ts -import { Agent } from "agents"; - -export class ResearchAgent extends Agent { - async buildPrompt(userMessage: string) { - const history = this.sql<{ role: string; content: string }>` - SELECT role, content FROM messages - ORDER BY timestamp DESC LIMIT 50`; - - const preferences = this.sql<{ key: string; value: string }>` - SELECT key, value FROM user_preferences`; - - return [ - { role: "system", content: this.systemPrompt(preferences) }, - ...history.reverse(), - { role: "user", content: userMessage }, - ]; - } -} -``` - - - -This means the client does not need to send the full conversation on every message. The Agent owns the history, can prune it, enrich it with retrieved documents, or summarize older turns before sending to the model. - -## Surviving disconnections - -Reasoning models like DeepSeek R1 or GLM-4 can take 30 seconds to several minutes to respond. In a stateless request-response architecture, the client must stay connected the entire time. If the connection drops, the response is lost. - -An Agent keeps running after the client disconnects. When the response arrives, the Agent can persist it to state and deliver it when the client reconnects — even hours or days later. - - - -```ts -import { Agent } from "agents"; -import { streamText } from "ai"; -import { createAI } from "agents/models/ai-sdk"; - -export class MyAgent extends Agent { - async onMessage(connection: Connection, message: WSMessage) { - const { prompt } = JSON.parse(message as string); - const ai = createAI({ binding: this.env.AI }); - - const result = streamText({ - model: ai("@cf/zai-org/glm-4.7-flash"), - prompt, - }); - - for await (const chunk of result.textStream) { - connection.send(JSON.stringify({ type: "chunk", content: chunk })); - } - - this.sql`INSERT INTO responses (prompt, response, timestamp) - VALUES (${prompt}, ${await result.text}, ${Date.now()})`; - } -} -``` - - - -With [`AIChatAgent`](/agents/agent-class/communication-channels/chat/chat-agents/), this is handled automatically — messages are persisted to SQLite and streams resume on reconnect. - -## Autonomous model calls - -Agents do not need a user request to call a model. You can schedule model calls to run in the background — for nightly summarization, periodic classification, monitoring, or any task that should happen without human interaction. - - - -```ts -import { Agent } from "agents"; - -export class DigestAgent extends Agent { - async onStart() { - this.schedule("0 8 * * *", "generateDailyDigest", {}); - } - - async generateDailyDigest() { - const articles = this.sql<{ title: string; body: string }>` - SELECT title, body FROM articles - WHERE created_at > datetime('now', '-1 day')`; - - const ai = createAI({ binding: this.env.AI }); - const { text } = await generateText({ - model: ai("@cf/zai-org/glm-4.7-flash"), - prompt: `Summarize these articles:\n${articles.map((a) => a.title + ": " + a.body).join("\n\n")}`, - }); - - this.sql`INSERT INTO digests (summary, created_at) - VALUES (${text}, ${Date.now()})`; - - this.broadcast(JSON.stringify({ type: "digest", summary: text })); - } -} -``` - - - -## Multi-model pipelines - -Because an Agent maintains state across calls, you can chain multiple models in a single method — using a fast model for classification, a reasoning model for planning, and an embedding model for retrieval — without losing context between steps. - - - -```ts -import { Agent } from "agents"; -import { generateText, embed } from "ai"; -import { createAI } from "agents/models/ai-sdk"; - -export class TriageAgent extends Agent { - async triage(ticket: string) { - const ai = createAI({ binding: this.env.AI }); - - const { text: category } = await generateText({ - model: ai("@cf/zai-org/glm-4.7-flash"), - prompt: `Classify this support ticket into one of: billing, technical, account. Ticket: ${ticket}`, - }); - - const { embedding } = await embed({ - model: ai.embedding("@cf/baai/bge-base-en-v1.5"), - value: ticket, - }); - const similar = await this.env.VECTOR_DB.query(embedding, { topK: 5 }); - - const { text: response } = await generateText({ - model: ai("@cf/zai-org/glm-4.7-flash"), - prompt: `Draft a response for this ${category} ticket. Similar resolved tickets: ${JSON.stringify(similar)}. Ticket: ${ticket}`, - }); - - this.sql`INSERT INTO tickets (content, category, response, created_at) - VALUES (${ticket}, ${category}, ${response}, ${Date.now()})`; - - return { category, response }; - } -} -``` - - - -Each intermediate result stays in the Agent's memory for the duration of the method, and the final result is persisted to SQL for future reference. - -## Caching and cost control - -Persistent storage means you can cache model responses and avoid redundant calls. This is especially useful for expensive operations like embeddings or long reasoning chains. - - - -```ts -import { Agent } from "agents"; - -export class CachingAgent extends Agent { - async cachedGenerate(prompt: string) { - const cached = this.sql<{ response: string }>` - SELECT response FROM llm_cache WHERE prompt = ${prompt}`; - - if (cached.length > 0) { - return cached[0].response; - } - - const ai = createAI({ binding: this.env.AI }); - const { text } = await generateText({ - model: ai("@cf/zai-org/glm-4.7-flash"), - prompt, - }); - - this.sql`INSERT INTO llm_cache (prompt, response, created_at) - VALUES (${prompt}, ${text}, ${Date.now()})`; - - return text; - } -} -``` - - - -For provider-level caching and rate limit management across multiple agents, use [AI Gateway](/ai-gateway/). - -## Next steps - - - - - - - - diff --git a/src/content/docs/agents/concepts/channels.mdx b/src/content/docs/agents/concepts/channels.mdx new file mode 100644 index 00000000000..1fe76eb8e2f --- /dev/null +++ b/src/content/docs/agents/concepts/channels.mdx @@ -0,0 +1,80 @@ +--- +title: Channels +description: A channel is how people and systems reach an agent, such as a browser over WebSockets, HTTP, chat, email, or webhooks. +pcx_content_type: concept +sidebar: + order: 9 +products: + - agents +--- + +import { Aside, LinkCard } from "~/components"; + +A channel is how people and systems reach an agent. A person might chat with an agent in a browser, send it an email, or message it from a chat app. A system might call it from a webhook or from another Worker. + +The harness does not depend on the channel. The same agent can serve several channels, and keep one memory across all of them. + +## What every channel does + +Whatever the interface, a channel does the same four jobs: + +- **Routes** each inbound event to the right agent instance, by name. +- **Identifies** the sender, so the agent knows who is asking. +- **Submits** the input to the harness as a new turn, or as an answer to a turn that is waiting. +- **Delivers** the response back to the sender, as a stream or as one message. + +The agent instance is the authorization boundary. Anyone a channel routes to an instance can act on every conversation in it. Authenticate the sender before you route the event, for example in the Worker that receives it. + +## Reach any agent + +These channels work on any Durable Object with the Lifecycle, with any harness: + +| Channel | How it works | +| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| WebSockets | The [`WebSockets`](/agents/runtime/capabilities/websockets/) capability accepts connections. The [client SDK](/agents/agent-class/communication-channels/chat/client-sdk/) connects from React with `useAgent`, or from any JavaScript runtime with `AgentClient`. Connections stay open while the agent hibernates. | +| HTTP | `routeAgentRequest()` routes a request to the agent named in the URL. The agent answers in its `onRequest()` hook. | +| Workers RPC | Another Worker gets the agent by name with `getByName()`, and calls its methods directly. | + +A webhook is an HTTP request. A scheduled job is a channel too: the agent starts a turn itself, with no user connected. + +## Channels on Think and the `Agent` class + +Think and the `Agent` class add channels of their own: + +- [Think channels](/agents/harnesses/think/channels/) set a policy per channel, such as which tools a channel may use. [Think messengers](/agents/harnesses/think/messengers/) receive and reply to messages from chat apps. +- On the `Agent` class, [`AIChatAgent`](/agents/agent-class/communication-channels/chat/) serves a chat UI, and [email](/agents/agent-class/communication-channels/email/), [voice](/agents/agent-class/communication-channels/voice/), and [webhooks](/agents/agent-class/communication-channels/webhooks/) each have their own APIs. + +## One agent, many channels + + + +`agents/experimental/channels` is a capability that serves a harness through several channels at once, such as the web, Slack, Telegram, and email. It works with any harness that implements the SDK's shared harness interface. Each harness session becomes one conversation, which can appear on several surfaces, such as a web page and a Slack thread. + +A gateway in the Worker is the trust boundary. It decides who sent each event, then routes the event to the agent instance. For a working app, refer to the [Channels example](https://github.com/cloudflare/agents/tree/main/examples/next/channels). + +## Approvals and questions + +Some turns stop to wait for a person, such as a tool call that needs approval. The channel shows the question, and sends the answer back to the harness. The turn then continues where it stopped. For more information, refer to [Human-in-the-loop](/agents/concepts/agentic-patterns/human-in-the-loop/). + +## Related resources + + + + + + diff --git a/src/content/docs/agents/concepts/conversation-state-and-memory.mdx b/src/content/docs/agents/concepts/conversation-state-and-memory.mdx deleted file mode 100644 index 7c4c0220643..00000000000 --- a/src/content/docs/agents/concepts/conversation-state-and-memory.mdx +++ /dev/null @@ -1,572 +0,0 @@ ---- -title: Conversation state and memory -pcx_content_type: concept -description: How agents store and recall information, including read-only context, writable short-form memory, searchable knowledge, and on-demand skills. -tags: - - AI -sidebar: - order: 4 -products: - - agents ---- - -import { TypeScriptExample, LinkCard, WranglerConfig } from "~/components"; - -Agents need memory to be useful over time. Without it, every conversation starts from zero. The agent forgets who the user is, what it learned, and what it was doing. Memory is what turns a stateless LLM call into a persistent, context-aware agent. - -The [Session API](/agents/runtime/lifecycle/sessions/) provides the memory layer for agents built on the Cloudflare Agents SDK. It manages two kinds of memory: **conversation history** (the messages and tool calls that make up a session) and **context memory** (persistent blocks injected into the system prompt that the agent can read, write, search, and load). - -Use this page when you need more than simple synced state or flat chat history. For small UI state, use [Store and sync state](/agents/agent-class/state/). For basic chat persistence, `AIChatAgent` stores messages for you. For opinionated long-term memory, Think builds on Session and context blocks. - -:::caution[Experimental] - -The Session memory APIs currently use `agents/experimental/memory/session`. The concepts are stable, but import paths and details may change before graduation. - -::: - -## Conversation history - -The most fundamental type of memory is the conversation itself: the messages between the user and the agent, the tool calls the agent made, and the results it received. The Session stores all of this in a tree-structured message history backed by a Session Provider, defaulting to SQLite. - - - -```ts -import { Session } from "agents/experimental/memory/session"; - -// Append messages as the conversation progresses -await session.appendMessage({ - id: `user-${crypto.randomUUID()}`, - role: "user", - parts: [{ type: "text", text: "What's the status of the deployment?" }], -}); - -// Read the full conversation history -const history = await session.getHistory(); -``` - - - -Conversation history persists across Durable Object hibernation and eviction. When the agent wakes up, the full history is available in SQLite. It does not need to be replayed or reconstructed. - -Messages are stored in a tree structure via `parent_id`, which enables branching conversations. When you `appendMessage` with a `parentId` that already has children, you create a branch, useful for features like response regeneration. `getHistory(leafId)` walks any chosen path through the tree. - -The Session also provides full-text search across the conversation history: - - - -```ts -const results = await session.search("deployment Friday", { limit: 10 }); -``` - - - -As conversations grow long, [compaction](#compaction) summarizes older messages to keep the context window manageable without losing the underlying data. - -## Context memory - -Context memory is persistent information injected into the system prompt, separate from the conversation history. It gives the agent access to identity, instructions, learned facts, knowledge bases, and reference material across every turn. - -The Session API supports four types of context memory, each suited to different kinds of information. The type is determined by the **provider** backing the context block. The Session detects the provider's capabilities automatically. - -### Read-only context - -This is your traditional system prompt: the agent's identity, personality, and instructions. You might write it directly in your codebase, load it from a `SOUL.md` file in R2, or fetch it from an API. The content is injected into the system prompt and the agent cannot modify it. - -A coding assistant might have a soul that defines its personality and constraints: - - - -```ts -import { Session } from "agents/experimental/memory/session"; - -const session = Session.create(this).withContext("soul", { - provider: { - get: async () => - "You are a senior TypeScript engineer. You write concise, " + - "well-tested code. You prefer composition over inheritance. " + - "When you are unsure, you say so rather than guessing.", - }, -}); -``` - - - -Or load it from R2 so you can update the agent's personality without redeploying: - - - -```ts -const session = Session.create(this).withContext("soul", { - provider: { - get: async () => { - const obj = await env.CONFIG_BUCKET.get("soul.md"); - return obj ? obj.text() : "You are a helpful assistant."; - }, - }, -}); -``` - - - -Read-only blocks are defined by providing an object with only a `get()` method. No tools are generated. The content appears in the system prompt and the agent has no way to change it. - -### Writable short-form context - -Think of this as a scratchpad the agent maintains for itself, a place to jot down things it needs to remember. Like how Claude Code keeps a todo list of tasks to work through, or how a customer support agent might track what it has learned about the user during the conversation. - - - -```ts -const session = Session.create(this) - .withContext("memory", { - description: "Important facts learned during conversation", - maxTokens: 1100, - }) - .withContext("todos", { - description: "Task list, track what needs to be done and what is complete", - maxTokens: 2000, - }); -``` - - - -When you omit the `provider` option in the builder, the Session auto-wires to a SQLite-backed writable provider. The agent gets a `set_context` tool that lets it replace or append content to these blocks. Token limits are enforced, so the agent cannot write more than the `maxTokens` budget allows. - -The system prompt renders writable blocks with a token usage indicator so the agent knows how much space it has left: - -```txt -══════════════════════════════════════════════ -MEMORY (Important facts learned during conversation) [45% — 495/1100 tokens] [writable] -══════════════════════════════════════════════ -User prefers dark mode. -User's project uses React and TypeScript. -Deployment target is Cloudflare Workers. - -══════════════════════════════════════════════ -TODOS (Task list) [12% — 240/2000 tokens] [writable] -══════════════════════════════════════════════ -- [x] Set up project scaffolding -- [ ] Add authentication middleware -- [ ] Write integration tests -``` - -The content persists across messages and survives hibernation. It is always visible in the system prompt, so the agent sees it on every turn without needing to fetch anything. - -### Searchable context - -When you have a large body of information (a knowledge base, documentation, logs, accumulated notes) you do not want to stuff it all into the system prompt. Searchable context keeps a summary in the system prompt (for example, "42 entries indexed") and lets the agent retrieve specific entries when it needs them. - -You provide a provider with a `search()` method. How that search works is entirely up to you: full-text search, vector search via [Vectorize](/vectorize/), a call to an external API, or anything else. The Session does not care about the implementation, only that the provider has a `search()` method. - -The built-in `AgentSearchProvider` uses Durable Object SQLite with FTS5 as default: - - - -```ts -import { AgentSearchProvider } from "agents/experimental/memory/session"; - -const session = Session.create(this).withContext("knowledge", { - description: - "Searchable knowledge base, search for relevant information before answering", - provider: new AgentSearchProvider(this), -}); -``` - - - -But you can implement your own provider backed by any search mechanism: - - - -```ts -const session = Session.create(this).withContext("knowledge", { - description: "Searchable knowledge base", - provider: { - get: async () => "Product documentation and FAQs", - search: async (query) => { - // Use Vectorize, an external API, whatever you need - const results = await env.VECTORIZE_INDEX.query( - await generateEmbedding(query), - { topK: 5 }, - ); - return results.matches.map((m) => m.metadata.text).join("\n\n"); - }, - set: async (key, content) => { - // Index new content - }, - }, -}); -``` - - - -The agent gets a `search_context` tool for querying and a `set_context` tool for indexing new entries. It decides what to search for, and you decide how the search works. - -This is the right choice when the agent needs to find specific pieces of information from a large collection, rather than loading entire documents. - -### Loadable context (Skills) - -Skills are large pieces of context (complete documents, reference guides, runbooks, templates) that the agent can discover and load on demand. Think of them as reference material on a shelf: the agent sees a list of titles and descriptions, picks what is relevant to the current task, loads it, uses it, and unloads it when done. - -Unlike searchable context where the agent retrieves small chunks from a larger collection, skills are designed to be loaded whole. When an agent loads a skill, it gets the entire document in its context window. - -Skills are backed by the `SkillProvider` interface. A skill provider has three methods: - -- **`get()`** returns a metadata listing (titles and descriptions) that appears in the system prompt -- **`load(key)`** fetches the full content of a specific skill -- **`set(key, content, description?)`** writes or updates a skill entry (optional) - -The system prompt shows available skills as a listing. The `[loadable]` tag tells the LLM that these entries are not inline. It needs to use a tool to access the full content: - -```txt -══════════════════════════════════════════════ -SKILLS [loadable] -══════════════════════════════════════════════ -- api-ref: API Reference documentation -- style-guide: Company style guide -- deploy-checklist: Production deployment checklist -``` - -The agent sees the titles, decides which skill is relevant to the current task, and uses `load_context` to pull the full content into its working context. When it is done, it uses `unload_context` to free the space. When the skill provider implements `set()`, the agent can also write back, updating existing skills or creating new ones. - -```txt -Agent sees: "- deploy-checklist: Production deployment checklist" -User asks: "Walk me through a production deployment" -Agent calls: load_context({ block: "skills", key: "deploy-checklist" }) -→ Full checklist content is loaded into the agent's working context -``` - -#### R2-backed skills - -The built-in `R2SkillProvider` stores skills in a Cloudflare R2 bucket. Each skill is an R2 object with optional custom metadata for descriptions. - - - -```ts -import { Session, R2SkillProvider } from "agents/experimental/memory/session"; - -const session = Session.create(this) - .withContext("soul", { - provider: { - get: async () => - [ - "You are a helpful assistant with access to skills.", - "When a user asks you to do something, check the SKILLS section", - "for a relevant skill and use load_context to load it.", - ].join("\n"), - }, - }) - .withContext("memory", { - description: "Learned facts", - maxTokens: 1100, - }) - .withContext("skills", { - provider: new R2SkillProvider(env.SKILLS_BUCKET, { prefix: "skills/" }), - }) - .withCachedPrompt(); -``` - - - -The `prefix` option scopes the provider to a subdirectory in the bucket. Skill keys in the metadata listing are shown without the prefix, so `skills/api-ref` becomes `api-ref` in the system prompt. - -Use `keys` to allowlist specific prefix-relative skills for `get()` and `load()`: - - - -```ts -new R2SkillProvider(env.SKILLS_BUCKET, { - prefix: "skills/", - keys: ["deploy-checklist", "api-ref"], -}); -``` - - - -Add an R2 bucket binding to your Wrangler configuration: - - - -```jsonc -{ - "r2_buckets": [ - { - "binding": "SKILLS_BUCKET", - "bucket_name": "my-agent-skills" - } - ] -} -``` - - - -Skills are regular R2 objects. Upload them through any R2 interface (the Wrangler CLI, the dashboard, or the Workers API): - -```sh -# Upload a skill from a file -wrangler r2 object put my-agent-skills/skills/style-guide --file ./docs/style-guide.md --content-type text/markdown -``` - -To add descriptions (shown in the metadata listing), set custom metadata on the R2 object: - - - -```ts -await env.SKILLS_BUCKET.put("skills/api-ref", content, { - customMetadata: { description: "API Reference documentation" }, -}); -``` - - - -#### Custom skill providers - -You can back skills with any storage by implementing the `SkillProvider` interface: - - - -```ts -import type { SkillProvider } from "agents/experimental/memory/session"; - -class DatabaseSkillProvider implements SkillProvider { - private db: D1Database; - - constructor(db: D1Database) { - this.db = db; - } - - async get(): Promise { - const rows = await this.db - .prepare("SELECT key, description FROM skills ORDER BY key") - .all(); - if (rows.results.length === 0) return null; - return rows.results - .map((r) => `- ${r.key}${r.description ? `: ${r.description}` : ""}`) - .join("\n"); - } - - async load(key: string): Promise { - const row = await this.db - .prepare("SELECT content FROM skills WHERE key = ?") - .bind(key) - .first(); - return row ? (row.content as string) : null; - } - - async set(key: string, content: string, description?: string): Promise { - await this.db - .prepare( - "INSERT INTO skills (key, content, description) VALUES (?, ?, ?) " + - "ON CONFLICT(key) DO UPDATE SET content = ?, description = ?", - ) - .bind(key, content, description ?? null, content, description ?? null) - .run(); - } -} -``` - - - -The Session detects the `load()` method via duck-typing and generates the appropriate tools automatically. - -#### Skills vs other memory types - -| Aspect | Skills | Writable context | Searchable context | -| -------------------- | ----------------------------------- | ------------------------ | ---------------------------------- | -| **In system prompt** | Metadata listing only | Full content | Summary count | -| **Access pattern** | Load whole document by key | Always visible | Search by query | -| **Best for** | Large documents, reference material | Short notes, preferences | Large collections of small entries | -| **Context cost** | Low (until loaded) | Proportional to content | Low (until searched) | -| **Agent writes?** | Optional (if `set` implemented) | Yes (via `set_context`) | Yes (via `set_context`) | - -The key distinction: skills are **lazy**. They cost nearly nothing in the system prompt until the agent decides it needs one. This makes them ideal for large reference material where only a subset is relevant to any given conversation. - -## How agents interact with memory - -The Session automatically generates tools based on the provider types of your context blocks. You pass these tools to your LLM alongside your own application-specific tools: - - - -```ts -const sessionTools = await session.tools(); -const allTools = { ...sessionTools, ...myApplicationTools }; - -const result = streamText({ - model: myModel, - system: await session.freezeSystemPrompt(), - messages: await convertToModelMessages(await session.getHistory()), - tools: allTools, -}); -``` - - - -### Generated tools - -The Session generates tools dynamically based on what provider types are present: - -| Tool | Generated when | What it does | -| -------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | -| **`set_context`** | Any writable, skill, or search block exists | Writes content to a named block. For writable blocks, replaces or appends. For skill/search blocks, writes a keyed entry. | -| **`load_context`** | Any skill block exists | Loads full content of a document by key into the agent's context. | -| **`unload_context`** | Any skill block exists | Frees context space by removing a previously loaded document. The document remains available for re-loading. | -| **`search_context`** | Any search block exists | Full-text search within a searchable block. Returns the top results ranked by relevance. | -| **`session_search`** | Using `SessionManager` | Searches across all sessions (cross-conversation search). | - -The tools include descriptions and parameter schemas that tell the LLM which blocks are available and what they are for. The agent decides when and how to use them based on the conversation. - -For the full tool signatures and all Session methods, refer to the [Session API reference](/agents/runtime/lifecycle/sessions/). - -## The system prompt - -Context blocks are assembled into a structured system prompt with clear headers and metadata. Each block gets a labeled section with tags indicating its type and capacity: - -```txt -══════════════════════════════════════════════ -SOUL (Identity) [readonly] -══════════════════════════════════════════════ -You are a helpful coding assistant who speaks concisely. - -══════════════════════════════════════════════ -MEMORY (Important facts) [45% — 495/1100 tokens] [writable] -══════════════════════════════════════════════ -User prefers dark mode. -User's project uses React and TypeScript. - -══════════════════════════════════════════════ -KNOWLEDGE (Searchable knowledge base) [searchable] -══════════════════════════════════════════════ -12 entries indexed. - -══════════════════════════════════════════════ -SKILLS [loadable] -══════════════════════════════════════════════ -- api-ref: API Reference documentation -- style-guide: Company style guide -``` - -The tags (`[readonly]`, `[writable]`, `[searchable]`, `[loadable]`) tell the LLM what kind of interaction is possible with each block. Token budgets show the agent how much space remains in writable blocks, helping it manage its own memory. - -## Gotchas - -### Prompt caching - -LLM providers (Anthropic, OpenAI, and others) cache the system prompt prefix. When consecutive requests share the same system prompt, the provider can skip re-processing that prefix, reducing both latency and cost. Breaking the cache (by changing the system prompt) throws away this benefit. - -The Session API is designed to work with prompt caching: - -- **`freezeSystemPrompt()`** renders the system prompt from all context blocks on the first call, then returns the cached value on subsequent calls. The prompt does not change between turns, even when the agent writes to memory via `set_context`. -- **`withCachedPrompt()`** persists the frozen prompt to storage, so it survives Durable Object hibernation and eviction. When the agent wakes up, it loads the same prompt without re-fetching from all providers. - -When the agent uses `set_context` to update a writable block, the underlying provider is updated immediately (the data is saved), but the frozen system prompt is **not** re-rendered. The LLM sees the update on its next turn only if you explicitly call `refreshSystemPrompt()`, which you typically do between conversation turns, not mid-turn. - -This means the system prompt stays stable throughout a multi-step tool-use turn, preserving the provider's prefix cache across every step. - - - -```ts -const session = Session.create(this) - .withContext("soul", { - provider: { get: async () => "You are a helpful assistant." }, - }) - .withContext("memory", { description: "Learned facts", maxTokens: 1100 }) - .withCachedPrompt(); // Persist the frozen prompt across hibernation - -// During a conversation turn: -const system = await session.freezeSystemPrompt(); // Same value every call -const tools = await session.tools(); - -// ... agent calls set_context to update memory ... -// The frozen prompt is NOT changed, prefix cache stays warm - -// Between turns (optional, if you want the agent to see its own updates): -await session.refreshSystemPrompt(); -``` - - - -### Compaction - -Long conversations eventually exceed the LLM's context window. Compaction addresses this at two levels: **macro-compaction** summarizes ranges of older messages, and **micro-compaction** truncates individual messages that are too large. - -#### Macro-compaction - -Macro-compaction summarizes older messages, but it never deletes the originals. - -It uses **overlays**: a summary is stored in a separate table, keyed by the message range it covers. When `getHistory()` is called, overlays are applied transparently at read time. The compacted range is replaced by a synthetic summary message. The underlying messages remain in SQLite, preserving the full conversation for audit, search, and branching. - -```txt -Messages: [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] - ↓ compaction ↓ -Overlay: [1] [2] [SUMMARY of 3-7] [8] [9] [10] - ↑ tail protected -``` - -The key points: - -- **Non-destructive**, original messages are never deleted. The full conversation is always available in the database. -- **Iterative**, when the conversation grows again and triggers another compaction, the existing summary is passed to the LLM to update, not replaced from scratch. -- **Boundary-aware**, compaction boundaries are shifted to avoid splitting tool call / tool result pairs. -- **Configurable**, `protectHead` preserves the first N messages (usually the system context), and `tailTokenBudget` keeps the most recent messages intact. - - - -```ts -import { createCompactFunction } from "agents/experimental/memory/utils/compaction-helpers"; - -const session = Session.create(this) - .withContext("memory", { maxTokens: 1100 }) - .onCompaction( - createCompactFunction({ - summarize: (prompt) => - generateText({ model: myModel, prompt }).then((r) => r.text), - protectHead: 3, - tailTokenBudget: 20000, - minTailMessages: 2, - }), - ) - .compactAfter(100_000); // Auto-compact when token estimate exceeds threshold -``` - - - -Auto-compaction triggers after `appendMessage()` when the estimated token count exceeds the threshold. Compaction failure is non-fatal, the message is already saved. - -#### Micro-compaction - -Micro-compaction works at the individual message level rather than across ranges. It handles two problems: - -**Read-time truncation**: `truncateOlderMessages()` shortens tool outputs and long text in older messages before sending them to the LLM. Recent messages (last 4 by default) are kept intact. This operates on a copy, stored messages are not mutated. - - - -```ts -import { truncateOlderMessages } from "agents/experimental/memory/utils"; - -const history = await session.getHistory(); -const truncated = truncateOlderMessages(history); -// Pass truncated history to the LLM -``` - - - -**Row size enforcement**: when a message is persisted (typically an assistant message with large tool outputs), it is checked against the SQLite row size limit. Oversized tool outputs are replaced with a preview and a note suggesting the tool be re-run. This prevents individual messages from exceeding storage limits while preserving the conversation flow. - -## Related - - - - - - diff --git a/src/content/docs/agents/concepts/durable-agents.mdx b/src/content/docs/agents/concepts/durable-agents.mdx new file mode 100644 index 00000000000..0c2ca419ec7 --- /dev/null +++ b/src/content/docs/agents/concepts/durable-agents.mdx @@ -0,0 +1,194 @@ +--- +title: Durable agents +description: A Durable Object gives an agent durable storage, not durable work. Learn how the Agents SDK makes work durable with a job queue in SQLite and the Durable Object alarm. +pcx_content_type: concept +sidebar: + order: 10 +products: + - agents +--- + +import { LinkCard, TypeScriptExample } from "~/components"; + +An agent's work often outlives a single request. A turn can call a model for minutes, wait on a tool, or sleep until tomorrow. A durable agent finishes that work, even if the code running it stops in the middle. + +Serverless infrastructure makes this hard. This page explains why, how the Agents SDK solves it, and what that means for the code you write. + +## Durable storage is not durable work + +Serverless code is request-scoped. It runs when a request, a message, or an event arrives, and the platform can stop it once that event is handled. A request can also time out. There is no background thread that keeps running between events. + +A [Durable Object](/durable-objects/) gives an agent two durable things: + +- **Storage.** Each object has its own SQLite database. A write is transactional and survives anything that happens to the code. +- **One alarm.** The object can set a single time at which the platform wakes it, even if it is not in memory. + +It does not give the agent durable work. An object leaves memory when: + +- It is idle, and hibernates. +- You deploy a new version. +- It exceeds its memory limit, or its isolate crashes. + +When that happens, anything held only in memory is gone: timers, promises, in-flight calls to a model, and local variables. A `setTimeout()` for tomorrow never fires. A loop that was halfway through a list does not continue. + +So the rule for durable work is: **anything that must continue is written to SQLite first, and woken by the alarm.** + +## How the Agents SDK makes work durable + +The [Lifecycle](/agents/concepts/runtime/) turns the object's storage and its one alarm into a durable job queue. + +### Write the intent first + +A job is a row in the object's SQLite database, in a table named `cf_agents_jobs`. The row names the capability that owns the job, a function, a due time, and a payload. Pushing a job writes that row before your code moves on, so the intent to do the work is durable before the work starts. + +A job has an id. Pushing a job with an id that already exists replaces that job, so repeating a push does not create a second job. + +### The alarm loop + +The Lifecycle owns the object's one alarm. Every capability and your own class push jobs to the same queue, and the Lifecycle sets the alarm for the earliest due job. Nothing else sets the alarm, so no capability overwrites another's wake-up time. + +```mermaid +flowchart LR + P["Push a job"] --> R[("Row in cf_agents_jobs
with a due time")] + R --> A["Lifecycle sets the alarm
to the next due job"] + A --> W["Alarm fires and
wakes the object"] + W --> D["Run due jobs
in due-time order"] + D --> O{"Outcome"} + O -->|"Done: delete the row"| A + O -->|"Run later: new due time"| A +``` + +When the alarm fires: + +1. The platform starts the object if it was evicted. The Lifecycle starts its capabilities. +2. The Lifecycle reads every job that is due, and runs them one at a time, in due-time order. Each job goes to the `onJob()` hook of the capability or class that pushed it. +3. Each job returns an outcome. Returning nothing completes the job and deletes its row. Returning a later time keeps the row and moves its due time. Returning `"yield"` leaves the job due, to run again on the next wake. +4. The Lifecycle sets the alarm again, from what is left in the queue. + +The object can hibernate, be evicted, or be replaced by a deploy between any two wakes. The queue is in SQLite, so the next alarm finds it. + +### Failures and crashes + +The job queue handles the ways work can stop: + +- **A job that throws is retried.** By default, the Lifecycle tries a job three times in the same wake, with a short backoff. If every attempt fails, the owner's `onJobError()` hook decides what happens. Without one, the job is complete. +- **A platform failure keeps the job.** If a deploy replaces the isolate, or the object is reset, the job is not retried in place and not deleted. The Lifecycle leaves it in the queue for a fresh run of the alarm. +- **A crash still wakes the object.** Before it runs any job, the Lifecycle sets a backup alarm 30 seconds ahead. If the isolate dies mid-job, that alarm starts the object again, and the job is still due. +- **A long job keeps a heartbeat.** A job can hand off long work, return a due time a short way ahead, and let the work continue. If the object is evicted, the job becomes due and the alarm wakes the object to pick up the work. If the work is still running when the job comes due, the job moves its due time out again. + +### The memory-limit breaker + +Some work fails the same way every time. If a job makes the object exceed its memory limit, the alarm fails, and the platform would retry the alarm, and run the same job, forever. + +The Lifecycle breaks that loop. It counts memory-limit resets during alarms in durable storage: + +- After each reset, it backs off the job that was running. Jobs that a capability marks as part of a recovery loop back off with it. The backoff is 30 seconds after the first reset, and longer after each one. +- After three resets in a row, it deletes those jobs. Other jobs are not touched. +- On each reset, it calls the `onMemoryLimit()` hook of each capability and your class's `onAlarmMemoryLimit()` hook, so they can clean up their own state. + +A clean alarm resets the count. You can change the number of resets with the Lifecycle's `maxAlarmMemoryLimitStrikes` option. + +### Built on the job queue + +Every durable feature in the SDK is a job in this queue: + +- **[Scheduler](/agents/runtime/capabilities/scheduler/)** runs your callbacks after a delay, at a set time, on a cron expression, or at an interval. Each schedule is one job. A recurring schedule returns its next due time as its outcome. +- **[The Pi harness](/agents/harnesses/pi/)** stores its sessions in SQLite and pushes one wake-up job before it hands Pi any work. While Pi is working, the job keeps a 30-second heartbeat. If the object is evicted mid-turn, the alarm wakes it, Pi reopens from SQLite, and resumes its tasks. When Pi has nothing left to do, the job completes. The wake-up job is part of a recovery loop, so the memory-limit breaker stops it if it crashes the object again and again. + +## What this means for your code + +The job queue makes sure work is not lost. It cannot make the work itself safe to repeat. Design for that: + +- **Delivery is at least once.** A job can run more than once: after a retry, after a crash mid-job, or after a deploy. Make each job idempotent. Check durable state before you act, and pass an idempotency key to external services. +- **Persist progress.** Anything only in memory is lost on eviction. Write a checkpoint to SQLite after each step, so a rerun starts where the last run stopped. +- **Keep steps small.** The Lifecycle runs due jobs one at a time, so a slow `onJob()` delays every other job on the object. Do one bounded step per job, then return a new due time for the next one. +- **Know what survives.** Rows in SQLite and jobs in the queue survive. Open connections to other services, a model response that is still streaming, and in-memory timers do not. + +This example writes the intent and the job in the same object, then checks for finished work before it acts: + + + +```ts +import { DurableObject } from "cloudflare:workers"; +import { Lifecycle, type LifecycleJobContext } from "agents/lifecycle"; + +export class ReportAgent extends DurableObject { + readonly lifecycle = Lifecycle.install(this); + + onStart(): void { + this.ctx.storage.sql.exec( + "CREATE TABLE IF NOT EXISTS reports (id TEXT PRIMARY KEY, sent INTEGER NOT NULL DEFAULT 0)", + ); + } + + async requestReport(id: string): Promise { + await this.lifecycle.start(); + // Write the intent first. The row and the job are in SQLite before this method returns. + this.ctx.storage.sql.exec( + "INSERT OR IGNORE INTO reports (id) VALUES (?)", + id, + ); + await this.lifecycle.jobs.push({ + id: `report:${id}`, + fn: "send", + time: Date.now(), + payload: { id }, + }); + } + + async onJob({ job }: LifecycleJobContext): Promise { + if (job.fn !== "send") return; + const { id } = job.payload as { id: string }; + // A job can run more than once. Skip work that already finished. + const [row] = this.ctx.storage.sql + .exec<{ sent: number }>("SELECT sent FROM reports WHERE id = ?", id) + .toArray(); + if (!row || row.sent === 1) return; + + await fetch("https://reports.example.com/send", { + method: "POST", + headers: { "Idempotency-Key": id }, + }); + this.ctx.storage.sql.exec("UPDATE reports SET sent = 1 WHERE id = ?", id); + } +} +``` + + + +## Leave the object for long work + +Some work does not belong inside one Durable Object: + +- **Many steps, with retries per step, that run for hours or days.** Use [Cloudflare Workflows](/workflows/). For when to choose a Workflow, refer to [Workflows](/agents/concepts/workflows/). +- **A long process with a full operating system.** Use [Containers](/containers/). + +## On the `Agent` class + +The `Agent` class adds fibers on top of the job queue. `runFiber()` runs a function that the agent recovers after an eviction, `stash()` saves checkpoints inside it, and `keepAlive()` keeps the object in memory during long work. Fibers exist only on the `Agent` class. For more information, refer to [Durable execution on the Agent class](/agents/agent-class/durable-execution/). + +## Related resources + + + + + + + + diff --git a/src/content/docs/agents/concepts/harnesses.mdx b/src/content/docs/agents/concepts/harnesses.mdx new file mode 100644 index 00000000000..5d29374d20d --- /dev/null +++ b/src/content/docs/agents/concepts/harnesses.mdx @@ -0,0 +1,107 @@ +--- +title: Harnesses +description: A harness is the agent loop around the model, and the unit of compute for an agent on Cloudflare. +pcx_content_type: concept +sidebar: + order: 2 +products: + - agents +--- + +import { LinkCard, TypeScriptExample } from "~/components"; + +A harness is the loop that turns a model into an agent. A single model call answers one prompt. A harness keeps calling the model until the task is done. + +On each turn, the harness: + +- Builds the prompt from the system instructions, the transcript, and any context. +- Calls the model. +- Runs the tools the model asks for, and returns their results to the model. +- Stores the transcript, so the next turn starts where the last one ended. +- Retries failed calls and recovers work that an eviction cut short. + +## The unit of compute + +A harness is the unit of compute for an agent. You do not write the loop for each agent. You pick a harness, give it a model and tools, and send it work. The harness decides how many model calls and tool calls the work needs. + +The Agents SDK exists to make harnesses run well on Cloudflare. It hosts a harness in a [Durable Object](/durable-objects/), stores the harness's state in the object's SQLite database, and wakes the harness after an eviction. + +## A harness is a capability + +On Cloudflare, a harness is one kind of [capability](/agents/concepts/runtime/). You install it on the Durable Object's Lifecycle with `.use()`, like any other capability: + + + +```ts +import { DurableObject } from "cloudflare:workers"; +import { createModels } from "@earendil-works/pi-ai/models"; +import { createRegistry, Harness } from "@earendil-works/pi-durable"; +import { PiHarness } from "agents/harness/pi"; +import { Lifecycle } from "agents/lifecycle"; +import { createAI } from "agents/models/pi-ai"; + +export class Assistant extends DurableObject { + ai = createAI({ binding: this.env.AI }); + registry = createRegistry(); + + harness = new PiHarness({ + harness: ({ storage, context, onWake }) => { + const models = createModels(); + models.setProvider(this.ai.provider); + return Harness.open( + storage, + { models, registry: this.registry, onWake }, + context, + ); + }, + defaults: { model: this.ai("@cf/zai-org/glm-5.3-flash") }, + }); + + lifecycle = Lifecycle.install(this).use(this.harness); + + async ask(prompt: string) { + return (await this.harness.prompt(prompt)).text; + } +} +``` + + + +The harness and the runtime split the work: + +| The harness owns | The runtime owns | +| ------------------------------------------------------ | ---------------------------------------------------------------- | +| The transcript and its sessions | Startup, request routing, and WebSockets | +| Model calls, tool calls, and retries | The SQLite database the harness stores its state in | +| Which input runs next, and which input steers the turn | The job queue and the alarm that wake the harness after eviction | +| Recovery of interrupted tool calls | Other capabilities, such as schedules and MCP clients | + +The harness never sets its own timers. It pushes a job to the Lifecycle's [job queue](/agents/concepts/durable-agents/), so the object can hibernate between steps and still wake on time. + +## Choose a harness + +- **[Pi harness](/agents/harnesses/pi/)**: runs [Pi Durable](https://github.com/earendil-works/pi/tree/main/packages/durable) in a Durable Object. Pi owns the transcript, the inbox of follow-ups, tool calls, retries, and crash recovery. Start new agents here. +- **[Think](/agents/harnesses/think/)**: an opinionated chat agent with memory, workspace tools, and streaming built in. Think is a class that extends the `Agent` class, so its loop comes with the `Agent` class preset. +- **[OpenCode](/agents/harnesses/opencode/)** (experimental): runs OpenCode's sessions, tools, and plugins in a Durable Object. + +The SDK also has experimental harnesses that run Think's loop as a capability, and that drive an agent CLI, such as Claude Code or Codex, in a [Container](/containers/). + +## Build your own + +A harness is a Lifecycle capability. To write your own loop, extend `LifecycleCapability`, store the transcript in the object's SQLite database, and push a job to the Lifecycle's queue whenever work must continue after an eviction. For more information, refer to [Build a capability](/agents/runtime/capabilities/build-a-capability/). + +The SDK has experimental building blocks for this: `Sessions` stores the transcript, `Streams` stores output while it streams, and `Tasks` runs replayable steps. + +## Related resources + + + + diff --git a/src/content/docs/agents/concepts/index.mdx b/src/content/docs/agents/concepts/index.mdx index 9637561aa37..e45d03d77c9 100644 --- a/src/content/docs/agents/concepts/index.mdx +++ b/src/content/docs/agents/concepts/index.mdx @@ -1,15 +1,25 @@ --- -pcx_content_type: reference +pcx_content_type: navigation title: Concepts -description: Understand the core concepts behind Cloudflare Agents, including state, tools, workflows, and memory. +description: The building blocks of an agent on Cloudflare, explained independently of any one implementation. sidebar: - order: 2 - group: - hideIndex: true + order: 3 products: - agents --- -import { DirectoryListing } from "~/components"; +These pages explain the building blocks of an agent on Cloudflare. Each page describes one idea, then links to the pages that implement it. - +Read them in order if you are new to agents: + +1. [What are agents?](/agents/concepts/what-are-agents/): what an agent is, and how it differs from a workflow or a co-pilot. +2. [Harnesses](/agents/concepts/harnesses/): the agent loop, and the unit of compute. +3. [Runtime](/agents/concepts/runtime/): the Durable Object, the Lifecycle, and capabilities. +4. [Models](/agents/concepts/models/): how an agent reaches a model. +5. [Tools](/agents/concepts/tools/): what a model can call, and how each tool is backed. +6. [Workspace](/agents/concepts/workspace/): the agent's durable files and the runtimes that work on them. +7. [Memory](/agents/concepts/memory/): conversation history and context. +8. [Channels](/agents/concepts/channels/): how people and systems reach an agent. +9. [Durable agents](/agents/concepts/durable-agents/): durable storage is not durable work, and how the job queue and the alarm close the gap. +10. [Workflows](/agents/concepts/workflows/): when to hand work to Cloudflare Workflows. +11. [Agentic patterns](/agents/concepts/agentic-patterns/): common designs, including human-in-the-loop and long-running agents. diff --git a/src/content/docs/agents/concepts/memory.mdx b/src/content/docs/agents/concepts/memory.mdx new file mode 100644 index 00000000000..da30e79d467 --- /dev/null +++ b/src/content/docs/agents/concepts/memory.mdx @@ -0,0 +1,109 @@ +--- +title: Memory +pcx_content_type: concept +description: How agents store and recall information, including conversation history, context in the system prompt, long-term memory, and compaction. +tags: + - AI +sidebar: + order: 8 +products: + - agents +--- + +import { LinkCard } from "~/components"; + +Agents need memory to be useful over time. Without it, every conversation starts from zero. The agent forgets who the user is, what it learned, and what it was doing. + +An agent on Cloudflare keeps its memory in its Durable Object, so memory survives restarts and belongs to one agent instance. There are two kinds: + +- **Conversation history**: the messages and tool calls that make up a conversation. +- **Context**: what the model reads in its system prompt on every turn, such as its identity and facts it learned about the user. + +The two are separate. An agent can have a prompt without a transcript, or a transcript without a prompt. + +## Conversation history + +The [harness](/agents/concepts/harnesses/) stores the conversation history for you, in the object's SQLite database: + +- The [Pi harness](/agents/harnesses/pi/) stores each Pi session's transcript. Read it with `harness.messages()`. Each session is a separate conversation, and you can fork a session or reset it with a handoff note. +- [Think](/agents/harnesses/think/) stores each chat's messages, and streams them to clients. + +Because the history lives on the server, a client sends only the new message. The harness builds the prompt from what it stored. + +A conversation is a session in the harness. One agent instance can hold many sessions, such as one per chat thread. Use separate agent instances when conversations belong to different users. + +## Context + +Context is the part of the prompt that is not the conversation. It usually has: + +- **Read-only instructions**, such as the agent's role and rules. +- **Writable memory**, such as facts about the user that the model updates with a tool. +- **Searchable knowledge**, where the prompt holds a summary and the model searches for details with a tool. + +Long-term memory does not need a special store. An agent can keep notes as files on its [workspace](/agents/concepts/workspace/), or as rows in its SQLite database, and read them back with a tool. + +### Context blocks + +`ContextBlocks` from `agents/context` assembles the system prompt from labelled blocks. Each block has a provider, and what the provider can do decides which tool the model gets for it: + +| Provider | Block behavior | Tool for the model | +| ---------------------- | -------------------------------------------------------- | ------------------ | +| `get()` | Read-only text, such as the agent's identity | None | +| `get()` and `set()` | Writable memory the model updates, such as user facts | `set_context` | +| `get()` and `search()` | A summary in the prompt, and full-text search on request | `search_context` | + +```ts +import { ContextBlocks } from "agents/context"; + +const context = new ContextBlocks([ + { + label: "soul", + provider: { get: async () => "You are a helpful assistant." }, + }, + { + label: "memory", + description: "Facts learned about the user", + maxTokens: 1_100, + provider: memoryProvider, + }, +]); + +const system = await context.freezeSystemPrompt(); +const tools = await context.tools(); +``` + +Each block renders with a header that shows its label, its description, how much of its `maxTokens` budget it uses, and a marker such as `[readonly]` or `[writable]`. The markers and budgets tell the model what it can do with each block, so it can manage its own memory. + +`agents/context` includes two durable providers that store their data in the object's SQLite database. `AgentContextProvider` stores a writable block, and `AgentSearchProvider` backs a searchable block with a full-text index. Think builds its system prompt from context blocks. + +:::caution[Experimental] +`agents/context` is experimental. Its API may change between releases. +::: + +## Keep the prompt stable + +Model providers cache the start of a request. If the system prompt changes between turns, the cache misses, and every turn pays for the full prompt again. + +`freezeSystemPrompt()` renders the prompt once and returns the same string on every later call. A write to a block goes to its provider at once, but it does not change the frozen prompt until you call `refreshSystemPrompt()`. Store the frozen prompt, so a restarted agent reuses the exact prompt the model already cached. + +For a block that changes while the prompt is frozen, such as the current date, set `whenChanged: "remind"`. `reminder()` then returns the new value for you to send after the cached part, for example at the end of the latest user message. + +## Compaction + +Long conversations eventually exceed the model's context window. Compaction replaces older messages with a summary when the harness builds the prompt. The original messages stay in storage, so you can still show them to the user. + +Refresh the system prompt after a compaction, so the prompt and the summarized history agree. + +## Related resources + + + + diff --git a/src/content/docs/agents/concepts/models.mdx b/src/content/docs/agents/concepts/models.mdx new file mode 100644 index 00000000000..0cc3426dd1b --- /dev/null +++ b/src/content/docs/agents/concepts/models.mdx @@ -0,0 +1,78 @@ +--- +title: Models +description: How an agent reaches a model on Cloudflare, who decides when to call it, and why a stateful agent changes how you use models. +pcx_content_type: concept +tags: + - AI +sidebar: + order: 4 +products: + - agents +--- + +import { LinkCard } from "~/components"; + +A model is the reasoning part of an agent. It reads the prompt and decides what to say, or which tool to call next. An agent can use one model or several. + +## How an agent reaches a model + +An agent reaches models through a provider. The Agents SDK has one provider factory, `createAI`, for each agent framework: + +- `agents/models/pi-ai` for the [Pi harness](/agents/harnesses/pi/). +- `agents/models/ai-sdk` for the [AI SDK](https://ai-sdk.dev/), Think, and the `Agent` class. + +Both providers use the Worker's `AI` binding. One provider serves every model, named by a string: + +```ts +ai("@cf/zai-org/glm-5.3-flash"); // a Workers AI model +ai("anthropic/claude-opus-5.5"); // a model from the AI Gateway catalog +ai("dynamic/support"); // an AI Gateway dynamic route +``` + +[Workers AI](/workers-ai/) models run on Cloudflare. Third-party models run through [AI Gateway](/ai-gateway/), which holds the vendor credentials, so your agent needs no vendor keys. AI Gateway also adds caching, logging, retries, and fallback between models. + +## The harness calls the model + +In an agent, you do not call the model on each turn yourself. The [harness](/agents/concepts/harnesses/) decides when to call it, how many times, and what to send. You choose: + +- The default model, such as the `defaults.model` option of the Pi harness. +- The model per session or per task, such as a cheaper model for summaries. +- The tools and context the harness sends with each call. + +To call a model outside a harness, such as in a one-off summary, use the provider directly with the framework's own functions, such as `generateText()` from the AI SDK. + +## A stateful agent changes how you use models + +A stateless Worker rebuilds its context on every request. An agent keeps state in its Durable Object, which changes how you use a model: + +- **History stays on the server.** The client sends only the new message. The harness reads the transcript from the object's database and builds the prompt. For more information, refer to [Memory](/agents/concepts/memory/). +- **Long calls survive disconnects.** A reasoning model can take minutes. The agent keeps running after the client disconnects, stores the answer, and delivers it when the client reconnects. +- **The agent calls the model on its own.** A schedule, a webhook, or an email can start a turn when no user is connected. For more information, refer to [Durable agents](/agents/concepts/durable-agents/). +- **Interrupted calls recover.** If the object is evicted during a turn, the harness resumes the turn when the object wakes. The Pi harness does this for you. + +## Control cost + +- **Keep the prompt prefix stable.** Model providers cache the start of a request. A system prompt that changes on every turn misses that cache. +- **Summarize old turns.** Long transcripts grow past the context window. Harnesses can compact older messages into a summary. +- **Cache in AI Gateway.** Identical requests from many agents can share one cached response. +- **Use a smaller model where it is enough.** Route simple steps, such as classification, to a cheaper model. + +## Related resources + + + + + + diff --git a/src/content/docs/agents/concepts/runtime.mdx b/src/content/docs/agents/concepts/runtime.mdx new file mode 100644 index 00000000000..eba9a194a05 --- /dev/null +++ b/src/content/docs/agents/concepts/runtime.mdx @@ -0,0 +1,102 @@ +--- +title: Runtime +description: An agent runs on a Durable Object with the Lifecycle installed and capabilities attached. Understand each part and the kinds of capabilities. +pcx_content_type: concept +sidebar: + order: 3 +products: + - agents +--- + +import { LinkCard, TypeScriptExample } from "~/components"; + +The runtime is where an agent lives. It has three parts: + +- A **Durable Object**, which is the agent instance. +- The **Lifecycle**, which runs the object's startup, requests, and background work. +- **Capabilities**, which add features to the object, one at a time. + +## The Durable Object + +Each agent instance is a [Durable Object](/durable-objects/). A Durable Object has: + +- A name that addresses it from anywhere, such as a user ID or a conversation ID. +- Its own SQLite database, which survives restarts. +- One alarm, which wakes it at a set time. +- WebSockets that stay connected while it hibernates. + +You run one instance per user, conversation, or task. An idle instance leaves memory and costs close to nothing. A request, a WebSocket message, or the alarm wakes it again. + +## The Lifecycle + +The `Lifecycle` from `agents/lifecycle` takes over the object's `fetch`, `alarm`, and WebSocket handlers. You install it once, in a field: + + + +```ts +import { DurableObject } from "cloudflare:workers"; +import { Lifecycle } from "agents/lifecycle"; +import { MCPClientManager } from "agents/mcp/client"; +import { Scheduler } from "agents/schedules"; + +export class Assistant extends DurableObject { + readonly mcp = new MCPClientManager("assistant", "1.0.0"); + readonly scheduler = new Scheduler({ callbacks: {} }); + readonly lifecycle = Lifecycle.install(this) + .use(this.mcp) + .use(this.scheduler); +} +``` + + + +The Lifecycle does three things: + +- **Startup.** It starts each capability, then calls your `onStart()` hook, once per time the object loads. +- **Routing.** It offers each request to the capabilities in order. The first capability that returns a response handles it. A request that no capability claims reaches your `onRequest()` hook. +- **Durable work.** It owns one job queue in SQLite and the object's single alarm. Every capability shares them. For more information, refer to [Durable agents](/agents/concepts/durable-agents/). + +The Lifecycle needs a named object and SQLite storage. Address objects with `getByName()` or `idFromName()`. + +## Capabilities + +A capability is a self-contained feature that you attach with `lifecycle.use()`. Each capability stores its own tables in the object's database, and runs only the hooks it needs. Capabilities do not depend on each other, so you install only the ones your agent uses. + +### How a capability claims traffic + +- **Selective** (the default): the capability handles only the requests it recognizes, and passes the rest on. +- **Catch-all**: the capability handles every request that reaches it. It runs after every selective capability. `WebSockets` is a catch-all for WebSocket upgrades. + +### What a capability does + +| Role | Capabilities | +| ------------------ | -------------------------------------------------------------------------------------------------------- | +| Connections | [`State`](/agents/runtime/capabilities/state/), [`WebSockets`](/agents/runtime/capabilities/websockets/) | +| Durable work | [`Scheduler`](/agents/runtime/capabilities/scheduler/) | +| External resources | [`MCPClientManager`](/agents/runtime/capabilities/mcp-client-manager/) | +| Harnesses | [`PiHarness`](/agents/harnesses/pi/) | +| Your own | A class that extends `LifecycleCapability` | + +The SDK also has experimental capabilities, whose APIs may change: `Queue` and `Tasks` for background work, `Sessions` and `Streams` for harness storage, `RoutedAgents` for routing between agents, and `Browser` for a persistent browser. + +A harness is a capability like the others. It gets the same storage, startup, and job queue. For more information, refer to [Harnesses](/agents/concepts/harnesses/). + +To write your own capability, refer to [Build a capability](/agents/runtime/capabilities/build-a-capability/). + +## On the `Agent` class + +The [`Agent` class](/agents/agent-class/) is a preset of this runtime. It is a Durable Object with the Lifecycle and a set of capabilities already installed, such as `Scheduler`, `State`, `WebSockets`, and `MCPClientManager`. Its methods, such as `this.schedule()` and `this.setState()`, call those capabilities. It also adds APIs that exist only on `Agent`, such as `@callable()` methods and fibers. + +## Related resources + + + + diff --git a/src/content/docs/agents/concepts/tools.mdx b/src/content/docs/agents/concepts/tools.mdx index f3e4adc0309..15b13aebe30 100644 --- a/src/content/docs/agents/concepts/tools.mdx +++ b/src/content/docs/agents/concepts/tools.mdx @@ -1,79 +1,95 @@ --- title: Tools -description: Understand how tools are exposed to models, where tools execute, and how MCP connects external tools to Cloudflare Agents. +description: Understand what a tool is, how each tool is backed, how tools reach each harness, and where tools run. pcx_content_type: concept sidebar: - order: 4 + order: 5 products: - agents --- -Tools let models retrieve information, process data, and perform actions. Each tool defines an interface that describes its inputs, outputs, and behavior. +import { LinkCard } from "~/components"; -A travel agent might use tools to search flights, check hotel rates, process payments, and send confirmation emails. The tool interface lets the model understand when and how to use each capability. +A tool is something a model can call. It lets the model look up information, change data, or act in the world. Each tool has a name, a description, and an input schema. The model reads them to decide when to call the tool and with which arguments. -Tool design involves three independent choices: +A travel agent might use tools to search flights, check hotel rates, take payments, and send confirmation emails. -1. **Model interface** — expose tools as direct tool calls or through Code Mode. -2. **Execution location** — run tool implementations in a Worker, browser, or another Agent. -3. **Tool source** — define tools in the application or connect to externally hosted tools through Model Context Protocol (MCP). +The harness runs the loop around tool calls. The model asks for a call, the harness runs the tool, and the harness returns the result to the model. The model then decides what to do next. -For example, browser tools can be exposed directly or through Code Mode. An MCP tool can also be exposed through either model interface. +## How a tool is backed -## Choose the model interface +A tool needs something to do its work. On Cloudflare, a tool is backed in one of three ways: -Direct tool calls and Code Mode define how the model sees and invokes tools. They do not determine where the underlying tool implementations run. +| Backing | What it means | Examples | +| ------------- | ------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | +| Stateless | The tool keeps nothing between calls. It calls an API and returns the result. | [Web fetch](/agents/tools/web-fetch/), [web search](/agents/tools/web-search/) | +| A plain field | The tool works on an object you create in a field of the Durable Object. It is not a Lifecycle capability. | The [workspace](/agents/concepts/workspace/) file tools: read, write, edit, find, and `exec` | +| A capability | The tool works on a capability you attach with `lifecycle.use()`. The capability keeps state and connections. | [MCP](/agents/tools/mcp/) tools, through the [MCP client](/agents/runtime/capabilities/mcp-client-manager/) | -| Interface | How it works | Use when | -| ----------------- | ------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------- | -| Direct tool calls | The model receives individual tool definitions. Each result returns to the model before it chooses the next call. | The task is simple and uses a small, known tool set. | -| Code Mode | The model receives one code tool and writes code against typed tool interfaces. | The task needs composition, dependent calls, filtering, branching, repeatable logic, or tool discovery. | +The backing tells you what to install. A stateless tool needs only its import. A tool on a plain field needs the field. A tool on a capability needs the capability on the Lifecycle. -### Direct tool calls +## How a tool reaches each harness -Most tool examples use direct tool calls, even when they do not name the pattern. You define each tool and pass its schema to the model. The model selects a tool, your application executes it, and the result returns to the model. +Each harness has its own tool format. The Agents SDK and Cloudflare Computer ship one adapter per format, so the same tool works with each harness: -The model sees each intermediate result before choosing another tool. This makes the execution path easy to inspect. However, dependent operations require repeated model turns and consume context with intermediate data. +| Harness or framework | How you add tools | Example adapter | +| -------------------- | -------------------------------------------------------- | ----------------------------- | +| Pi harness | A Pi extension on the harness registry | `agents/webfetch/pi` | +| Think | `getTools()`, plus the built-in workspace tools | `agents/webfetch/ai-sdk` | +| AI SDK | The `tools` option of `streamText()` or `generateText()` | `agents/webfetch/ai-sdk` | +| TanStack AI | The `tools` option of `chat()` | `agents/webfetch/tanstack-ai` | -### Code Mode +Each tool page shows the adapter for each harness. For the full list of tools, refer to [Tools](/agents/tools/). -[Code Mode](/agents/tools/codemode/) gives the model one code-execution tool. The model writes JavaScript that calls typed tools, passes results between them, and applies control flow. +## Direct tool calls or Code Mode -The generated code can filter large responses and return only the final value the model needs. Intermediate results stay inside the sandbox instead of entering the model context after every operation. This makes Code Mode more efficient for composed workflows and large tool catalogs. +How the model sees tools is another separate choice: -Code Mode also supports progressive discovery. The model can search available connectors and request detailed types only for the methods it needs. Successful programs can be saved as reusable snippets. +| Interface | How it works | Use when | +| ----------------- | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | +| Direct tool calls | The model receives each tool definition. Each result returns to the model before it chooses the next call. | The task is simple and uses a small, known set of tools. | +| Code Mode | The model receives one code tool, and writes JavaScript that calls typed tool interfaces. | The task needs composition, dependent calls, filtering, branching, or a large tool catalog. | -For runtime behavior, approvals, replay, and snippets, refer to [How Code Mode works](/agents/tools/codemode/how-it-works/). +With direct calls, every intermediate result enters the model's context, and each dependent call costs a model turn. With [Code Mode](/agents/tools/codemode/), the generated code passes results between tools in a sandbox, and returns only the final value. The model can also search the available tools and request types only for the ones it needs. -## Choose where tools run +Any tool can be exposed either way, whatever backs it. For more information, refer to [How Code Mode works](/agents/tools/codemode/how-it-works/). -Execution location describes where a tool implementation runs. It is independent from the model interface. Tools in each location can be exposed directly or through Code Mode. +## Where a tool runs -| Location | Use when | Start here | -| ------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------- | -| Worker | The tool calls an API, queries SQL, or uses server-side bindings and secrets. | [Server-side tools](/agents/agent-class/communication-channels/chat/chat-agents/#server-side-tools) | -| Browser | The tool needs geolocation, clipboard, local storage, or other browser APIs. | [Client-side tools](/agents/agent-class/communication-channels/chat/chat-agents/#client-side-tools) | -| Another Agent | A chat-capable Agent should execute as a retained, streaming tool. | [Agents as tools](/agents/agent-class/agent-tools/) | +Where a tool runs is a separate choice from how it is backed: -With direct tool calls, the model calls the tool and the framework routes execution to the configured location. - -With Code Mode, generated code runs in a sandbox. Calls from that code cross the sandbox boundary to the underlying tool implementation. Server tools can execute in the host Worker, browser-owned tools can execute in the parent page, and Agent tools can delegate work to another Agent. +- **In the agent.** Most tools run in the Durable Object. They can use bindings, secrets, and the object's database. +- **In the browser.** A client tool has no server implementation. The client runs it and sends back the result, so the tool can use browser APIs such as geolocation. For an example, refer to [Think client tools](/agents/harnesses/think/client-tools/). +- **In another service.** An MCP tool runs on the MCP server that hosts it. The agent only sends the call and receives the result. ## Connect external tools with MCP -The [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) standardizes how AI applications discover and invoke externally hosted tools. MCP describes the source and transport of a tool, not how the model must invoke it. +The [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) is a standard for discovering and calling tools that other services host. An agent connects to MCP servers with the [MCP client](/agents/runtime/capabilities/mcp-client-manager/) capability, then passes the servers' tools to its harness. For more information, refer to [MCP tools](/agents/tools/mcp/). + +MCP tools can also be exposed inside Code Mode, through [MCP connectors](/agents/tools/codemode/mcp/). To expose your own tools to other agents, build an [MCP server](/agents/model-context-protocol/). -An Agent can expose MCP tools through either model interface: +## Control side effects -- Pass MCP tools directly to a model with the [Agents MCP client](/agents/tools/mcp/). -- Expose MCP tools inside Code Mode for composition and progressive discovery with [MCP connectors](/agents/tools/codemode/mcp/). +A tool that changes external state, such as a payment or a deletion, may need a person to approve it first. For more information, refer to [Human-in-the-loop](/agents/concepts/agentic-patterns/human-in-the-loop/). -An MCP server can also expose Code Mode itself. For example, it can present one `code` tool or separate `search` and `execute` tools. For these server-side patterns, refer to [Build a Code Mode MCP server](/agents/model-context-protocol/guides/build-codemode-mcp-server/). +Harnesses also decide what happens when an eviction interrupts a tool call. The Pi harness runs a call again only if the tool is marked replay-safe. Otherwise, it tells the model that the call was interrupted. -## Control side effects +## Related resources -Approval policy is also independent from execution location and tool source. Any tool that modifies external state may require user approval. + -Direct tools can use the standard [human-in-the-loop approval pattern](/agents/concepts/agentic-patterns/human-in-the-loop/). + -The durable Code Mode runtime can pause generated code before an annotated connector method executes. Approval replays completed calls from the execution log, applies the approved action, and continues the same program. + diff --git a/src/content/docs/agents/concepts/what-are-agents.mdx b/src/content/docs/agents/concepts/what-are-agents.mdx index 2784b2271c9..f03f648a9fc 100644 --- a/src/content/docs/agents/concepts/what-are-agents.mdx +++ b/src/content/docs/agents/concepts/what-are-agents.mdx @@ -1,29 +1,27 @@ --- title: What are agents? -description: Understand what Agents are, how they differ from workflows and co-pilots, and when to use them. +description: Understand what agents are, how they differ from workflows and co-pilots, and how an agent is built on Cloudflare. pcx_content_type: concept tags: - AI - LLM sidebar: - order: 2 + order: 1 products: - agents --- import { LinkCard } from "~/components"; -An agent is an AI system that can autonomously execute tasks by making decisions about tool usage and process flow. Unlike traditional automation that follows predefined paths, agents can dynamically adapt their approach based on context and intermediate results. Agents are also distinct from co-pilots (such as traditional chat applications) in that they can fully automate a task, as opposed to simply augmenting and extending human input. +An agent is an AI system that completes tasks on its own. It decides which tools to use and in what order. Traditional automation follows a fixed path. An agent adapts its approach to the context and to the results it gets along the way. A co-pilot, such as a chat assistant, helps a person do a task. An agent can do the whole task. -- **Agents** → non-linear, non-deterministic (can change from run to run) -- **Workflows** → linear, deterministic execution paths -- **Co-pilots** → augmentative AI assistance requiring human intervention +- **Agents**: non-linear and non-deterministic. The path can change from run to run. +- **Workflows**: linear, deterministic execution paths. +- **Co-pilots**: AI assistance that needs a person to decide and act. -## Example: Booking vacations +## Example: book a vacation -If this is your first time working with or interacting with agents, this example illustrates how an agent works within a context like booking a vacation. - -Imagine you are trying to book a vacation. You need to research flights, find hotels, check restaurant reviews, and keep track of your budget. +Imagine you are booking a vacation. You need to research flights, find hotels, check restaurant reviews, and keep track of your budget. ### Traditional workflow automation @@ -36,73 +34,74 @@ A traditional automation system follows a predetermined sequence: ![Traditional workflow automation diagram](~/assets/images/agents/workflow-automation.svg) -### AI Co-pilot +### AI co-pilot -A co-pilot acts as an intelligent assistant that: +A co-pilot acts as an assistant that: -- Provides hotel and itinerary recommendations based on your preferences -- Can understand and respond to natural language queries +- Recommends hotels and itineraries based on your preferences +- Understands and responds to natural language - Offers guidance and suggestions -- Requires human decision-making and action for execution +- Leaves decisions and actions to you ![A co-pilot diagram](~/assets/images/agents/co-pilot.svg) ### Agent -An agent combines AI's ability to make judgments and call the relevant tools to execute the task. An agent's output will be nondeterministic given: +An agent combines a model's judgment with tools that carry out the task. Its output is non-deterministic, because of: - Real-time availability and pricing changes - Dynamic prioritization of constraints -- Ability to recover from failures -- Adaptive decision-making based on intermediate results +- Recovery from failures +- Decisions based on intermediate results ![An agent diagram](~/assets/images/agents/agent-workflow.svg) -An agent can dynamically generate an itinerary and execute on booking reservations, similarly to what you would expect from a travel agent. - -## Components of agent systems +An agent can build an itinerary and book the reservations, as a travel agent would. -Agent systems typically have three primary components: +## Parts of an agent -- **Decision Engine**: Usually an LLM (Large Language Model) that determines action steps -- **Tool Integration**: APIs, functions, and services the agent can utilize — often via [MCP](/agents/model-context-protocol/) -- **Memory System**: Maintains context and tracks task progress +An agent runs in a loop: -### How agents work +1. **Observe** the current state or task. +2. **Plan** what to do next, using a model to reason. +3. **Act** by calling tools. +4. **Record** the results in memory, then start the next iteration. -Agents operate in a continuous loop of: +On Cloudflare, each part of that loop maps to a building block: -1. **Observing** the current state or task -2. **Planning** what actions to take, using AI for reasoning -3. **Executing** those actions using available tools -4. **Learning** from the results (storing results in memory, updating task progress, and preparing for next iteration) +| Part | Building block | +| ------------------------- | ---------------------------------------------------------------------------------------------------------- | +| The loop itself | A [harness](/agents/concepts/harnesses/), such as the Pi harness | +| Where the agent lives | The [runtime](/agents/concepts/runtime/): a Durable Object with the Lifecycle and capabilities | +| Reasoning | A [model](/agents/concepts/models/), reached through Workers AI or AI Gateway | +| Actions | [Tools](/agents/concepts/tools/), including tools from [MCP](/agents/model-context-protocol/) servers | +| Working files | A [workspace](/agents/concepts/workspace/), provided by Cloudflare Computer | +| What it remembers | [Memory](/agents/concepts/memory/): conversation history and context | +| How people reach it | [Channels](/agents/concepts/channels/), such as WebSockets, chat, and email | +| Work that must finish | [Durable agents](/agents/concepts/durable-agents/): a job queue driven by the Durable Object's alarm | -## Building agents on Cloudflare +## Build agents on Cloudflare -The Cloudflare Agents SDK provides the infrastructure for building production agents: +Each agent instance is a [Durable Object](/durable-objects/). It has a name, its own SQLite database, and an alarm. You can run one agent per user, conversation, or task. An idle agent hibernates and costs close to nothing until a request or an alarm wakes it. -- **Persistent state** — Each agent instance has its own SQLite database for storing context and memory -- **Real-time sync** — State changes automatically broadcast to all connected clients via WebSockets -- **Hibernation** — Agents sleep when idle and wake on demand, so you only pay for what you use -- **Global edge deployment** — Agents run close to your users on Cloudflare's network -- **Built-in capabilities** — Scheduling, task queues, workflows, email handling, and more +The Agents SDK makes harnesses run well on that runtime. The harness owns the loop. The runtime stores its state and wakes it after an eviction, a deploy, or a crash. ## Next steps diff --git a/src/content/docs/agents/concepts/workflows.mdx b/src/content/docs/agents/concepts/workflows.mdx index 2a15c661ae2..fcc60fb6da8 100644 --- a/src/content/docs/agents/concepts/workflows.mdx +++ b/src/content/docs/agents/concepts/workflows.mdx @@ -1,204 +1,89 @@ --- -title: Using Agents with Workflows -description: Integrate Cloudflare Workflows with Agents for durable, multi-step background processing with automatic retries. +title: Agents and Workflows +description: When to hand work from an agent to Cloudflare Workflows, how the two communicate, and what AgentWorkflow adds on the Agent class. pcx_content_type: concept sidebar: - order: 7 + order: 11 products: - agents --- -import { TypeScriptExample, LinkCard } from "~/components"; +import { LinkCard } from "~/components"; -## What are Workflows? +[Cloudflare Workflows](/workflows/) run durable, multi-step processes. Each step is saved when it completes, retries on failure, and never runs twice. A Workflow can also pause for days to wait for an event, such as an approval. -[Cloudflare Workflows](/workflows/) provide durable, multi-step execution for tasks that need to survive failures, retry automatically, and wait for external events. When integrated with Agents, Workflows handle long-running background processing while Agents manage real-time communication. +An agent and a Workflow solve different problems, and they work well together. -### Agents vs. Workflows +## Agents and Workflows compared -Agents and Workflows have complementary strengths: +| Property | Agent | Workflow | +| ----------------------- | ------------------------------------------ | -------------------------------- | +| Execution model | A long-lived instance that wakes on events | A run that goes to completion | +| Path | Chosen by the model at each turn | Fixed steps in code | +| Real-time communication | WebSockets and HTTP streaming | None | +| State | Its own SQLite database | The saved result of each step | +| Failure handling | The harness and the Lifecycle job queue | Automatic retries per step | +| Waiting | Hibernates until a request or the alarm | Pauses until an event or a timer | -| Capability | Agents | Workflows | -| ----------------------- | ---------------------------------------- | ------------------------------ | -| Execution model | Long-lived identity that wakes on events | Run to completion | -| Real-time communication | WebSockets, HTTP streaming | Not supported | -| State persistence | Built-in SQL database | Step-level persistence | -| Failure handling | Application-defined | Automatic retries and recovery | -| External events | Direct handling | Pause and wait for events | -| User interaction | Direct (chat, UI) | Through Agent callbacks | +An agent decides what to do. A Workflow does a known sequence of steps, reliably. -Agents can loop, branch, and interact directly with users. Workflows execute steps sequentially with guaranteed delivery and can pause for days waiting for approvals or external data. +## When to use each -### When to use each +Use an agent on its own for: -**Use Agents alone for:** +- Chat and messaging. +- Tasks where the model picks the next step. +- Real-time features with connected clients. +- Background work that fits in the [job queue](/agents/concepts/durable-agents/), such as a scheduled reminder. -- Chat and messaging applications -- Quick API calls and responses -- Real-time collaborative features -- Tasks under 30 seconds -- One durable Think chat turn with [`submitMessages()`](/agents/harnesses/think/programmatic-submissions/#submitmessages) +Add a Workflow when the agent starts a process that: -**Use Agents with Workflows for:** +- Has many steps, and each step must not run twice, such as a payment followed by a booking. +- Runs for hours or days, such as a data pipeline or a report. +- Waits for an outside event, such as a person's approval. -- Data processing pipelines -- Report generation -- Human-in-the-loop approval flows -- Tasks requiring guaranteed delivery -- Multi-step operations with retry requirements +Use a Workflow without an agent for background jobs that need no model and no conversation, such as data synchronization. -**Use Workflows alone for:** +## How an agent and a Workflow communicate -- Background jobs with or without user approval -- Scheduled data synchronization -- Event-driven processing pipelines +Any agent can start a Workflow through its [Workflow binding](/workflows/build/trigger-workflows/), and pass its own name in the parameters. The Workflow then reaches the agent back by name, with `getByName()` on the agent's Durable Object binding, and calls its methods over RPC. -## How Agents and Workflows communicate +A common pattern: -The `AgentWorkflow` class (imported from `agents/workflows`) provides bidirectional communication between Workflows and their originating Agent. +1. A tool call in the agent starts a Workflow, and returns the instance ID to the model. +2. The Workflow runs its steps. After each step, it calls a method on the agent to record progress. +3. The agent pushes the progress to connected clients. +4. When the Workflow finishes, it calls the agent with the result. The agent can start a new turn to tell the user. -### Workflow to Agent +Calls from a Workflow back to the agent are not steps, so a retry can repeat them. Make them safe to repeat, for example by keying each update on the step name. -Workflows can communicate with Agents through several mechanisms: +## On the `Agent` class -- **RPC calls**: Directly call Agent methods with full type safety via `this.agent` -- **Progress reporting**: Send progress updates via `this.reportProgress()` that trigger Agent callbacks -- **State updates**: Modify Agent state via `step.updateAgentState()` or `step.mergeAgentState()`, which broadcasts to connected clients -- **Client broadcasts**: Send messages to all WebSocket clients via `this.broadcastToClients()` +`AgentWorkflow` from `agents/workflows` exists only for the `Agent` class. It takes the `Agent` that started it as a typed stub, and adds: - +- `runWorkflow()` on the agent, which starts a Workflow and tracks it in the agent's database. +- Progress callbacks, such as `onWorkflowProgress()` and `onWorkflowComplete()`. +- Durable steps that update the agent's state, such as `step.mergeAgentState()`. +- Approval helpers: `waitForApproval()` in the Workflow, and `approveWorkflow()` and `rejectWorkflow()` on the agent. -```ts -// Inside a workflow's run() method -await this.agent.updateTaskStatus(taskId, "processing"); // RPC call -await this.reportProgress({ step: "process", percent: 0.5 }); // Progress (non-durable) -this.broadcastToClients({ type: "update", taskId }); // Broadcast (non-durable) -await step.mergeAgentState({ taskProgress: 0.5 }); // State update (durable) -``` - - - -### Agent to Workflow - -Agents can interact with running Workflows by: - -- **Starting workflows**: Launch new workflow instances with `runWorkflow()` -- **Sending events**: Dispatch events with `sendWorkflowEvent()` -- **Approval/rejection**: Respond to approval requests with `approveWorkflow()` / `rejectWorkflow()` -- **Workflow control**: Pause, resume, terminate, or restart workflows -- **Status queries**: Check workflow progress with `getWorkflow()` / `getWorkflows()` - -## Durable vs. non-durable operations - -Understanding durability is key to using workflows effectively: - -### Non-durable (may repeat on retry) - -These operations are lightweight and suitable for frequent updates, but may execute multiple times if the workflow retries: - -- `this.reportProgress()` — Progress reporting -- `this.broadcastToClients()` — WebSocket broadcasts -- Direct RPC calls to `this.agent` - -### Durable (idempotent, won't repeat) - -These operations use the `step` parameter and are guaranteed to execute exactly once: - -- `step.do()` — Execute durable steps -- `step.reportComplete()` / `step.reportError()` — Completion reporting -- `step.sendEvent()` — Custom events -- `step.updateAgentState()` / `step.mergeAgentState()` — State synchronization - -## Durability guarantees - -Workflows provide durability through step-based execution: - -1. **Step completion is permanent** — Once a step completes, it will not re-execute even if the workflow restarts -2. **Automatic retries** — Failed steps retry with configurable backoff -3. **Event persistence** — Workflows can wait for events for up to one year -4. **State recovery** — Workflow state survives infrastructure failures - -This durability model means workflows are well-suited for tasks where partial completion must be preserved, such as multi-stage data processing or transactions spanning multiple systems. - -## Workflow tracking - -When an Agent starts a workflow using `runWorkflow()`, the workflow is automatically tracked in the Agent's internal database. This enables: - -- Querying workflow status by ID, name, or metadata with cursor-based pagination -- Monitoring progress through lifecycle callbacks (`onWorkflowProgress`, `onWorkflowComplete`, `onWorkflowError`) -- Workflow control: pause, resume, terminate, restart -- Cleaning up completed workflow records with `deleteWorkflow()` / `deleteWorkflows()` -- Correlating workflows with users or sessions through metadata - -## Common patterns - -### Background processing with progress - -An Agent receives a request, starts a Workflow for heavy processing, and broadcasts progress updates to connected clients as the Workflow executes each step. - - - -```ts -// Workflow reports progress after each item -for (let i = 0; i < items.length; i++) { - await step.do(`process-${i}`, async () => processItem(items[i])); - await this.reportProgress({ - step: `process-${i}`, - percent: (i + 1) / items.length, - message: `Processed ${i + 1}/${items.length}`, - }); -} -``` - - - -### Human-in-the-loop approval - -A Workflow prepares a request, pauses to wait for approval using `waitForApproval()`, and the Agent provides UI for users to approve or reject via `approveWorkflow()` / `rejectWorkflow()`. The Workflow resumes or throws `WorkflowRejectedError` based on the decision. - -### Resilient external API calls - -A Workflow wraps external API calls in durable steps with retry logic. If the API fails or the workflow restarts, completed calls are not repeated and failed calls retry automatically. - - - -```ts -const result = await step.do( - "call-api", - { - retries: { limit: 5, delay: "10 seconds", backoff: "exponential" }, - timeout: "5 minutes", - }, - async () => { - const response = await fetch("https://api.example.com/process"); - if (!response.ok) throw new Error(`API error: ${response.status}`); - return response.json(); - }, -); -``` - - - -### State synchronization - -A Workflow updates Agent state at key milestones using `step.updateAgentState()` or `step.mergeAgentState()`. These state changes broadcast to all connected clients, keeping UIs synchronized without polling. +For the full API, refer to [Run Workflows](/agents/agent-class/run-workflows/). ## Related resources diff --git a/src/content/docs/agents/concepts/workspace.mdx b/src/content/docs/agents/concepts/workspace.mdx new file mode 100644 index 00000000000..0a507e7f0fb --- /dev/null +++ b/src/content/docs/agents/concepts/workspace.mdx @@ -0,0 +1,87 @@ +--- +title: Workspace +description: A workspace is an agent's durable working directory, provided by Cloudflare Computer. Understand where its files live, how code runs on them, and how harnesses use it. +pcx_content_type: concept +sidebar: + order: 6 +products: + - agents +--- + +import { LinkCard, TypeScriptExample } from "~/components"; + +A workspace is an agent's working directory. The agent reads and writes files in it, runs code against those files, and keeps them between turns. A coding agent keeps a repository there. A research agent keeps notes and downloaded pages. + +On Cloudflare, [Cloudflare Computer](https://github.com/cloudflare/computer) provides the workspace. You create a `Workspace` from `@cloudflare/computer`. + +## Files live in the Durable Object + +A `Workspace` stores its files in the Durable Object's own SQLite database. The files survive restarts, evictions, and deploys, and they belong to one agent instance. There is no separate storage service to configure. + +`workspace.fs` works like `node:fs/promises`, with methods such as `readFile`, `writeFile`, `mkdir`, `readdir`, `rm`, and `grep`. + + + +```ts +import { DurableObject } from "cloudflare:workers"; +import { Workspace } from "@cloudflare/computer"; +import { WorkerJavaScriptBackend } from "@cloudflare/computer/backends/worker-javascript"; + +export class Assistant extends DurableObject { + readonly workspace = new Workspace({ + storage: this.ctx.storage, + backends: [new WorkerJavaScriptBackend({ loader: this.env.LOADER })], + }); + + async saveNote(text: string) { + await this.workspace.fs.writeFile("/workspace/notes.md", text); + return this.workspace.fs.readdir("/workspace"); + } +} +``` + + + +A workspace can also mount read-only files. An `R2Bucket` mount shows the contents of an R2 bucket. A `WorkerBundle` mount shows files that ship inside your Worker, such as templates or reference documents, and updates them on each deploy. + +## Code runs next to the files + +`workspace.runtime.exec()` runs code against the workspace files. The code runs in a runtime, called a backend, that you register on the workspace. + +Cloudflare Computer has three backends. All of them work on the same files: + +| Backend | Runs | Status | +| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------ | +| `WorkerJavaScriptBackend` | A JavaScript module in a fresh, isolated [Dynamic Worker](/dynamic-workers/), with the workspace as `node:fs/promises` and host modules such as `ws:git` | Stable | +| `WorkerShellBackend` | Shell commands in a Dynamic Worker, through a bash interpreter written in JavaScript | Experimental | +| `ContainerBackend` | Shell commands in a [Container](/containers/), with a full Linux userland. The workspace files are mounted as a real filesystem. | Experimental | + +The Dynamic Worker backends start in milliseconds and need a Worker Loader binding. Use the container backend when the agent needs real binaries, such as a compiler or `pandoc`. + +A workspace without a backend still has its files. Add a backend only when the agent needs to run code. + +## A plain field, not a capability + +A `Workspace` is a plain field on the Durable Object. You do not attach it with `lifecycle.use()`, and it does not need the Lifecycle. It takes the object's storage in its constructor, and the agent and its tools call it directly. + +Because it is a plain field, any harness can use the same workspace. The harness gives the model tools that work on it. + +## How harnesses use the workspace + +- **The model sees tools.** Cloudflare Computer ships tools that work on a workspace, such as `read`, `write`, `edit`, `find`, `grep`, and `exec`. Each tool has an adapter for each harness: `@cloudflare/computer/tools/pi-ai` for the Pi harness, and `@cloudflare/computer/tools/ai-sdk` for the AI SDK and Think. +- **The harness connects the workspace.** Each harness page explains how to connect a workspace. +- **Think has one built in.** `this.workspace` in Think is a Cloudflare Computer `Workspace`, and Think adds the workspace tools to every turn. + +## Related resources + + + +