Skip to content

Latest commit

 

History

History
450 lines (324 loc) · 47 KB

chat-shared-layer.md

File metadata and controls

450 lines (324 loc) · 47 KB

Chat Shared Layer

Shared streaming, persistence, and protocol primitives for the cf_agent_chat_* WebSocket protocol. Lives in packages/agents/src/chat/ and is consumed by both @cloudflare/ai-chat (the stable chat agent) and @cloudflare/think (the opinionated assistant base class).

Problem

@cloudflare/ai-chat and @cloudflare/think both implement the same WebSocket chat protocol and share fundamental streaming/persistence concerns, but they live in separate packages with no shared code path. Think was forced to fork message-builder.ts (with a drift warning comment) and reimplement sanitization because agents — the only package both depend on — didn't have these primitives.

This led to:

  • Duplicated chunk-to-message logic (applyChunkToParts) across two packages, with a comment warning about drift risk
  • Duplicated sanitization (OpenAI metadata stripping, row-size enforcement) with subtle behavioral differences
  • Duplicated wire protocol constants (MSG_CHAT_* strings matching MessageType values)
  • Duplicated metadata handling (the start/finish/message-metadata switch that applyChunkToParts doesn't cover) in three separate code paths: ai-chat server, ai-chat client, and Think server

On the ai-chat side, index.ts and react.tsx already mixed too many concerns together — streaming, reconciliation, persistence, broadcasting, turn management — making the code difficult to modify and reason about. The server has only grown since (today ~7.9k lines, with durable chat-recovery layered on); the React hook has since moved into agents/chat/react so both packages share it.

Architecture

packages/agents/src/chat/          ← shared foundation
  index.ts                         barrel exports
  message-builder.ts               applyChunkToParts, getPartialStreamText + types
  tool-output-truncation.ts        provider-executed tool payload truncation
  stream-accumulator.ts            StreamAccumulator class
  turn-queue.ts                    TurnQueue class
  chat-turns.ts                    ChatTurns: the turn core both hosts run on (owns the queue, aborts,
                                   submit concurrency, continuation, pre-stream set and apply chain)
  admissions.ts                    ChatAdmissions: a client request's durable record, and its replay
                                   after a reset
  server-turn.ts                   runServerTurn: a turn the server starts (saveMessages, continueLastTurn,
                                   the retry, a recovered turn, an agent-tool run, Think.chat())
  continuation-turn.ts             the auto-continuation turn, from the fire to the settle
  turn-failure.ts                  reportTurnFailure: the order of a failure report
  turn-stop.ts                     isTurnStopped: whether a turn's own signal stopped it
  turn-fiber.ts                    ChatTurnFibers: a turn body inside the host's recovery fiber
  before-turn.ts                   what a turn settles in the transcript before the model is called
  repair-transcript.ts             settle interrupted tool calls, strip trailing reasoning, store a repair
  request-context.ts               ChatRequestContext: the stored client tools and body
  agent-tool-runs.ts               AgentToolRuns: an agent-tool child run (life, cancel, tail, reconcile)
  agent-tool-run-store.ts          the SQL store behind AgentToolRuns
  submit-concurrency.ts            SubmitConcurrencyController
  broadcast-state.ts               broadcastTransition state machine
  continuation-state.ts            ContinuationState
  auto-continuation-controller.ts  AutoContinuationController (barrier timer + double-fire guard)
  async-helpers.ts                 TIMED_OUT, awaitWithDeadline, drainInteractionApplies
  abort-registry.ts                AbortRegistry
  resumable-stream.ts              ResumableStream (chunk replay over the Streams capability)
  sql-batch.ts                     bound-param batching for IN-clause deletes
  connection.ts                    sendIfOpen WS send guard
  client-tools.ts                  ClientToolSchema, createToolsFromClientSchemas
  protocol.ts                      CHAT_MESSAGE_TYPES constants (chat + resume + tool + recovery)
  wire-types.ts                    MessageType enum, wire message types, ChatTurnOutcome
  parse-protocol.ts                parseProtocolMessage
  tool-state.ts                    tool-part update / interaction helpers
  agent-tools.ts                   agent-tool-as-child event state + broadcast snoop (interceptAgentToolBroadcast)
  message-reconciler.ts            reconcileMessages, resolveToolMergeId, reconcileOrphanPartial, assistantContentKey
  orphan-store.ts                  OrphanPersistStore interface
  pre-stream-turns.ts              PreStreamTurns (accepted-but-not-streaming window, STREAM_PENDING)
  origin-message-ids.ts            originating user message ids on outgoing frames
  truncate-older-messages.ts       truncateOlderMessages / truncateOlderToolResults for model requests
  lifecycle.ts                     shared lifecycle / result / config types (MessageConcurrency, ...)
  react.tsx                        useAgentChat and tool part helpers (exported as agents/chat/react)
  ws-chat-transport.ts             WebSocketChatTransport (re-exported by transport.ts as agents/chat/transport)

  # @internal chat-recovery engine — shared by ai-chat, think, and the
  # experimental tanstack-recovery / pi-recovery adapters
  recovery.ts                      chat-fiber snapshot codec
  recovery-incident.ts             incident budget math + storage helpers
  recovery-engine.ts               ChatRecoveryEngine + adapter / wake-hook seams
  interrupted-turn.ts              planInterruptedTurn: what a turn found interrupted does next
  recovery-attempt.ts              runRecoveredTurn: the body of one recovery attempt
  recovery-route.ts                routeStreamInterruption: a live stall or transient error into recovery
  recovery-task.ts                 reserved chained Task definition for continuations
  turn-task.ts                     createChatTurnTaskDefinition (chat turns as Tasks)
  recovery-codec.ts                ChatRecoveryCodec (AISDKRecoveryCodec)
  resume-handshake.ts              ResumeHandshake stream-resume driver
  stall-watchdog.ts                iterateWithStallWatchdog

packages/ai-chat/src/              ← stable chat agent
  index.ts                         AIChatAgent (uses shared imports)
  react.tsx                        re-exports agents/chat/react
  ws-chat-transport.ts             re-exports agents/chat/transport
  types.ts                         re-exports MessageType and wire types from agents/chat

packages/think/src/                ← opinionated assistant
  think.ts                         Think (uses shared imports)
  react.tsx                        useAgentChat wrapper over agents/chat/react
  extensions/                      ExtensionManager, HostBridgeLoopback (standalone)

The directory has a few more small helpers (throttling, chunk sizing, replay batching) that are not listed individually.

Dependency direction: ai-chat → agents, think → agents. The shared layer resolves the circular dependency that caused the original fork.

Modules

message-builder.ts

applyChunkToParts(parts, chunk) → boolean — the core chunk-to-message-part builder. Mutates a UIMessage["parts"] array in place for streaming performance. Returns true if the chunk type was recognized, false for types the caller must handle (start, finish, message-metadata, error, finish-step).

This is the single most shared piece of code in the chat system. Used by:

  • StreamAccumulator.applyChunk — the higher-level wrapper, which the reply pump (pumpReply) and both hosts' orphan recovery (_persistOrphanedStream) build messages with

Key type: StreamChunkData — deliberately loose (index signature, many optionals) to match the wire format without encoding chunk-type-specific constraints. The messageMetadata field is typed as unknown (not Record<string, unknown>) to match UIMessageChunk from the AI SDK.

sanitize.ts

Row-size enforcement for chat tables that are not session storage. Message persistence in both hosts goes through agents/sessions, which sanitizes messages and offloads oversized payloads losslessly (content-addressed attachments, chunked rows) instead of truncating.

sanitizeMessage(message) → UIMessage — re-exported from agents/sessions/sanitize. Strips OpenAI ephemeral fields (itemId, reasoningEncryptedContent) from providerMetadata and callProviderMetadata, then filters truly empty reasoning parts.

enforceRowSizeLimit stays exported, deprecated, only because released Think (0.21–0.24) and ai-chat (0.10–0.11) import it. Neither host in this repo cuts a message to fit a row: Sessions splits a large message across rows and reads it back whole. AIChatAgent's _sanitizeMessageForPersistence runs _truncateProviderExecutedToolPayloads (large strings in Anthropic-style server-executed tool payloads) and then the protected sanitizeMessageForPersistence() hook.

stream-accumulator.ts

StreamAccumulator — wraps applyChunkToParts and handles the chunk types it returns false for. Manages messageId, parts, and metadata as a coherent unit.

class StreamAccumulator {
  messageId: string;
  readonly parts: UIMessage["parts"];
  metadata?: Record<string, unknown>;

  applyChunk(chunk: StreamChunkData): ChunkResult;
  toMessage(): UIMessage;
  mergeInto(messages: UIMessage[]): UIMessage[];
}

ChunkResult carries an optional ChunkAction — a discriminated union that signals domain-specific concerns without the accumulator knowing about them:

Action type When Caller handles
start start chunk with optional messageId / messageMetadata Metadata already merged by accumulator
finish finish chunk with optional finishReason Metadata already merged by accumulator
message-metadata message-metadata chunk Metadata already merged by accumulator
tool-approval-request tool-approval-request chunk Nothing: the reply is stored when it ends
cross-message-tool-update tool-output-available / tool-output-error for a toolCallId not in current parts pumpReply: the host updates the stored message
error error chunk pumpReply: the host classifies it; a terminal one ends the reply

mergeInto(messages) — produces a new message array by finding an existing message (by messageId, or walking backward for last assistant in continuation mode), then replacing or appending. This replaced the flushActiveStreamToMessages function on the client and the activeStreamRef + metadata merge pattern.

Where the accumulator is used vs. not:

  • Client (agents/chat/react.tsx, shared by both packages' React exports): Uses StreamAccumulator for broadcast/resume streams. The transport-owned path (local tab requests) still goes through useChat's built-in pipeline.
  • Both servers: every live reply is built in the reply pump's accumulator (reply-pump.ts), and orphaned partials are rebuilt through StreamAccumulator in _persistOrphanedStream.

reply-pump.ts, reply-source.ts and reply-stream.ts

pumpReply(input, host) runs one reply: start its stream, build the message, store and send each chunk, stop on a stop, a stall or an error, route a stall or a transient error to recovery, store the reply, send the terminal frame after the transcript, run the response hook. Both hosts call it for every reply. chat-turn-core.md has the order of work and the decisions (D118 to D139).

A host passes a ReplyPumpHost: send (a frame to sockets), store (the reply, with the cutover), route (recovery), classify and describeError, settled (the response hook), and the chunk steps only one host has. A caller that wants the chunks too (Think.chat()) passes a ReplySink.

LiveReply is the reply while it streams and while it is stored. A tool result that arrives then is applied to its accumulator, and changed() makes the pump store the reply again. ended says the stream closed and the terminal frame waits, which the resume handshake reads (holdsTerminalFrames).

ReplySource is what the pump reads. uiMessageStreamSource(result) reads an AI SDK result and keeps the provider error behind an in-band error chunk. responseSource(response, body, requestId) reads an onChatMessage Response: SSE lines (a line may span two reads) or plain text as one text part.

ReplyStreams writes a reply's chunks to ResumableStream. It releases the tabs parked on a request when its stream starts and the tabs offered it when it ends, flushes a tool call or result at once and text deltas with the first and every tenth, and lets a host record the request's result in the transaction that settles the stream (Think's submissions).

chat-turns.ts

ChatTurns is the turn core AIChatAgent and Think both construct. It owns the state a host needs to run one turn at a time (TurnQueue, AbortRegistry, SubmitConcurrencyController, ContinuationState, AutoContinuationController, PreStreamTurns, and the tool-result apply chain) and the rules across them. Each rule has one method, and most are thin calls into the files below.

How a turn starts:

  • runClientRequest() runs one client chat request in the order both hosts follow: decide concurrency, accept (pre-stream mark and abort controller), persist, queue, the superseded and debounce checks, end a request cancelled meanwhile without calling the model, run the turn, settle. The host supplies the steps as a ClientChatRequest.
  • runServerTurn() runs a turn the server starts. See server-turn.ts.
  • runContinuationTurn() runs the turn a tool result or approval scheduled. See continuation-turn.ts.
  • decideSubmit(), awaitSubmitTurn() and settlePreStreamTurn() cover the overlapping-submit checks.

While a turn runs:

  • turnResetGuard() tells a running turn whether the chat was cleared since it was admitted, so it neither streams into the cleared chat nor persists there.
  • applyInteraction() applies tool results and approvals one at a time. Only one that settled its call schedules a continuation, targeted at that call's message, and not when a stop landed while it was applied.
  • settleBeforeTurn() settles what must not reach the model and stores what changed. continuationWaitsOnClient() says whether a continuation has anything to continue yet. See before-turn.ts.
  • settleInterruptedReply() and settleBeforeRecovery() settle a cut-off reply before it is stored, and before a recovery continues it.
  • streamStarted(), streamEnded() and replyFinalized() are the points a host reports from its reply pipeline.
  • reportTurnFailure() tells clients and the app about a turn that failed before its stream. See turn-failure.ts.
  • isTurnStopped() (turn-stop.ts) is how every outcome decides between aborted and an error: the turn's own signal aborted, for anything but a stall. What a stopped turn throws is not an error.

Stop, clear and idle:

  • cancel(id) stops the request's turn, queued or running, and a recovery attempt registered for it with beginRecoveryAttempt(rootId). stopAll() stops every request, and linkExternal() links a caller's signal. A stop that stops the running turn drops the continuations that were waiting when it landed. runtimeAbort() is for an abort the runtime does itself, such as the stall watchdog, which drops nothing.
  • reset() tears all of it down in one synchronous step for a chat clear.
  • waitForIdle() and waitUntilStable() define idle and stable: no turn, no submit in flight, no tool result being applied, no continuation about to fire.

The host passes a ChatTurnsHost: the transcript, whether a reply is streaming, the reply being streamed, the names of the tools a client runs, whether a resumable stream is active, keepAliveWhile, an id generator, and fireContinuation. What a turn does (the model call, streaming and persisting the reply) is still host code, in one turn body per host for every server-started turn (AIChatAgent._runServerTurnReply, Think._runModelTurn). chat-turn-core.md has the differences that were settled on the way and what is still host code.

Both hosts keep their old private field names (_turnQueue, _continuation, _abortRegistry / _aborts, and so on) as aliases of the core's parts.

admissions.ts

ChatAdmissions keeps an accepted client request across an isolate reset. runClientRequest writes a record in cf_agents_chat_admissions before the request's messages, and the record is deleted when the turn's fiber is durably accepted, when recovery picks the turn up, or when the request ends. A stop is written on the record, and a clear deletes every record. resume() replays the records a reset left, in order and with their concurrency decisions restored, once no recovery is pending. A new request replays them first. saveMessages and continueLastTurn have no record: they store nothing until their turn starts.

server-turn.ts

runServerTurn runs a turn the server starts: saveMessages, continueLastTurn, the retry, a recovered turn, an agent-tool run, and Think.chat(). It captures the queue generation, creates the abort controller and links the caller's signal, queues the turn, and at the front of the queue runs the host's prepare, persist and run, checking for a reset and a stop before each. A turn stopped before its messages are stored stores nothing, and a turn stopped before run never calls the model.

mapServerTurnOutcome decides the status the caller gets. A reset gives skipped, a stop before any reply gives aborted, an error stays an error, and what the reply path reported stands. A skipped result carries a reason: cleared, nothing-to-continue, or awaiting-client for a continueLastTurn() whose reply still waits on a client. pinnedOr lets a caller pin the tools and body a turn runs with. A pinned context is this turn's only: it is never written to the stored request context. An aborted result says why in reason: stopped, or interrupted for a reply handed to recovery.

continuation-turn.ts

The auto-continuation turn, from the moment it fires to the moment it settles.

  • runContinuationTurn creates the abort signal when the continuation fires, queues the turn, claims the continuation when the turn starts, runs the host's turn body, reports a failure before the stream, and settles. A continuation with no connection is the same runner with nothing to claim.
  • claimContinuation gives four reasons a continuation does not run: it was fired for another turn, the conversation moved on, the reply already went on to its answer (transcriptEndsInAnswer), or the reply still waits on a client. A dropped continuation is reported to the host with the reason (chat:continuation:dropped).
  • settleContinuationTurn releases only what the turn owns and starts the follow-up a result deferred while it ran.
  • dropWaitingContinuations is what a stop of the running turn calls.

The tools and body a continuation runs with are not copied onto it. The host reads the stored request context when the turn starts.

before-turn.ts and repair-transcript.ts

A provider rejects a request that holds a tool call with no result, and Anthropic rejects an assistant message that ends in a thinking block. These two files keep both out of a request.

  • repairTranscriptBeforeTurn settles every unanswered call in a message a later message follows, whoever owns it, and an approved call that never ran. A turn that starts a new reply treats the last message the same way. A continuation turn keeps, in the message it continues, a call to a tool the client sent a schema for and an approval request, and reports them as keptToolCallIds. A turn that kept any does not call the model.
  • settleInterruptedReply settles a reply whose stream was cut off, before it is stored. A call a client is known to own is kept.
  • stripTrailingReasoning removes the reasoning an assistant message ends in. It runs inside both of the above.
  • settleInterruptedPart (message-builder.ts) closes a text or reasoning part an interruption left streaming. Both hosts apply it to the message a continuation extends, so the continuation's parts follow the cut-off ones in order.
  • replyIsEmpty says whether a reply holds nothing a client can show and nothing a model request can carry. Such a reply is not stored. The before-turn repair and the settle before a recovery remove a stored one through the sink, and the recovery then retries the question.
  • removeEmptyReplyToContinue is what continueLastTurn() calls first: a last reply that holds nothing is removed, and the host answers the question again.
  • chunkMustBeStoredNow (recovery-codec.ts) says which stream chunks go to storage at once: a tool call, before the tool runs, and a settled tool result.
  • interruptedToolPartAsError is the default for the hosts' repairInterruptedToolPart hook. Its text says what is known about the call.
  • persistRepairedTranscript stores what a repair changed and emits chat:transcript:repaired, through a RepairedTranscriptSink the host supplies.

request-context.ts

ChatRequestContext owns the stored client tools and body that later turns run with. A chat request replaces the context whole when its turn starts, and one that sends no client tools clears the stored ones. A tool result replaces the stored tools only when it settled its call and listed some, and not when the context was cleared or replaced while the result was applied. Every change is written through, and a value equal to what is stored is not written again. The host passes a store with get, set and delete.

agent-tool-runs.ts

AgentToolRuns owns an agent-tool child run in both hosts, over one SQL store (agent-tool-run-store.ts). It starts the run and binds its request id before the turn queues, writes the terminal status once, cancels only the run's own turn, keeps a run whose reply was cut off open until chat recovery finishes its turn, and reconciles a run an earlier isolate started. It also serves what the parent reads: inspect, chunks, tail and progress.

protocol.ts

CHAT_MESSAGE_TYPES — plain string constants for the wire protocol message types, including STREAM_PENDING (cf_agent_stream_pending) and CHAT_RECOVERING (cf_agent_chat_recovering). Think uses these directly. The MessageType enum with the same values lives next to them in wire-types.ts; @cloudflare/ai-chat/types re-exports it.

message-reconciler.ts

Pure functions for aligning client messages with server state during persistence. Both @cloudflare/ai-chat and @cloudflare/think consume reconcileMessages and resolveToolMergeId: a client can post an optimistically-minted assistant snapshot (e.g. while a prior tool call is still streaming), so reconciling it against the server's current path maps client IDs onto server IDs and lets stale client tool states pick up the server's outputs — without it, an INSERT-OR-IGNORE-by-ID persist would write a duplicate orphan assistant row.

reconcileMessages(incoming, serverMessages, sanitize?) — two-stage pipeline:

  1. Tool output merge: When the server has output-available for a tool that the client still shows as input-available, approval-requested, or approval-responded, adopt the server's output. This handles the case where the client sends stale tool states.

  2. ID reconciliation (two-pass):

    • Pass 1: Exact ID matches between incoming and server, claiming server indices
    • Pass 2: Content-key matching for non-tool assistant messages using JSON-serialized sanitized parts. Prevents duplicate rows when the AI SDK assigns a different local ID than the server.

resolveToolMergeId(message, serverMessages) — per-message ID resolution by toolCallId. If a tool call ID exists in a server message with a different ID, adopt the server's ID. Called during persistence to prevent duplicate rows.

reconcileMessages and resolveToolMergeId are shared — both hosts call them (Think._handleChatRequest reconciles incoming messages; Think._persistIncomingMessage resolves assistant tool-merge IDs). The module also exports reconcileOrphanPartial(existing, incoming) — the orphan-persist (c) merge primitive (shared; ai-chat is the only consumer today). It is described with the rest of the orphan path in recovery-engine.ts.

recovery-engine.ts, recovery-attempt.ts and recovery-route.ts

runRecoveredTurn (recovery-attempt.ts) is the body of a recovery attempt in both hosts, and routeStreamInterruption (recovery-route.ts) routes a live stall or transient error into recovery, reading Retry-After from the error. The engine section below describes the orchestration around them.

ChatRecoveryEngine owns the shared durable chat-recovery orchestration — the sequence both AIChatAgent and Think run when a Durable Object wakes and finds an interrupted chat turn (a chat-turn Task run, on a root agent or a routed facet, that died mid-stream from hibernation, process death, or deploy churn). This state machine was previously duplicated across both packages, and the duplication was already drifting (better fixes landing in one but not the other).

Durable chat recovery is an invariant in both hosts: every chat entry path runs inside a recovery fiber. ChatRecoveryConfig accepts true or a tuning object, not false; previously compiled JavaScript that still supplies false is resolved to the default configuration. This guarantees that agent-tool child inspection can use durable recovery state after a restart instead of relying on instance-local abort controllers or stream managers.

Two host-supplied seams:

  • ChatRecoveryAdapter — the incident/budget I/O the engine drives (read/write/sweep incidents, read progress, emit lifecycle events, resolve the recovery stream, give-up/exhaust). Stable across a session.
  • ChatFiberWakeHooks — the per-wake "divergent organs": the latest stored message, whether a partial holds anything the host would store, the base persist gate, persistOrphanedStream, completeRecoveredStream, and Think's submission steps (scheduleData, onStreamEnded, onSkipped). Passed per recoverInterruptedTurn call so the adapter stays focused. The retry/continue/skip decision is planInterruptedTurn (interrupted-turn.ts), the same for every host.

The engine owns the lifecycle and its ordering invariants: resolve stream / reconstruct partial → kind (interruptedTurnKind) → open incident → if the budget is exhausted, persist the settled partial before sealing (so non-idempotent tool results aren't discarded, #1631) and terminalize → else (inside a failed-on-throw guard) invoke onChatRecovery, apply the shared persist gate (persist !== false || hasSettledToolResults), complete the live stream, then plan the turn (planInterruptedTurn) and schedule it or skip. The budget math is the pure evaluateChatRecoveryIncident. experimental/pi-recovery is a third adapter implementation driving a non-AI-SDK codec — the forcing function that keeps the engine host-agnostic.

recoverInterruptedTurn takes the turn as its record left it: the request id, the unwrapped snapshot, the stash data and the run's creation time (InterruptedChatTurn). A chat-turn Task run replayed with no live closure reaches it through the host's _recoverChatTurn, which ChatTurnTaskHooks.recover calls. A chat fiber row an older version left reaches the same method through the host's _handleInternalFiberRecovery override, which also asks Think's messenger runtime first about its reply fibers. Hosts unwrap the snapshot themselves, so the engine never reads a fiber.

Orphan-persist seams (persistOrphanedStream's internals). The engine owns whether to persist; the host owns how, in four steps:

ReplyStreams.persistOrphan runs the whole path for both hosts:

Step Where What
(a) chunks → parts core rebuild via StreamAccumulator; a reply that extended a stored message is replayed onto a copy of its parts from when the stream started
(b) target id core the message id recorded on the stream; an old stream with none takes the host's legacyMessageId
(c) merge onto existing core, host mergeLegacy the rebuilt reply replaces the stored message but keeps a stored tool part that got as far; a stream that holds only part of the message (no recorded id, a continuation from before the base part count, or a rebuild that does not start with what the stored message holds, as a stream imported from AIChatAgent 0.8.4 does) takes the host's mergeLegacy (AIChatAgent: reconcileOrphanPartial)
(d) upsert by id host store an OrphanPersistStore write; appendMessage gets the stream's parent id

In (c) a stored tool part wins over the rebuilt one when it has got at least as far (a result beats an approval, an approval beats a call): a stream has no producer once it is orphaned, so a tool result or an approval that arrived since was written to the stored message, never to the stream. A result the stream itself carries for a call the message held before (a continuation's) is further on, and the rebuilt part stays.

Continuation attempts run as steps of a chat-turn Task run: the run of the turn being recovered, or one started only for the attempt (chat-turn-core.md, "Where an attempt runs"). A run started for a first schedule joins by incident identity; a stable-state retry that its attempt's run cannot keep gets a separate run; delays are step.sleep. The run calls the existing bounded _chatRecoveryContinue / _chatRecoveryRetry entry point; both hosts run it through the shared dispatchChatRecoveryToHandoff, which returns at model handoff so a long turn never blocks the Lifecycle job loop and registers the turn as tracked alarm work, at a root and in a facet alike: a facet's runs execute under its own alarm pass, driven by its root (alarm-coordination.md). A platform failure before handoff propagates through the current Task or compatibility schedule; after handoff that execution has settled, so the detached continuation enqueues exactly one replacement attempt. The incident record remains the recovery state machine.

Every attempt that can run heavy work (the replay of an interrupted turn run, and each _chatRecoveryContinue / _chatRecoveryRetry callback through ChatRecoveryEngine.runRecoveryAttempt) records itself on the incident as an attemptsInFlight entry, confirmed with storage.sync(), and removes it when it finishes. An isolate killed by a memory-limit reset cannot write anything, so the next attempt counts entries left by another isolate in interruptedAttempts, and maxInterruptedAttempts seals the turn. Nothing is counted on the failure path. See rfc-chat-recovery-interrupted-attempts.md.

A facet's turns and recovery attempts run on Tasks too: the run and its step journal live on the facet, and Tasks mirrors its wake to the root's alarm. Legacy recovery schedule rows and legacy chat fiber rows use the same entry points and drain without migration.

Full design + point-in-time decision record: rfc-chat-recovery-foundation.md.

Key decisions

Why agents/chat and not a new package

Both ai-chat and think already depend on agents. Adding a new package would create another dependency edge and another build/publish step. The agents package already has subdirectory exports (agents/mcp, agents/react, etc.), so agents/chat follows the established pattern.

Why the accumulator signals actions instead of handling them

The accumulator doesn't know about SQLite, WebSockets, or broadcasting. It signals via ChunkAction and the caller decides what to do. This keeps the accumulator testable as a pure data structure and reusable across contexts that handle actions differently (the server stores a result for an earlier message, the client ignores it; the server sends errors on the wire, the client logs them).

Why reconciliation is shared

Both hosts face client/server ID mismatch, so the pure reconciler functions live in agents/chat and both consume them:

  • AIChatAgent must accept whatever IDs the AI SDK generates on the client side, and the useChat hook's internal state management can produce ID mismatches during streaming, tool interactions, and page refreshes.
  • Think persists through Session (INSERT OR IGNORE-by-ID for user messages, upsert for assistant), which is idempotent by ID — but a client can still post an optimistically-minted assistant snapshot mid-turn. Reconciling it against the server's active path maps the client ID onto the server's and prevents a duplicate orphan assistant row.

Why StreamChunkData.messageMetadata is unknown

The AI SDK's UIMessageChunk types messageMetadata as unknown. If StreamChunkData used Record<string, unknown>, passing a UIMessageChunk directly to applyChunkToParts would fail type checking. The accumulator uses an asMetadata() helper to safely narrow unknown to Record<string, unknown> at runtime.

Tradeoffs

The accumulator creates a new message on every toMessage() / mergeInto() call. This is intentional for immutability (React needs new references for re-renders), but it means the server can't use toMessage() for its shared _streamingMessage reference without breaking identity.

Wire protocol values exist as both CHAT_MESSAGE_TYPES and MessageType. Both now live in agents/chat (protocol.ts and wire-types.ts), and ai-chat re-exports MessageType, so there is one package to keep in sync, but still two declarations of the same strings.

What's next

TurnQueue (done)

TurnQueue — a serial async queue with generation-based invalidation — now lives in agents/chat/turn-queue.ts. It handles:

  • Promise-chain serialization (FIFO)
  • Generation counter with reset() (maps to ai-chat's epoch and Think's former _clearGeneration)
  • Auto-skip of stale entries (generation mismatch at the front of the queue)
  • Active request tracking (activeRequestId, isActive)
  • waitForIdle() — resolves when the queue is fully drained
  • Per-generation queued counts (queuedCount())
class TurnQueue {
  get generation(): number;
  get activeRequestId(): string | null;
  get isActive(): boolean;
  enqueue<T>(
    requestId: string,
    fn: () => Promise<T>,
    options?: EnqueueOptions
  ): Promise<TurnResult<T>>;
  reset(): void;
  waitForIdle(): Promise<void>;
  queuedCount(generation?: number): number;
}

AIChatAgent uses it through _runExclusiveChatTurn, which wraps _turnQueue.enqueue() with the onChatResponse drain and merge-map cleanup. Concurrency policies (drop/latest/merge/debounce) remain in AIChatAgent — they operate on message-specific state the queue doesn't know about. The onStale callback on _runExclusiveChatTurn lets the WS submit call site send a done:true response for turns skipped by auto-skip.

Think wraps both chat() and _handleChatRequest in _turnQueue.enqueue(), giving it proper turn serialization (previously concurrent calls could interleave on this.messages). _clearGeneration was replaced by _turnQueue.generation.

Fields moved from AIChatAgent to TurnQueue: _chatTurnQueue, _activeChatTurnRequestId, _chatEpoch, _queuedChatTurnCountsByEpoch.

Fields that stayed in AIChatAgent: _mergeQueuedUserStartIndexByEpoch, _submitSequence / _latestOverlappingSubmitSequence, _activeDebounceTimer / _activeDebounceResolve, _pendingChatResponseResults / _insideResponseHook, _pendingInteractionPromise.


Server-side StreamAccumulator (done)

AIChatAgent's live loop no longer mutates a shared _streamingMessage. Both hosts build every reply in the reply pump's accumulator, and the reply tool results land on is the pump's LiveReply. _findAndUpdateToolPart writes into the accumulator's parts in place and calls LiveReply.changed().


Broadcast stream state machine (done)

broadcastTransition — a pure state machine for the accumulator-based broadcast/resume path — now lives in agents/chat/broadcast-state.ts. It manages the StreamAccumulator lifecycle that useAgentChat's onAgentMessage handler previously tracked through scattered refs (accumulatorRef, activeStreamIdRef).

type BroadcastStreamState =
  | { status: "idle" }
  | { status: "observing"; streamId: string; accumulator: StreamAccumulator };

type BroadcastStreamEvent =
  | {
      type: "response";
      streamId: string;
      messageId: string;
      chunkData?: unknown;
      done?: boolean;
      error?: boolean;
      replay?: boolean;
      replayComplete?: boolean;
      continuation?: boolean;
      currentMessages?: UIMessage[];
    }
  | { type: "resume-fallback"; streamId: string; messageId: string }
  | { type: "clear" };

function transition(
  state: BroadcastStreamState,
  event: BroadcastStreamEvent
): TransitionResult;

The machine handles accumulator creation (including continuation context walking), chunk application, replay suppression, done/error cleanup, and produces messagesUpdate closures for the caller to apply. Side effects (sending ACKs, calling onData, setIsServerStreaming) stay in the caller.

Scope: covers only the broadcast/resume accumulator path (path B). The transport-owned path (path A — local tab requests via WebSocketChatTransport) is managed by the AI SDK's useChat and doesn't go through the state machine. The transport's resume resolver state (_resumeResolver, _resumeNoneResolver, _expectToolContinuation) stays in ws-chat-transport.ts.

What still uses independent variables: localRequestIdsRef (path A vs B switch), resumingToolContinuationRef (tool continuation re-entrancy guard), useChatHelpers.status (AI SDK lifecycle), and the transport's resolver state. These cross-cut the broadcast/transport boundary and aren't part of the accumulator lifecycle.

Server frame order: a done: true or error: true frame ends the client's stream, and a later cf_agent_chat_messages snapshot replaces the client's message list. So when a turn persists an assistant message, the server sends that transcript broadcast before the turn's terminal frames. Otherwise a message the user sends right after the turn ends is lost from the UI until the next turn. The reply pump holds the terminal frames (an in-band error frame included) until the reply is stored and the transcript sent, for both hosts, and sends an error frame instead when the store fails.

History

  • This design doc was created alongside the initial shared layer extraction.
  • No prior RFCs — the extraction was motivated by Think's fork of message-builder.ts and the growing complexity of ai-chat/src/index.ts.
  • TurnQueue extracted to agents/chat/turn-queue.ts. AIChatAgent and Think both adopt it, unifying turn serialization and the epoch/clear-generation concept.
  • Broadcast stream state machine extracted to agents/chat/broadcast-state.ts. useAgentChat's onAgentMessage handler uses broadcastTransition instead of manual accumulator/ref management.
  • Think stripped to minimal core (since superseded by the Sessions replatform below): single-session inline storage, removed multi-session API, deleted AgentChatTransport, disconnected extensions from Think class. Session module and transport deleted.
  • ResumableStream moved from ai-chat to agents/chat/resumable-stream.ts. Resume protocol constants (STREAM_RESUMING, STREAM_RESUME_ACK, STREAM_RESUME_REQUEST, STREAM_RESUME_NONE) added to CHAT_MESSAGE_TYPES. Think wired with full resume support.
  • Client tool primitives (ClientToolSchema, createToolsFromClientSchemas) moved to agents/chat/client-tools.ts. Tool protocol constants (TOOL_RESULT, TOOL_APPROVAL, MESSAGE_UPDATED) added. Think implements client-side tools with debounce-based auto-continuation.
  • Think now has: MCP waitForMcpConnections, message push on connect, feature parity with AIChatAgent's core chat experience.
  • Durable chat-recovery orchestration unified in agents/chat/recovery-engine.ts (ChatRecoveryEngine over a ChatRecoveryAdapter + per-wake ChatFiberWakeHooks); AIChatAgent, Think, and the experimental/pi-recovery fixture all drive it. The orphan-persist path was factored into named seams: (a) shared StreamAccumulator reconstruction, (b) host resolveOrphanTargetId, (c) shared reconcileOrphanPartial, and (d) OrphanPersistStore upsert backed by Sessions. See rfc-chat-recovery-foundation.md.
  • Auto-continuation barrier (#1649 / #1650) extracted to agents/chat/auto-continuation-controller.ts (AutoContinuationController). The controller owns the coalesce timer, the _barrierActive double-fire guard, and the schedule/coalesce/fire lifecycle (schedule / rearmForBatch / armTimer / fireWhenStable / activateDeferredAndReschedule / reset), parameterized by an AutoContinuationHost (stream-active signal, pending-interaction signal, incomplete-batch test, apply-drain, keepAliveWhile, and the host fire() turn pipeline). Both hosts retain thin delegating wrappers over their original method names; COALESCE_MS (50ms) is now single-sourced on the controller. Exported @internal for sibling packages. Fast-follow: Think's waitUntilStable() now consults controller.isArmed() to wait out an armed continuation, converging its idle definition with ai-chat's waitForIdle(). See rfc-chat-recovery-foundation.md.
  • Adapter-spine helpers de-duplicated (Tier A + B, pure leaf lifts, no behavior change). Three byte-identical fragments shared by both hosts now live once in agents/chat: (1) async-helpers.ts — the TIMED_OUT sentinel, awaitWithDeadline (deadline-bounded race), and drainInteractionApplies (the substrate-free interaction-apply completeness drain, parameterized by hasPending / getTail); (2) classifyAgentToolChildRecovery(storage) in recovery-incident.ts — the parent's agent-tool reattach incident scan (in-progress > failed > none precedence); (3) interceptAgentToolBroadcast(msg, hooks) in agent-tools.ts — the #1575 outgoing-frame snoop that tails an agent-tool child's progress, parameterized by an AgentToolBroadcastHooks substrate (forwarders / liveSequences / lastErrors maps, the host response-type constant, and the host run-lookup). Both hosts delegate through their existing private method names and broadcast() overrides (which keep a cheap size-guard so the common no-child path stays allocation-free, then call super.broadcast), so all call sites are untouched. The recovery-engine adapter seam (_chatRecoveryEngine / _runChatRecoveryFiber) and the genuinely product-substrate dispatch/classify/terminalize methods were deliberately left in the hosts (RFC bucket 3) for the Turns effort. See rfc-chat-recovery-foundation.md.
  • useAgentChat and WebSocketChatTransport hoisted into agents/chat/react and agents/chat/transport (#1801). @cloudflare/ai-chat/react re-exports the hook; @cloudflare/think/react wraps it.
  • Recovery continuations moved onto Tasks as chained __cf_internal_chat_recovery runs (#2194), and from there into chat-turn runs; that definition now only finishes runs an earlier version enqueued.
  • Sessions moved into a Lifecycle capability (agents/sessions, #2196). Both hosts persist through it, so row-size truncation left the message path and enforceRowSizeLimit now guards only non-session tables.
  • ResumableStream rebuilt over the Streams Lifecycle capability (agents/streams, #2173).
  • ChatTurns (agents/chat/chat-turns.ts) took over the turn coordination both hosts duplicated: the fields around TurnQueue, clear, cancel, the tool-result continuation decision, and the idle and stable waits. See rfc-chat-turn-core.md.
  • The rest of the turn loop's coordination moved into agents/chat: server-started turns (server-turn.ts), the auto-continuation turn (continuation-turn.ts), the recovery attempt and the live-interruption route (recovery-attempt.ts, recovery-route.ts), the turn fiber and the failure report (turn-fiber.ts, turn-failure.ts), agent-tool child runs (agent-tool-runs.ts), the before-turn repair (before-turn.ts) and the stored request context (request-context.ts). See chat-turn-core.md for each difference between the hosts and what was chosen.