Skip to content
AnswerWell geo Documentation

Research · 9 min read · Answerwell

Agent Tools, Detached Runs, and Programmatic Turn Control

How to delegate work to child agents as tools, run background sub-agents with progress, and admit Think turns with saveMessages, submitMessages, and runTurn.

This page summarizes Cloudflare’s Agents SDK documentation on agents as tools—running chat-capable child agents from a parent—and the related Think primitives for server-driven turns, action safety, and recovery. Together they answer how to let a parent model or workflow hand off work to an isolated sub-agent, keep that work alive after the parent turn ends, and trigger or resume chat without a live browser session.

Agents as tools: when a parent dispatches a child agent

Section titled “Agents as tools: when a parent dispatches a child agent”

Agents as tools let one chat agent call another as part of its work. The child is a full sub-agent with its own Durable Object storage, messages, tools, resumable stream, and drill-in URL; the parent keeps a run registry so clients can render timelines, replay after refresh, and clean up later.

Agents as tools let one chat agent dispatch another chat-capable sub-agent as part of its work. The child is a real sub-agent with its own Durable Object storage, messages, tools, resumable stream, and drill-in URL.

— Cloudflare, Agents as tools

They work with @cloudflare/think agents and AIChatAgent subclasses. AIChatAgent children run headlessly through saveMessages(), so they should use server-side tools; browser client tools are not available during an agent-tool turn unless you model that interaction as server-side state or a separate parent-mediated workflow.

Approach Use when
subAgent(...).chat() Parent code needs direct streaming RPC, and you own forwarding, cancellation, and replay
agentTool() / runAgentTool() A parent model or workflow delegates to a child and you want retained runs, event replay, abort bridging, and UI drill-in

For model-chosen delegation, register the child with agentTool() in getTools(). The generated tool calls runAgentTool, streams agent-tool-event frames on the parent WebSocket, and returns the child summary to the parent model.

runAgentTool: imperative runs, idempotency, and retention

Section titled “runAgentTool: imperative runs, idempotency, and retention”

runAgentTool() is for deterministic workflows: scheduled jobs, HTTP handlers, or fan-out where the parent code—not the model—decides when to start a child.

runAgentTool() is idempotent by runId. Passing the same runId never starts a duplicate child turn. Completed, failed, aborted, and interrupted runs are retained until you explicitly clear them.

— Cloudflare, Agents as tools

Use clearAgentToolRuns() when clearing chat history or applying retention policy. If a retained run is still starting or running, cleanup cancels the child before deleting its facet. Gate drill-in with onBeforeSubAgent() so guessed run IDs cannot spawn fresh child facets.

Think children that do workflow-style work without assistant text can override getAgentToolOutput() and getAgentToolSummary(). Persist structured output before the child turn finishes, because getAgentToolOutput() is read as soon as saveMessages() resolves.

Detached runs: background sub-agents without blocking the parent turn

Section titled “Detached runs: background sub-agents without blocking the parent turn”

By default runAgentTool() waits until the child reaches a terminal state. For long work—imports, deep research, renders—pass detached so the dispatching turn continues immediately.

By default runAgentTool() awaits the child to terminal before returning. For long-running work — large imports, video renders, deep research — that you do not want to block the dispatching turn on, pass detached.

— Cloudflare, Agents as tools

Detached behavior at a glance:

Option Role
detached: true Fire-and-forget; observe via agent-tool-event frames and onAgentToolFinish()
detached: { onFinish: "methodName" } Durable completion callback (method name only—survives eviction, not closures)
detached: { notify: true } Inject a chat message when the run finishes so the model can react
detached: { maxBudgetMs } Per-run ceiling; on expiry parent gives up and tears down the child
cancelAgentTool(runId) Idempotent cancel; delivers onFinish with status aborted

Durable completion. Delivery survives eviction and deploys: a warm fast path delivers with low latency while the isolate is alive, and a self-scheduling reconcile backbone finalizes anything the fast path missed. Delivery is exactly-once on the happy path; under a crash it is at-least-once, so onFinish handlers must be idempotent.

— Cloudflare, Agents as tools

Detached runs do not inherit options.signal; cancel explicitly with cancelAgentTool(runId).

AgentToolFailure: errors, aborts, and retryable interrupts

Section titled “AgentToolFailure: errors, aborts, and retryable interrupts”

If a run fails, aborts, or is interrupted, the tool returns structured AgentToolFailure instead of an empty success:

retryable is true only for an interrupted run — the child was reset or superseded by a deploy or parent recovery and never reached a logical outcome, so re-dispatching the same call can succeed.

— Cloudflare, Agents as tools

Branch on reason and childStillRunning (also mirrored on wire frames and useAgentToolEvents()), not on error prose—for example, re-dispatch on no-progress when the child may self-heal, but surface window-exceeded when the child was torn down.

Parent recovery re-attaches to live children after deploy or eviction, tails the stream to terminal, and uses progress-keyed waits (agentToolReattachNoProgressTimeoutMs, optional agentToolReattachMaxWindowMs). Subscribe with agents/observability on channel agentTool for agent_tool:recovery:* events (see Diagnostics channels).

A child’s inspectAgentToolRun(runId) returns the run’s current status snapshot, or null. null does not mean “failed” — it means the child has no record of that run yet.

— Cloudflare, Agents as tools

Callers treat null as “not terminal, keep watching within budget.”

Children call reportProgress() from an active agent-tool run (for example inside a tool’s execute). Ephemeral updates stream to the parent; naming a milestone promotes a signal to a durable row that survives eviction and replay.

Ephemeral signals ride the child’s own turn stream as a transient data-agent-progress part, so they re-broadcast to the parent’s connected clients and surface on AgentToolRunState.progress through useAgentToolEvents().

— Cloudflare, Agents as tools

On the parent, override onProgress() for server-side metering (best-effort; not durable after eviction). For chat agents, detached: { onMilestones } can inject synthetic status (narrate) or drive a model turn (react) when a named milestone lands.

In React, useAgentToolEvents() (with useAgent and useAgentChat) groups runs by parent tool call ID and exposes progress and milestones—see Client SDK and Agents as tools.

After silence following at least one progress signal, the reconcile backbone may seal a detached run as interrupted with reason: "no-progress" (detachedNoProgressBudgetMs, default one hour). A child that never reports progress is bounded only by detachedMaxBudgetMs (default 24h)—slow work is not abandoned merely for being slow.

Think actions: idempotency, authorization, and reply attachments

Section titled “Think actions: idempotency, authorization, and reply attachments”

Side-effecting actions in Think use a durable ledger separate from agent-tool runs but follow the same “at-most-once on the happy path” mindset.

When an action declares an idempotencyKey, Think records the settled result in a durable ledger keyed by action:<name>:<key>. If the same key is seen again — on a recovery retry, a reconnect, or a duplicate inbound event — Think returns the stored result without re-running execute.

— Cloudflare, Actions

Use stable domain identifiers (order id, inbound event id)—never timestamps or random values per attempt. Without an explicit idempotencyKey, deduplication is per toolCallId only within one tool call.

Pending rows reclaim after actionLedgerPendingRetryLeaseMs (default 5 minutes) only when an explicit idempotencyKey asserts re-running is safe; otherwise stale pending returns ActionPendingError.

Declare permissions on actions; grant per turn via authorizeTurn() or per call via authorizeAction(). Denied actions surface ActionAuthorizationError before execute runs.

ctx.attachReply() records delivery metadata (email draft, card, voice note) for your channel layer; attachments do not change model-visible tool output. Read them from onChatResponse() or replyAttachments(). Record attachments from execute only—not from idempotency or approval callbacks. A ledger replay does not re-fire attachments.

Programmatic turns: saveMessages, submitMessages, and runTurn

Section titled “Programmatic turns: saveMessages, submitMessages, and runTurn”

Server code often needs to inject messages or accept work without a user clicking send. Autonomous responses and Think document the split:

Primitive Behavior
saveMessages() Persist messages and run a full model turn; awaitable when the caller can wait
persistMessages() / addMessages() Store context without starting inference
submitMessages() Durable acceptance, idempotent retry, inspect/cancel later—messages enter the session when execution starts
runTurn({ mode }) Unified admission: wait ≈ saveMessages, submit ≈ submitMessages, stream ≈ chat()

Use saveMessages() when the caller can wait for the model turn to finish. Use submitMessages() with Think when the caller needs a fast durable receipt, idempotent retry, and later status inspection.

— Cloudflare, Autonomous responses

Blocking modes cannot nest. Calling wait/stream/continuation (or the equivalent shortcut) from inside an active turn — for example, from a tool’s execute — throws, because it would deadlock the turn queue.

— Cloudflare, Think

From inside a turn, use runTurn({ mode: "submit" }) or addMessages() instead of nested blocking admission.

Webhook pattern (from Programmatic submissions):

const submission = await this.submitMessages(messages, {
idempotencyKey: payload.id,
});
return Response.json({
submissionId: submission.submissionId,
status: submission.status,
accepted: submission.accepted,
});

waitUntilStable before server-driven injection

Section titled “waitUntilStable before server-driven injection”

From schedules, webhooks, or queues, call waitUntilStable() before reading this.messages or calling saveMessages():

waitUntilStable() waits until the conversation is fully stable: No active LLM stream in progress; No pending client-tool interactions; No queued continuation turns.

— Cloudflare, Autonomous responses

Without this guard you risk stale baselines or overlapping streams. saveMessages() always queues (serialized), unlike client sendMessage() which respects messageConcurrency on AIChatAgent.

Use onChatResponse to react to turns you did not trigger; it does not nest—chained saveMessages from inside drains sequentially (Chat agents, Autonomous responses).

Durable chat recovery and human-waiting turns

Section titled “Durable chat recovery and human-waiting turns”

Think wraps turns in recoverable fibers (Durable recovery). WebSocket chat, chat(), submitMessages(), saveMessages(), and continuations can resume after Durable Object eviction.

Turns waiting on client tools or approvals are treated as waiting on a human: recovery budgets are suspended until the user responds (Chat agents, Client tools). Server tools orphaned mid-execute recover via transcript repair instead.

Override onChatRecovery() when you need provider-specific behavior (for example fetch a stored result instead of a new model call). Optionally tune chatRecovery budgets and chatStreamStallTimeoutMs for stall detection.

  • Using timestamps or request IDs as action idempotencyKey values, breaking deduplication across retries (Actions).
  • Calling saveMessages() or runTurn({ mode: "wait" }) from inside a tool execute, causing nested-blocking errors (Think).
  • Expecting browser client tools on AIChatAgent children during agent-tool turns without a server-side alternative (Agents as tools).
  • Passing a closure to detached.onFinish instead of a method name that survives eviction (Agents as tools).
  • Treating inspectAgentToolRun() === null as terminal failure (Agents as tools).
  • Injecting server-driven messages without waitUntilStable() while a stream or approval is pending (Autonomous responses).
  • Assuming onFinish exactly-once under crash without idempotent handlers (Agents as tools).
  1. Confirm the parent exposes the child via agentTool() or imperative runAgentTool(), and that duplicate runId values do not spawn second turns.

  2. Start a detached child run with reportProgress() in the child; verify live updates appear through useAgentToolEvents() and that milestones replay after refresh.

  3. Interrupt the parent Durable Object during a child run (deploy or eviction) and confirm parent recovery events on the agentTool observability channel and a terminal AgentToolFailure or completion with the expected reason.

  4. From a webhook or schedule, call submitMessages() with an idempotencyKey (retry and confirm the same submissionId), then call waitUntilStable() before server-driven saveMessages() so no user stream or tool approval overlaps.

  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page does not match your experience with the Agents SDK or Think APIs, email yimasynthetic@gmail.com with the page URL and the exact statement you believe is wrong or unclear.