Skip to content

Chat: AIChatAgent runs its turns on the chat module - #3504

Merged
mattzcarey merged 5 commits into
mainfrom
slim/push-2-switch
Nov 29, 2026
Merged

mattzcarey merged 5 commits into
mainfrom
slim/push-2-switch

Conversation

@mattzcarey

@mattzcarey mattzcarey commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

AIChatAgent's turns run on the shared chat module: submitTurn, clearChat, answerTool and chatDispatch over ChatDeps, and one turn definition, chatTurnDefinition. Its old turn engine, its recovery engine instance and its implementations of the old host interfaces are deleted. An agent-tool run on an AIChatAgent child is that child's chat turn, so the child's separate run store is deleted too. packages/ai-chat/src/index.ts goes from 4,374 lines to 1,637.

Three units, in this order: the switch group (#3298, #3361, #3475), F21 (#3487), and step (d), which removes what the switch left alive.

Why:

  • Think's harness and AIChatAgent each had their own implementation of a chat turn, its recovery and its socket protocol. This leaves one.
  • A turn is one durable Task run across attempts, so a recovered reply keeps its request id and ends once.
  • Rows a release left (a cut-off turn, a scheduled recovery, the last terminal, agent-tool child rows, a run in flight, the request context) are carried forward once at start, each with an upgrade test.

What a user can see change, each with its changeset line (.changeset/chat-turns.md, chat-recovery.md, agent-tools.md):

  • A request whose onChatMessage returns no response ends with outcome: "skipped".
  • A turn that a clear reaches, waiting or running, ends with outcome: "skipped" and keeps nothing.
  • A turn that recovery gives up on reports its end to onChatResponse once, with status: "error" and the terminal message, after onExhausted.
  • Turns store their messages directly, so a persistMessages override no longer sees a turn's writes.
  • A recovered turn keeps its request id and ends once; a tab no longer sees an end with outcome: "recovering" followed by a new request.
  • saveMessages and continueLastTurn resolve once recovery has finished the turn, with how it ended, instead of with reason: "interrupted".
  • onError hears of an onChatMessage failure once per turn.
  • Recovery no longer calls an overridden continueLastTurn or waitUntilStable.
  • chatRecovery.stableTimeoutMs is deprecated and has no effect.
  • A turn cut off before the upgrade is carried over under its request id, with the recovery budget of a new turn.
  • A stopped reply that was waiting to be retried is stored before the next request's question, and every tab is told the request ended.
  • A tool answer that arrives while a continuation runs schedules the next continuation; a stop that drops it reports its own request id.
  • An agent-tool run on an AIChatAgent child is its chat turn: a reset of the child resumes it, a cancel ends it at once, and runs a release kept carry on.
  • F21: a reply that completed is kept as stored, including one that ends in reasoning. Think leaves that trailing reasoning out of the model request; for AIChatAgent leaving it out stays the app's, as in earlier releases. A reply cut off while still reasoning is removed and its question answered again.

Five differences from main, as the lead ruled them (the follow-up unit slim/switch-pr2-completes carries the first two):

  1. A clear that reaches a streaming turn: ruled to match main. The request's end frame says aborted again (the follow-up); a request still waiting ends skipped.
  2. Recovery does not call an overridden continueLastTurn or waitUntilStable: kept, and AIChatAgent warns once at start when a subclass overrides continueLastTurn, naming onChatRecovery (the follow-up).
  3. Kept: a recovery that finds its reply waiting on the client ends at once with chat:recovery:skipped, reason awaiting_client_interaction; main waited stableTimeoutMs first.
  4. Kept: in those cases the tab gets the recovering status off before cf_agent_message_updated.
  5. Kept: a stalled stream whose recovery the app declines sends the recovering status on and then off.
    Items 3 to 5 get their changeset lines in the follow-up.

Fixed in step (d), dropped by the switch and found afterwards:

  • waitForMcpConnections had no reader after the switch. A tab's request waits for the MCP connections before onChatMessage again, with the configured timeout (default 10 s). The old tests only checked that a turn completes; the new ones record the wait.
  • A turn the alarm's memory-limit breaker seals said nothing: Tasks failed and deleted its run from outside the handler. It is now given up like a spent budget (onExhausted with out_of_memory, the terminal message, one end), through an @internal Tasks register option onSealed.
  • A sweep of every public and protected member of the pre-switch class for readers that vanished found these two and nothing else unruled.

Also in step (d): Tasks starts a cancelled lane head's successor only once the cancelled attempt has returned; a Task run struck by a platform failure in a live isolate runs at once on the next start; 196 unused names leave agents/chat's index; the released-rows carry, the agent-tool child's side and the class's host wiring move out of index.ts into sibling files as the same code.

Cost (probes/perf, local workerd, 60 rows; statements / rows written / rows read; release values from PERF-BUDGET Table 1):

  • Every AIChatAgent row is at or below the release in all three: turn-short 67 / 20 / 60 (release 102 / 26 / 79); turn-paced-20 72 / 25 / 65 (108 / 28 / 85); queued-3 294 / 91 / 338 (423 / 109 / 349); recovery-abort 176 / 70 / 232 (411 / 98 / 598); turn-slow-300 101 / 54 / 94 (192 / 56 / 169); resume-mid-stream 110 / 55 / 103 (196 / 56 / 172); startup-empty 55 / 48 / 91 (87 / 88 / 831).
  • Against main before the switch a turn makes more statements and reads more rows, and writes fewer (turn-short 67 / 20 / 60 against 56 / 25 / 49): a turn is a Task run and reads its run, its checkpoint, the stored request context and the transcript at its start. Not attributed statement by statement.
  • A paused model's buffer is written at most every 250 ms, so a reset loses at most 250 ms of what a paused model had sent.
  • ThinkHarness shares the turn definition: its prompt rows are +8 statements, +1 row written, +7 rows read against main, still under the release. Not attributed.
  • These were measured on the group; F21 adds one pass in memory, step (d) removes one promise per turn and adds one waitForConnections call per tab request (as the release had). Not re-measured on step (d)'s top.

Validated:

  • Deployed gate by verify, root and sub-agent, against main and the release: PASS on the group, on F21 and on step (d) (fault suites, reset fuzz, upgrades from the release, the facet shapes, cost flat). The MCP wait matches the release in six of six cases.
  • ai-chat's suite (949), agents' chat-host, Tasks, lifecycle and chat projects, the harness suite and Think's class suite pass on each unit's head.
  • Every fix after the first review has a test that failed first.
  • The memory-limit seal could not be reached on a deployment: a turn that runs out of memory in every attempt ends through chat recovery's own budget, and the breaker did not strike in 30 resets at the root. The seal's give-up rests on its tests (chat-host, and one on AIChatAgent itself). ThinkHarness's chat turns still lack it.

No public API is added: agents/chat stays @internal.


Devin Review

…l run is its chat turn's run

One unit, three branches that land together: `slim/chat-fn-6d` (the chat functions, #3298), `slim/chat-fn-6s1` (AIChatAgent onto them, #3361), `slim/agent-runs-r3` (R3-identity, #3475). Review `git diff slim/local-main...slim/agent-runs-r3`; each branch is the one below it plus its own commits.

`AIChatAgent`'s turns now run on the shared chat module: `submitTurn`, `clearChat`, `answerTool` and `chatDispatch` over `ChatDeps`, and one turn definition, `chatTurnDefinition`. Its old turn engine, recovery engine instance and host-interface implementations are deleted, and an agent-tool run on an `AIChatAgent` child is that child's chat turn (`agent-tool:<runId>`), so the child's separate run store and the seam between the two are deleted too.

Why:
- Think's harness and `AIChatAgent` each had their own implementation of a chat turn, its recovery and its socket protocol; this leaves one.
- A turn is one durable Task run across attempts, so a recovered reply keeps its request id and ends once.
- Rows a release left (a cut-off turn, a scheduled recovery, the last terminal, agent-tool child rows, a run in flight) are carried forward once at start, each with an upgrade test.

Kept as before the switch, each with a test: a tool answer's continuation asks the model 50 ms after the answer and a stop inside that window drops it; `tool:result`, `tool:approval`, `message:cancel`, `chat:continuation:dropped` and `chat:request:failed` are published, and a spent recovery budget publishes `chat:recovery:exhausted`; a stop during a recovered attempt turns the recovering status off; an agent-tool run under a stopped turn reports a plain abort.

What a user can see change is exactly the changeset lines (`.changeset/chat-turns.md`, `chat-recovery.md`, `agent-tools.md`); everything else matches main. The deleted tests and their successors are listed in `archive/report-limits-switch-successors.md`. No public API is added: `agents/chat` stays `@internal`, and `ChatHooks.isReplay` and `ChatTurnResult.gaveUp` are internal to it.

Cost (`probes/perf`, local workerd, 60 rows, at 826bcd46a, whose product code is the head's; release values from PERF-BUDGET Table 1, base `slim/local-main` f9564d8). Cells are statements / rows written / rows read:
- **Every `AIChatAgent` row is at or below the release in all three.** turn-short 67 / 20 / 60 (release 102 / 26 / 79); turn-paced-20, a reply of 20 chunks 50 ms apart, 72 / 25 / 65 (release 108 / 28 / 85); queued-3 294 / 91 / 338 (release 423 / 109 / 349); recovery-abort 176 / 70 / 232 (release 411 / 98 / 598); turn-slow-300 101 / 54 / 94 (release 192 / 56 / 169); resume-mid-stream 110 / 55 / 103 (release 196 / 56 / 172); startup-empty 55 / 48 / 91 (release 87 / 88 / 831).
- **Against the base (main), a turn makes more statements and reads more rows, and writes fewer:** turn-short 67 / 20 / 60 against 56 / 25 / 49; queued-3 294 / 91 / 338 against 238 / 102 / 216. A turn is a Task run now: it reads its run and its checkpoint, the stored request context and the transcript at its start, where the old engine held them in memory. I have not attributed each statement.
- A paused model's buffer is written at most every 250 ms, so a reset loses at most 250 ms of what a paused model had sent; with that a paced reply writes fewer rows than the release (25 against 28). A connect makes one more statement than the release (the lane read). `submitTurn` reads each sent message once to compare it with the stored one.
- ThinkHarness, which shares the turn definition: `harness/prompt-*` rows are +8 statements, +1 row written and +7 rows read against the base (prompt-hello 67 / 21 / 86, base 59 / 20 / 79, release 74 statements), except prompt-paced-20, which falls to 72 / 26 / 91 (base 78 / 39 / 98, release 36 rows written). I have not attributed the +8 statements.

Validated on `slim/agent-runs-r3`:
- chat-host, the chat node project, the harness suite, the whole ai-chat suite and Think's class suite pass.
- Think's harness config, test by test against the base run the same way: 16 gained; one timing test (`detached-reconcile-lane`, an alarm that must return within 15 s) failed in the full run beside two other suites and passes alone on the head.
- Each fix folded in after the last review has a test that failed first: the sub-agent count starting again for a chat turn; a given-up turn's end reaches `onChatResponse` after a reset; a `continueLastTurn` with nothing to continue sends no frame; ThinkHarness's `continue` of a finished reply calls the model; a host that runs its own tools may ask again for a call it holds.
- Deployed gate by verify, root and facet, against main and the release: owed on this head.

In a sub-agent the Lifecycle counts a job's attempts that never settled and seals the job at three. A turn is one run now, so that count would have ended a turn cut off by resets before chat recovery's own budget could. A chat attempt that finds the one before it died, mid-reply or before it streamed, counts it in the recovery budget and offers it to `onChatRecovery`, as before; it then tells Tasks, and the Lifecycle's count for that run starts again (two `@internal` members: `Tasks.interruptionsCounted`, `LifecycleJobs.attemptsCounted`).

Unit: slim/agent-runs-r3 @c1c88c257 (group: slim/chat-fn-6d @bdd3c88c8, slim/chat-fn-6s1 @9341dad6a)
…soning is left out of the model request (F21)

A stored assistant reply that ends in reasoning is no longer rewritten or removed by the before-turn repair. The turn definition hands the host two lists: `ChatModelCall.messages`, the request view with trailing reasoning left out and a reply left empty dropped, and `ChatModelCall.transcript`, the stored list.

Why:
- Anthropic rejects a request whose assistant message ends in a thinking block, so the repair used to delete that reasoning from storage.
- A model may complete a reply with reasoning only; the user then saw it disappear when they asked again, and the turn had no assistant message.

Applies to `AIChatAgent`, Think's class and the harness-backed Think. The changeset line is in `.changeset/chat-turns.md`; the chat guide and `design/chat-turn-core.md` are updated.

Cost: no extra read or write; the request view is one more pass in memory over the messages the turn already read.

Validated: ai-chat `continue-last-turn` and `chat-turn-races`, Think's `empty-reply` and `client-tools`, and the harness suite pass. Stacked on `slim/agent-runs-r3`; it lands right after that unit.

Unit: slim/inbox-f21-b @640f50be4 (applied by tree: local-main's tree == c1c88c257, the unit's base)
…dule's index

One unit, stacked branches (`slim/switch-d`, `-d2`, `-d3`, `-d4x`, `-d5x`, `slim/switch-mcp-wait-on-d`, top `slim/switch-e`), lands by its top. `packages/ai-chat/src/index.ts` goes from 3,074 to 1,623 lines (904 of code); what a user can see: the two fixes of things the switch dropped (the MCP wait, the memory-limit seal) and the two Tasks fixes below.

**Behaviour:**
- `waitForMcpConnections` is honoured again: a tab's request waits for the agent's MCP connections before `onChatMessage`, with the configured timeout (default 10 s). The switch of AIChatAgent onto the chat module had left the setting with no reader, so a turn that started while connections were restoring saw an incomplete `getAITools()`. As before the switch, `saveMessages`, continuations and tool answers do not wait; a recovered attempt of a tab's request now does.
- A chat turn the alarm's memory-limit breaker seals is given up, not dropped: what it streamed is stored, `onExhausted` is called with `reason: "out_of_memory"`, `chat:recovery:exhausted` is published, every tab gets the terminal message and `onChatResponse` hears `status: "error"`. Before the switch AIChatAgent did this from `onAlarmMemoryLimit`; after it the turn is a Tasks run that Tasks fails and deletes from outside its handler, so the chat said nothing. Tasks gets an `@internal` register option `onSealed(runId)`, called before a sealed run is failed; the chat module's `giveUpSealedTurn` does the give-up. Nothing runs for a turn that is not sealed.
- Tasks starts a cancelled lane head's successor only once the cancelled attempt has returned, so a stopped turn has stored its reply before the next turn stores its question. The chat turn definition's own wait for this is deleted.
- A Task run that a platform failure struck in a live isolate runs at once on the next start.

**Deleted:**
- One read of an agent-tool run per chunk it streams (now one per turn).
- 196 names off `agents/chat`'s index that nothing imports (381 to 185).
- ai-chat's test worker loses 987 lines only the deleted old-engine tests used.
- In `index.ts`: single-caller pass-throughs, a set of resuming tabs nothing added to, an options type nothing passed, comments describing the old engine.

**Moved out of `index.ts`, same code behind small host objects:**
- `ai-chat/src/released-rows.ts`: the carry of rows an ai-chat release left.
- `ai-chat/src/agent-tools.ts`: the agent-tool child's side and detached delivery.
- `ai-chat/src/turn-host.ts`: the class as the chat module's host (`respond`, the turn's end, `onChatResponse` delivery, the wait behind `saveMessages`).
- `agents/src/chat/agent-tool-turns.ts`: the agent-tool progress wiring and the tail asked for before a turn's stream opens.
- `requestContextFromLegacy` and `abortReasonText` out of the old engine's files, so ai-chat imports nothing defined in `chat-turns.ts`, `recovery-engine.ts` or `agent-tool-runs.ts`.

`index.ts` now holds the released API with its docs (627 comment lines), the constructor's wrappers of the app's handlers, and the wiring of the four helper objects. Two `@internal` protected members left the class: `_persistOrphanedStream` and `_orphanStore`.

Not tested with a real memory-limit kill on AIChatAgent (a chat-host test drives the seal); ThinkHarness's chat turns still have that gap.

Not here: the old turn engine's files and the 14 old host interfaces in `agents/src/chat` are still used by Think's class and go when it moves onto the harness.

Validated: ai-chat 949 of 949 at each step, the same tests; agents' chat project 1,482; chat-host, tasks, lifecycle and agent-tool worker tests; Think's class suite on `slim/switch-d`; `tsc`, oxlint, oxfmt, exports, public-API and instance-name checks. The two Tasks changes, the MCP wait, the seal's give-up and the per-chunk read each have a test that fails without them (the old MCP tests only checked that a turn completes). Cost: one promise fewer per turn. No changeset: none of these bugs was released.

Unit: slim/switch-e @a014ec45c (step (d): switch-d..d5x, switch-mcp-wait-on-d, switch-e)
… request's frame aborted (as before the switch); AIChatAgent warns once when a subclass overrides continueLastTurn; changeset lines for the kept differences
@changeset-bot

changeset-bot Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 169790b

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes changesets to release 4 packages
Name Type
agents Patch
@cloudflare/ai-chat Patch
@cloudflare/think Patch
@cloudflare/agent-think Patch

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@pkg-pr-new

pkg-pr-new Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

agents

npm i https://pkg.pr.new/agents@3504

@cloudflare/ai-chat

npm i https://pkg.pr.new/@cloudflare/ai-chat@3504

@cloudflare/codemode

npm i https://pkg.pr.new/@cloudflare/codemode@3504

hono-agents

npm i https://pkg.pr.new/hono-agents@3504

@cloudflare/shell

npm i https://pkg.pr.new/@cloudflare/shell@3504

@cloudflare/think

npm i https://pkg.pr.new/@cloudflare/think@3504

@cloudflare/voice

npm i https://pkg.pr.new/@cloudflare/voice@3504

@cloudflare/worker-bundler

npm i https://pkg.pr.new/@cloudflare/worker-bundler@3504

commit: 169790b

@agent-think

agent-think Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

🔴 agents import sizes: 2 entry points over threshold

Entry point Exports Largest gzip change Size now
🔴 agents/harness/think 1 resized +6 KiB (+2.59%) 236 KiB
🔴 agents/chat 6 resized, 31 new, 84 removed up to +2.3 KiB (+394.65%) 2.9 KiB
🟡 agents/tasks 1 resized +371 B (+2.29%) 16.2 KiB
🆕 agents/internal 1 new — 146 B
Changed exports (124)
Import Gzip change Size now
🔴 agents/harness/think#ThinkHarness +6 KiB (+2.59%) 236 KiB
🔴 agents/chat#storableRequestContext +2.3 KiB (+394.65%) 2.9 KiB
🔴 agents/chat#abortReasonText +2.2 KiB (+516.4%) 2.7 KiB
🔴 agents/chat#CHAT_REQUEST_CONTEXT_KEY +2.2 KiB (+553.2%) 2.6 KiB
🔴 agents/chat#addContinuationTarget +2.2 KiB (+495.98%) 2.6 KiB
🔴 agents/chat#requestContextFromLegacy +2.1 KiB (+399.82%) 2.7 KiB
🟡 agents/tasks#Tasks +371 B (+2.29%) 16.2 KiB
🟡 agents/chat#ChatTurns +189 B (+1.25%) 15 KiB
🆕 agents/chat#chatTurnDefinition — 134.7 KiB
🆕 agents/chat#chatDispatch — 129.2 KiB
🆕 agents/chat#startAgentToolTurn — 125.7 KiB
🆕 agents/chat#carryForwardAgentToolRuns — 125.6 KiB
🆕 agents/chat#submitTurn — 125.5 KiB
🆕 agents/chat#giveUpSealedTurn — 125 KiB
🆕 agents/chat#clearChat — 124.8 KiB
🆕 agents/chat#stopAllTurns — 124.8 KiB
🆕 agents/chat#cancelAgentToolTurn — 124.7 KiB
🆕 agents/chat#cancelTurn — 124.6 KiB
🆕 agents/chat#AgentToolTails — 4 KiB
🆕 agents/chat#resumeChat — 3.4 KiB
🆕 agents/chat#agentToolProgressEmitter — 3.3 KiB
🆕 agents/chat#agentToolTurnChunks — 3.1 KiB
🆕 agents/chat#inspectAgentToolTurn — 3 KiB
🆕 agents/chat#tailAgentToolTurn — 3 KiB
🆕 agents/chat#planInterruptedTurn — 2.8 KiB
🆕 agents/chat#chatClientView — 2.7 KiB
🆕 agents/chat#reclaimAgentToolStreams — 2.7 KiB
🆕 agents/chat#forgetTab — 2.7 KiB
🆕 agents/chat#progressCreditOf — 2.6 KiB
🆕 agents/chat#liveTurnsOf — 2.6 KiB
🆕 agents/chat#chatTurnStreamId — 2.6 KiB
🆕 agents/chat#CHAT_CLEARED — 2.6 KiB
🆕 agents/chat#releasedAgentToolRunOfRequest — 600 B
🆕 agents/chat#releasedAgentToolRunWaiting — 571 B
🆕 agents/chat#recordAgentToolProgress — 516 B
🆕 agents/chat#agentToolRunMessages — 478 B
🆕 agents/chat#agentToolTurnOf — 431 B
🆕 agents/chat#agentToolTurnId — 417 B
🆕 agents/chat#RELEASED_AI_CHAT_AGENT_TOOL_TABLES — 415 B
🆕 agents/internal#FIBER_TASK — 146 B
➖ agents/chat#AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS — —
➖ agents/chat#agentToolRunOutcome — —
➖ agents/chat#applyAgentToolEvent — —
➖ agents/chat#applyLateToolInput — —
➖ agents/chat#awaitWithDeadline — —
➖ agents/chat#broadcastTransition — —
➖ agents/chat#bumpChatRecoveryProgress — —
➖ agents/chat#CHAT_ADMISSIONS_TABLE — —
➖ agents/chat#CHAT_RECOVERING_FLAG_TTL_MS — —
➖ agents/chat#CHAT_RECOVERING_KEY — —

…and 74 more exports in the workflow artifact.

How this works

Each runtime export is bundled on its own, minified, and gzipped. Changes smaller than 100 B, or smaller than 1% and 1 KiB, are ignored. Growth over 10% or 5 KiB is marked 🔴. This report is informational and does not fail CI. The workflow artifact contains every measurement.

Compared 0d6cba3f → 169790b9 · workflow run · reported by agent-think[bot]

…verrides it: the override is looked for before Agent puts its method wrappers on the class's prototype, once per class
@mattzcarey
mattzcarey merged commit 30d843b into main Nov 29, 2026
25 of 26 checks passed
@mattzcarey
mattzcarey deleted the slim/push-2-switch branch November 29, 2026 00:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant