Repository navigation
Chat: submitTurn, clearChat, answerTool and chatDispatch over ChatDeps (4.iii, 6d, draft) - #3298
Closed
mattzcarey wants to merge 1 commit into
Closed
mattzcarey wants to merge 1 commit into
mattzcarey wants to merge 1 commit into
Conversation
|
mattzcarey
force-pushed
the
slim/chat-fn-6d
branch
from
November 26, 2026 16:47
1f3ce7f to
6aa3a11
Compare
Contributor
|
✅ agents import sizes: no significant changes ( |
agents
@cloudflare/ai-chat
@cloudflare/codemode
hono-agents
@cloudflare/shell
@cloudflare/think
@cloudflare/voice
@cloudflare/worker-bundler
commit: |
mattzcarey
force-pushed
the
slim/chat-fn-6d
branch
3 times, most recently
from
November 26, 2026 17:07
c895667 to
50bb96a
Compare
mattzcarey
force-pushed
the
slim/chat-fn-6
branch
from
November 26, 2026 17:11
e769352 to
c5dd398
Compare
mattzcarey
force-pushed
the
slim/chat-fn-6d
branch
2 times, most recently
from
November 26, 2026 17:26
242f836 to
36c01f1
Compare
mattzcarey
force-pushed
the
slim/chat-fn-6
branch
from
November 26, 2026 23:07
1d16b90 to
0d4e1ff
Compare
mattzcarey
force-pushed
the
slim/chat-fn-6d
branch
3 times, most recently
from
November 26, 2026 23:15
ab67713 to
ce1677d
Compare
mattzcarey
force-pushed
the
slim/chat-fn-6d
branch
2 times, most recently
from
November 26, 2026 23:45
89365cb to
d83717c
Compare
mattzcarey
force-pushed
the
slim/chat-fn-6
branch
from
November 26, 2026 23:51
a4ab736 to
27d8a51
Compare
mattzcarey
force-pushed
the
slim/chat-fn-6d
branch
from
November 26, 2026 23:52
d83717c to
8e0a33d
Compare
mattzcarey
marked this pull request as ready for review
November 26, 2026 23:53
mattzcarey
added a commit
that referenced
this pull request
Nov 27, 2026
… a tool answer's continuation extends the reply that holds the call (Devin on #3298)
This was referenced Nov 27, 2026
Closed
mattzcarey
added a commit
that referenced
this pull request
Nov 27, 2026
… a tool answer's continuation extends the reply that holds the call (Devin on #3298)
mattzcarey
force-pushed
the
slim/chat-fn-6d
branch
from
November 27, 2026 00:48
47bc9e6 to
e8d20c7
Compare
mattzcarey
added a commit
that referenced
this pull request
Nov 27, 2026
… a tool answer's continuation extends the reply that holds the call (Devin on #3298)
mattzcarey
force-pushed
the
slim/chat-fn-6d
branch
from
November 27, 2026 01:59
aa962bd to
3c7f3b4
Compare
mattzcarey
added a commit
that referenced
this pull request
Nov 27, 2026
… a tool answer's continuation extends the reply that holds the call (Devin on #3298)
mattzcarey
force-pushed
the
slim/chat-fn-6d
branch
from
November 27, 2026 02:26
bff6bea to
96c0d3f
Compare
This was referenced Nov 27, 2026
mattzcarey
added a commit
that referenced
this pull request
Nov 27, 2026
… a tool answer's continuation extends the reply that holds the call (Devin on #3298)
mattzcarey
force-pushed
the
slim/chat-fn-6d
branch
from
November 27, 2026 04:09
96c0d3f to
e44a940
Compare
This was referenced Nov 27, 2026
Closed
mattzcarey
marked this pull request as draft
November 27, 2026 16:13
mattzcarey
added a commit
that referenced
this pull request
Nov 27, 2026
The chat module's functions over Tasks, Streams, Sessions and WebSockets: chatDispatch, submitTurn, answerTool, cancelTurn, clearChat, resumeChat, replayTurn, and the chat-turn definition's parked tabs, live turns and stopped mark. Rebased onto main c519393 from e44a940; the one conflict (the turn's report) keeps main's stash drop and 6d's continuation and parked-tab steps.
mattzcarey
force-pushed
the
slim/chat-fn-6d
branch
from
November 27, 2026 16:13
e44a940 to
5278c07
Compare
mattzcarey
added a commit
that referenced
this pull request
Nov 27, 2026
…o main as one commit AIChatAgent runs its turns on chatTurnDefinition and chatDispatch, and its old engine is deleted. Rebased onto the rebased #3298 from f87cd85 plus verify's FIX: main merged in (#3389, #3444, #3447, #3435, #3423 resolved in chat-host.ts with turn-task's notes), F27, the stop in a retry backoff ending the turn once, a throwing onChatRecovery given up with recovery_error, and turn-task's 25baf34.
mattzcarey
added a commit
that referenced
this pull request
Nov 27, 2026
…o main as one commit AIChatAgent runs its turns on chatTurnDefinition and chatDispatch, and its old engine is deleted. Rebased onto the rebased #3298 from f87cd85 plus verify's FIX: main merged in (#3389, #3444, #3447, #3435, #3423 resolved in chat-host.ts with turn-task's notes), F27, the stop in a retry backoff ending the turn once, a throwing onChatRecovery given up with recovery_error, and turn-task's 25baf34.
The chat module's functions over Tasks, Streams, Sessions and WebSockets: chatDispatch, submitTurn, answerTool, cancelTurn, clearChat, resumeChat, replayTurn, and the chat-turn definition's parked tabs, live turns and stopped mark. Rebased onto main c519393 from e44a940; the one conflict (the turn's report) keeps main's stash drop and 6d's continuation and parked-tab steps.
mattzcarey
force-pushed
the
slim/chat-fn-6d
branch
from
November 27, 2026 16:54
5278c07 to
54d3ca4
Compare
mattzcarey
added a commit
that referenced
this pull request
Nov 27, 2026
…o main as one commit AIChatAgent runs its turns on chatTurnDefinition and chatDispatch, and its old engine is deleted. Rebased onto the rebased #3298 from f87cd85 plus verify's FIX: main merged in (#3389, #3444, #3447, #3435, #3423 resolved in chat-host.ts with turn-task's notes), F27, the stop in a retry backoff ending the turn once, a throwing onChatRecovery given up with recovery_error, and turn-task's 25baf34.
mattzcarey
marked this pull request as ready for review
November 27, 2026 17:04
Member
Author
|
Replaced by #3504, which carries this change with the rest of the switch (integrated and tested together). |
mattzcarey
added a commit
that referenced
this pull request
Nov 29, 2026
* Chat: AIChatAgent runs its turns on the chat module, and an agent-tool 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) * Chat turns: a completed reply that ends in reasoning is kept; the reasoning 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) * Chat: step (d), what the switch left alive in ai-chat and the chat module'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) * Chat: PR 2's rulings: a clear that reaches a streaming reply ends its request's frame aborted (as before the switch); AIChatAgent warns once when a subclass overrides continueLastTurn; changeset lines for the kept differences * fix(ai-chat): the continueLastTurn warning is only for a class that overrides it: the override is looked for before Agent puts its method wrappers on the class's prototype, once per class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
4.iii slice 6d, stacked on #3289. What a host's public methods and socket handler call, as functions over
ChatDeps(RFC, "The chat module"):submitTurn(deps, lane, input, { requestId, idempotencyKey })starts the turn's run ofchatTurnDefinitionon the host's lane. It carries the request's messages the transcript doesn't already hold as they are, and the turn stores them when it starts, so a question queued behind a reply follows that reply (U1 A1 U2 A2). A client request also stores its client tools and body (capped bystorableRequestContext). A turn that brings neither, such as a server turn or a tool answer's continuation, runs with the stored ones.cancelTurn(deps, requestId)andclearChat(deps, lane)aretasks.cancelandtasks.clear(lane)plussession.clearMessages().answerTool(deps, lane, answer, { autoContinue })stores a client's tool result or approval in the message that holds the call (one Sessions upsert). It reads the latest leaf first and the whole path only when the call isn't there. A result for a call in the reply still streaming is joined to that live reply. WithautoContinue, once the message's last call is answered it starts onetool-answerturn per answered batch (an idempotency key over the reply and its call ids), so answers that race start one continuation. That turn names the reply holding the call (replyId), so an answer to an older reply's call continues that reply, not the latest.resumeChat(deps, lane, connection, probeId)handles a reconnecting tab:STREAM_RESUMING);STREAM_PENDING). It is offered the stream when the stream starts, or told there is none if the turn ends without one;STREAM_RESUME_NONE.replayTurn(deps, connection, requestId)replays what that turn streamed so far once the tab acks.chatDispatch(deps, lane, connection, message)maps a chat protocol frame to those: request, cancel, cancel-continuation, clear, tool result or approval, resume request and ack. A request without messages ends at once with an error naming the reason. Messages pushed by a tab returnfalse, for the host: Think ignores them and AIChatAgent stores them.Tests on the minimal Durable Object (the workers
chat-hostsuite):Per the arch ruling,
ChatProtocolHost,ReplyStreamsHostandRecoveredTurnHostgo when their last host moves onto these functions. harness's H2 moves ThinkChat ontochatDispatchfirst, then AIChatAgent moves in 6f and Think in H2's Think move. Until then the old host-objectdispatchChatProtocolserves those two hosts. The replay and the live frames can overlap by a chunk at the hand-over; 6f closes that as AIChatAgent moves, andResumeHandshakeand its host go then. Like #3289, this merges with its first caller.Mid-stream tool answers and the request context were #3310 and #3311; they are folded in here.
Cost (statements / rows written per prompt, local workerd, perf's harness
probes/perf, a ThinkHarness on a Durable Object, the object's second prompt; release is agents 0.34.0 and think 0.24.0, main is 9492a1a, head is 96c0d3f). Since H2, ThinkHarness's turns run throughchatTurnDefinition, so this is its hot path. The batching is also split out as #3357 per arch, and these rows are that hunk:hello(a short text reply)tool(one server tool)Statements are below the release in every row. Rows written are below it except the paced reply: 40 against 36, because a model that pauses between chunks is written at each pause, so a reset loses nothing it sent.
The chat functions have no production caller yet; once AIChatAgent calls them (the 6f switch), they add:
submitTurndoes onegetMessagepoint read for every message a tab sends (a tab sends its whole list), to carry only the new or changed ones in the run's input. Today each one is upserted: one write per message.answerToolreads the latest leaf, and the whole path only when the call is in an older reply.patchMetadatawrite.