Skip to content

Think on the harness: the hook stack, F29, and the test and nightly fixes - #3503

Merged
mattzcarey merged 10 commits into
mainfrom
slim/push-1-think-harness
Nov 28, 2026
Merged

mattzcarey merged 10 commits into
mainfrom
slim/push-1-think-harness

Conversation

@mattzcarey

@mattzcarey mattzcarey commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

Seven units integrated and tested together on slim/local-main while GitHub was unavailable. Each unit had its reviewer's approval on the exact commit, verify's deployed gate where it applies, and a full run of the affected suites after it went in (pnpm run build, pnpm run check, nx affected -t test). The units are below, one section each, in the order they were integrated.

This PR replaces #3406, #3409, #3413, #3421, #3422, #3424, #3427, #3428, #3431 (the hook stack), #3491 (F29), #3499 (the typing test) and #3501 (the codemode e2e result shapes). Those PRs are closed with a pointer to this one.

# Unit Commit
1 The hook stack (old #3406 … #3431) 2af4b56
2 F29: a recovery attempt runs outside the turn its run was started in (old #3491) f9564d8
3 The typing test settles the requests it stalls (old #3499) 5be64a9
4 Nightly: the codemode Workers AI e2e and the Pi/OpenCode suites go green (includes old #3501) ab52d86
5 Cleanup: the last test retry goes to 0; Channels' unused tool-schema.ts is deleted d39d572
6 Harness score, groups A and B 3414dbe
7 Successor tests and two racy tests held with a gate c1c6cca

1. harness-backed Think: the hook stack (structured output, workflow prompts, continuations, metadata, context-overflow recovery and guard, stopWhen, classifyChatError's request id)

Group G (#3406, #3409, #3413, #3421, #3422, #3424, #3427, #3428, #3431), squashed as one unit.

Group G, stacked on #3428: aborts around context-overflow recovery on the harness-backed Think.

Think calls classifyChatError(error, ctx) with the turn's requestId, so a classifier can stop that turn. It also skips compaction and the retry for a turn that was stopped.

  • ThinkHarness's classifyError hook and the extensions' classifyError event now carry the model call's session and operationId (@internal, optional).
  • The harness's onContextOverflow hook (from harness-backed Think: reactive context-overflow recovery (group G) #3424) gets the operation's signal.
  • The shell passes { requestId, stage: "stream" } to classifyChatError, and doesn't compact or rerun a stopped turn.

Cost: none. The same calls, with one more argument.

Score on the harness config, with no new failures:

File Before After
assistant-agent-loop.test.ts 23 26 of 33 (the three "does not compact or retry an aborted turn" tests)
hooks.test.ts 110 110 of 153

The agents harness.test.ts and extensions.test.ts pass 137 of 137.

Not here: "does not run the model again for a turn stopped while its history was compacted". Its abortAllRequests inside the compaction function doesn't reach the running operation's signal on the shell.

Q17: the optional context argument on classifyError, the session/operationId on the extensions' classifyError event, and signal on onContextOverflow are @internal additions not in arch's list. They're inert for hooks that ignore them, nothing is stored, and the public-API list is unchanged.


Included: #3428 harness-backed Think: TurnConfig.stopWhen (group G)

Group G, stacked on #3427: TurnConfig.stopWhen on the harness-backed Think.

In Think, a turn's stopWhen (one AI SDK stop condition or several) runs beside maxSteps: once a step meets one, no further model call is made after that step's tools run. The shell now keeps the turn's stopWhen from beforeTurn and checks it as each model step ends, against the turn's steps so far (stepResultOf). When a condition holds, it lowers the turn's maxSteps to the steps taken, which the harness already reads before each call. The step's tools still run, as in the AI SDK.

Cost: none without stopWhen. With it, one evaluation per step, as in Think.

Score on the harness config: hooks.test.ts 109 → 110 of 153 ("composes TurnConfig stopWhen with the maxSteps bound"). No harness change.


Included: #3427 harness-backed Think: the proactive context guard (group G)

Group G, stacked on #3424: Think's proactive context guard on the harness-backed Think.

With contextOverflow.proactive: { maxInputTokens, headroom?, maxCompactions? }, Think compacts before a step when the previous step's reported input tokens crossed maxInputTokens × headroom. It then sends that step the compacted history with the turn's reply so far. Each attempt counts toward maxCompactions (default 1), so a compaction that can't shorten isn't tried again every step. It emits chat:context:compacted with reason: "proactive", and beforeStep sees the compacted messages.

The shell does the same in #beforeTurn, before beforeStep. It reads the ended step's usage (kept since #3388), compacts through this.session, and builds the call's messages from session.getHistory() plus the reply so far. A later call reads the compacted history from the harness as usual.

Cost: none without proactive. With it, one comparison per model call, and when the guard fires one compaction and one history read.

Score on the harness config: assistant-agent-loop.test.ts 17 → 23 of 33 (0 class-only). hooks.test.ts 109 of 153, unchanged. No harness change.

Not here: "with BOTH layers" (a proactive compaction, then a reactive one in the same turn), plus the abort and continuation tests that #3424 lists.


Included: #3424 harness-backed Think: reactive context-overflow recovery (group G)

Group G, stacked on #3422: Think's reactive context-overflow recovery on the harness-backed Think.

Before, when a model call overflowed (classifyChatError returned "context_overflow"), the harness always compacted the session and tried the call again. Think does that only with contextOverflow.reactive, and then:

  • it emits chat:context:compacted (reason, shortened, requestId, attempt);
  • it runs the turn again, beforeTurn included;
  • if compaction can't shorten the history, the overflow ends the turn, and onChatError gets classification: "context_overflow".

The shell now does the same:

  • ThinkHarness takes an @internal onContextOverflow hook that answers whether room was made. Without it, the harness compacts as before.
  • The shell's hook reads contextOverflow, a new property as on Think, then compacts through this.session and emits the event.
  • After a shortening compaction it lets beforeTurn run again for the retry.
  • An overflow error reaches chat()'s onChatError with Think's context.

Cost: none unless a call overflows. An agent without contextOverflow.reactive no longer compacts on an overflow, as on Think. That's a change only on the unreleased harness-backed Think.

Score on the harness config: assistant-agent-loop.test.ts 10 → 17 of 33 (0 class-only). hooks.test.ts 109 of 153, unchanged.

Not here:

  • maxRetries above 1: the chat host tries an overflow once (overflowTried).
  • Aborts during recovery.
  • The proactive guard (7 tests).
  • The continuation and recovery paths, which reach _retryLastUserTurn and _cfRunConnectionlessContinuation.

Q17: the onContextOverflow hook isn't one of the fields in arch's list. It's @internal. Unset, the harness compacts and retries byte for byte as before. Nothing is stored, and the public-API list is unchanged.


Included: #3422 harness-backed Think: turn metadata from chat() (group G)

Group G, stacked on #3421: turn metadata on the harness-backed Think.

On Think, chat(input, callback, { channel, metadata }) stamps channel and turnMetadata on the turn's user message. activeTurnMetadata reads it back from the transcript, so a recovered or continued turn sees the same value. The shell now stamps both in chat() and reads activeTurnMetadata the same way (turnMetadataFromMessages). It used to return undefined. A client can't forge either key: the harness already strips channel and turnMetadata from client writes (reservedMetadataKeys).

"strips reserved metadata keys from client-supplied messages at intake" becomes class-only, because it writes through Think's private _persistIncomingMessage. Its successor, "strips reserved metadata keys a client's chat request sends", sends a chat request over a WebSocket with forged channel and turnMetadata. It asserts the stored message keeps the harmless key, has no turnMetadata, and doesn't carry the client's channel. Think stamps its own web there, and the harness strips it. It passes on both configs.

Cost: none for a chat() without channel or metadata. With them, one object spread per user message.

Score on the harness config: turn-metadata.test.ts 1 → 4 of 5, plus 1 class-only. Class config: 5 of 5.

A draft because it's stacked on the question 17 drafts. It adds no harness field.

rv-4 FIX: chat() now stamps through stampTurnContext (turn-metadata.ts), so an empty channel name stamps nothing, as on Think. New test: "stamps no channel for an empty channel name, as Think". It passes on both configs and failed on a1affe0, which stamped channel: "". turn-metadata is now 5 of 6 (1 class-only).


Included: #3421 harness-backed Think: messageMetadata on the reply (group G)

Group G, stacked on #3413: Think's messageMetadata on the harness-backed Think.

Think writes metadata onto the assistant message from the model's stream parts: TurnConfig.messageMetadata from beforeTurn, else the agent's messageMetadata property, called with the part and whether the turn continues. The shell now has the property and passes the writer to ThinkHarness as an @internal ThinkTurnConfig.messageMetadata. The harness merges it into the toUIMessageStream writer it already has, so the reply's owner stays and wins. The metadata reaches the live start and finish chunks and the stored reply, sub-agents included.

Cost: none without a writer. With one, a call per stream part, as in Think.

Score on the harness config: assistant-message-metadata.test.ts 1 → 6 of 9 (0 class-only). hooks.test.ts 109 of 153, unchanged. The agents harness.test.ts passes 125 of 125.

Not here: the 3 left are about continuations. Think stores an approval's continuation as a second assistant message, and the harness continues the same one, so it's the turn's shape, not the metadata. The other two extend a message on recovery (#2321), Q10's ground.

A draft because of question 17.

Q17: messageMetadata on ThinkTurnConfig isn't one of the fields in arch's list. It's the same kind as item 2 (sendReasoning): an option of the UI message stream, @internal, inert when unset (the harness's owner writer runs as before), and nothing stored. The public-API list is unchanged.


Included: #3413 harness-backed Think: runTurn's continuation runs an overridden continueLastTurn (group G)

Group G, stacked on #3409. On Think, runTurn({ continuation: true }) runs an app's overridden continueLastTurn and keeps the status it returns. The harness-backed Think went straight to the harness, so an override never ran. Now, when continueLastTurn is overridden, runTurn calls it. The returned status stands, and the turn's message and structured output are read from the settled operation.

Cost: none without an override. With one, one more wait on an operation that has already settled.

Score on the harness config, with no new failures:

File Before After
hooks.test.ts 108 109 of 153
run-turn.test.ts 14 15 of 35
think-session.test.ts 108 109 of 322

No new harness field. It's a draft only because it's stacked on the question 17 drafts.


Included: #3409 harness-backed Think: a workflow prompt's structured output through think_final_answer (group G)

Group G: a workflow prompt's structured output on the harness-backed Think, stacked on #3406. It's a draft like the rest of the stack: it adds one @internal harness hook (question 17).

When a submission's workflow prompt asks for output, Think ends the turn with a think_final_answer tool built from the prompt's schema, and the tool's input is the output the workflow is told. The shell now does the same:

  • The submission's running report arms the tool. The session's tools then offer it (suffixed if an app tool has the name), and the turn's beforeTurn adds Think's instruction and requires a tool call.
  • The tool's call records its input and ends the turn (no model call after it). The terminal report passes that input to sendWorkflowNotification's output argument (harness-backed Think: a workflow's submission tells the workflow when it ends (harness score B, 5) #3403).
  • The tool's parts never reach the transcript. The new @internal storedReply harness hook gives the chat host's sanitizeForPersistence the shell's withoutFinalAnswerParts.
  • The chat host now sanitizes before its empty check, so a reply that held only the tool isn't stored. With no hook, nothing changes.

Cost: none for a turn without a workflow output. With one, a metadata read on the running report and one extra tool.

Score on the harness config: submissions.test.ts 50 → 52 of 131 ("captures workflow structured output in terminal notifications", "does not persist the internal final-answer tool into the conversation"). hooks.test.ts 108 of 153. Class config: submissions.test.ts 131 of 131.

Not here:

  • "delivers a structured output that fits a workflow event, and fails one that does not". Think fails an oversized output's submission itself (status error). The shell's submission is already completed when it's told, and failing only the notification would leave the two disagreeing.
  • Recovery of a recorded output across an eviction: the output is held in memory for the running operation.

Not here (rv-1 allowed):

  • Pinning a structured turn with no tools of its own: Think always offers its workspace tools, so a structured turn always has tools of its own through the public API. The last-step pin takes the same { type: "tool" } path and is tested.
  • The extensions' tool hooks not seeing the final-answer call: the shell returns before toolCallStart/toolCallFinish for it, the same early return the beforeToolCall/afterToolCall test pins. A test would need a sandboxed extension fixture in this agent.

The fixes and tests rv-1 asked for are on the stack's top (#3431), per the one-go rule: 7b6cb4d (the recovered-partial test).


Included: #3406 ThinkHarness: structured output from beforeTurn, returned by runTurn (group G)

Group G's structured output, stacked on #3396. Like #3388, it's a draft until question 17 rules on @internal harness fields.

ThinkHarness's beforeTurn can set output: the AI SDK's spec, such as Output.object({ schema }), passed to streamText. When an operation's model call ends with an answer rather than a tool call, its parsed output is kept as the operation's. A parse failure settles the operation unanswered with the error, as a wait-mode Think turn errors. operationOutput(session, operationId) (@internal) reads a settled operation's output from its run's result. The harness-backed Think passes TurnConfig.output through, and runTurn's wait mode returns output when the turn had one, including a continuation's.

Cost: none without output. With it, one parse of the last model call's answer, and the output stored inside the run's result, which the run already writes.

Score on the harness config: hooks.test.ts 101 → 107 of 152 (0 class-only). "keeps the status an overridden continueLastTurn returns" still fails: the shell's continuation doesn't go through an overridden continueLastTurn, which isn't output. Next: the workflow final-answer capture in submissions.test.ts (turn-task's 3 tests, and 2 more there).

rv-3 FIX (at 17da635):

  • (1) A recovery that reuses the saved reply still has its output: the parsed output is kept on the placement (PLACED_KEY), which is written a second time for each turn with output.
  • (2) The live caller gets the value the schema produced, as on Think. The stored JSON is used across a restart. At most one value per session is kept in memory, replaced by the next output turn, deleted on read or on reset.
  • (3) onStepFinish runs before a parse failure fails the turn.
  • (4) An output over 512 KiB fails the turn with "Structured output is N bytes; an operation's output holds at most 524288", before it settles.

Cost, added: one more placement-checkpoint write per turn with output, and one in-memory value per session.


2. fix(think): a recovery attempt runs outside the turn its run was started in (F29)

Think starts each chat turn's Task run from inside that turn's admitted-turn context. A run started with start: "now" from inside an async context keeps it, so a recovery attempt that the same run made later ran as if it were still inside the turn that had started it. Code that asks "am I inside a turn?" (for example the guard on waitForSubmission) then answered yes for a turn that had ended.

What changed

  • packages/think/src/think.ts: the two attempt hooks given to the chat-turn and the recovery task definitions run inside admittedTurnContext.exit, so an attempt starts with no turn context of its own.
  • Tests: think-session.test.ts "runs a recovery attempt outside the turn its run was started in". The test reads the guard itself, so it cannot pass merely because the turn has ended. It is a class-only row (harness-class-only.json, mechanics only): on the harness a retry is another attempt of the turn's own run and has no such context.

Tests

think-session.test.ts on the class config: 340 of 340 at 97a494cb3.

Cost

None on a hot path: one context exit per recovery attempt.

Changeset

None. The bug is on main only and was never released.

Review state

rv-5 and rv-1 approved this content at aa81d7d and b714038; verify passed it at 046e2e9 and carried the PASS to 1fe1f2b. 97a494cb3 is the same two commits rebased onto slim/local-main (range-diff =, = against 72c24c7).


3. test(think): the typing test settles the requests it stalls

Hygiene in messengers.test.ts: the typing test ("still posts the reply when the first/refresh typing request never settles") stalled each typing request with new Promise(() => {}), a promise that never settles and outlives the test.

  • The test now keeps the resolver of each request it stalls, and settles them all in a finally once its assertions have run, so nothing it started is left pending.
  • Each case also checks that exactly one request stalled (requests never overlap), so the refresh case can't pass without stalling one.

This doesn't fix the intermittent "Cannot perform I/O on behalf of a different Durable Object (Lock)" unhandled rejection that Vitest attributes to this test. That rejection still shows in about 1 of 3 local runs of the file with this change, and its owner isn't found yet.

Tests only, no changeset.


4. test(nightly): the codemode Workers AI e2e and the Pi/OpenCode suites go green

Two of the nightly's three reds (run 46088241758) were bugs in the suites.

codemode on Workers AI (llm-codemode.spec.ts "LLM combines tools from both namespaces"). The suite's arithmetic tools had no outputSchema, so the types the model writes against said AddNumbersOutput = unknown. The model passed addNumbers' result ({ result: 15 }) to multiply as a number and got a tool error, then spent its steps working out the shape. In about 3 of 8 runs it used all five steps on tool calls and the reply had no text. The assertion's message is the reply, so the failure printed nothing.

  • addNumbers, multiply and divide declare outputSchema: { result: number }.
  • An empty reply fails with "(the reply has no text)".
  • Against Workers AI locally: 12 of 12 replies answered after the change, 5 of 8 before. The LLM suite passes 8/8 and the mock suite 21/21.

Pi and OpenCode deployed ("finishes a tool run that a code update cut off": the code update's deploy failed with "Script startup exceeded CPU time limit"). Both harnesses were in one Worker, 26 MB, with a startup of 303-497 ms over three measured deploys. The limit is 1 s, and the redeploy went over it. Now each suite deploys only its own harness:

  • harnesses/pi.ts and harnesses/opencode.ts are the two Workers, shared.ts has the witness object and the control routes, and each has a wrangler.<kind>.jsonc with only its own bindings (OpenCode drops BROWSER and LOADER, which it never read).
  • Pi's Worker is 4.3 MB and starts in 19-22 ms. OpenCode's is 22 MB and starts in 470-629 ms; that's @opencode/core, and it's noted for the lead.
  • pnpm run harnesses on a deployment: every fault case passes, including both code updates. The two real Workers AI conversations pass on a rerun (they missed their per-turn deadlines in the first run, at 185-238 s per turn, while Workers AI on the account was slow).

The third red, think harness compat --check, is the harness score's table (lane 3), not a suite bug.

Tests only, no changeset. Cost: none (nightly-only code).


5. test and cleanup: the last retry goes to 0; Channels' unused tool-schema.ts is deleted

  • examples/agents-as-tools/playwright.config.ts was the last test config in the repo with a retry (retries: process.env.E2E_NO_RETRY ? 0 : 1, to ride out Workers AI 504s). It now sets retries: 0, like every other suite. Run against real Workers AI with no retries: 7 of 7 pass (11 min), so nothing was hidden behind the retry. No workflow runs this suite; it runs locally.
  • packages/agents/src/experimental/channels/tool-schema.ts is deleted. Nothing has imported it since Channels moved to experimental (chore(channels)!: remove the first pass of Channels and move it to experimental #2429), it isn't a build entry, and agents/experimental/channels doesn't re-export it.

Checks: agents tsc clean; the Channels project 172/172.

No changeset (an example's test config and an unexported file).


6. test(think): harness score, groups A and B: the class's submission ledger and detached recovery tests are class-only, with public successors through real resets

About 120 Think tests that reach the class's private recovery engine or submission ledger become rows in harness-class-only.json, each with a public successor that runs on both configs, or marked mechanics-only, probe-covered or ruled out with its written ruling. New successors go through real resets, real stalls and real model errors: a submission recovered after a reset before any text, a recovered reply that fails, a stalled turn answered again from the start when onChatRecovery says persist: false, a throwing onExhausted, and classifyChatError's verdict on a failed model call (transient and rate_limit tried again and answered once; fatal, unknown and none end the turn).

The harness score counts the tests that construct Think and pass on the harness-backed path. These tests can't pass there by design:

  • they seed rows in the class's shape (insertSubmissionForTest, seedIncidentForTest, insertInterruptedFiber) and run its recovery callbacks or start-up reconciliation by hand;
  • or they read its detached recovery (scheduled continuations and retries, the successor-turn handoff, stream evidence), which the harness replaces with the turn's own next attempt.
    Each row names the private seam its test reaches; a ruled-out row cites its written ruling (one id per submission; a submission's end is its run's status; a stalled stream retried inside the run, Q10; stableTimeoutMs has no effect); a probe-covered row names verify's deployed scenario.

Rows by theme:

For every row, the old test passes on the class and fails on the harness, and its successor passes on both (submissions, chat-recovery-public, onconnect-broadcast, hydration-budget and think-session's recovery describes, both configs). Tests only, no changeset. Score: see report-parity.md.


7. test(think): harness score, more class-only rows with public successors (stream reclaim, onChatResponse, stop-reason), and four racy tests ordered by gates

Nine Think tests that reach the class's private reply pump or reply-stream store become rows in harness-class-only.json, each with a public successor that runs on both configs, or marked mechanics-only:

  • stream-cleanup (5): four tests that read the class's reply-stream rows and its cleanup schedule are mechanics-only; the one that pins a cut-off stream's chunks staying reconstructable has the reset successor 'tells onChatRecovery the partial a reset cut off mid-reply';
  • onChatResponse (5): tests that drove the class's reply pump by hand (_pumpReply) get successors from the model's own stream: an empty reply (onChatResponse once, completed, nothing stored, RPC onDone too), an in-band error before any part, an in-band error after some text (the text kept), and text the model writes after its error (not kept).

Nine stop-reason agent-tool cases now run on both configs with no row: they waited on the class's private agent-tool controllers, and now wait for the run to settle through inspectAgentToolRun.

It fixes two problems the previous unit left in the score check:

  • the four pending-retry submission rows move to the reset successors that hold a submission running while its recovery waits, so no successor names more than the script's four rows;
  • the successor 'a reused id is not settled with the result of the submission deleted before it' starts its wait once the new submission is stored, instead of racing its acceptance.

Two racy tests from the train's local full run now hold their window with a gate instead of a timer: Think's 'aborts a submission cancelled while its running hook is in flight' holds the running status report until the cancel has been asked (was a 150 ms delay), and the agents test 'waits for an in-flight connection instead of reporting it ready' holds the MCP connection in connecting until addMcpServer has been asked (was a 50 ms timer).

For every row the old test passes on the class and fails on the harness, and its successor passes on both (stream-cleanup, chat-recovery-public, think-session's onChatResponse describe, submissions, stop-reason; both configs). The racy tests passed 3 of 3 on both Think configs and in the agents workers project. Tests only, no changeset.


Devin Review

…mpts, continuations, metadata, context-overflow recovery and guard, stopWhen, classifyChatError's request id)

Group G (#3406, #3409, #3413, #3421, #3422, #3424, #3427, #3428, #3431), squashed as one unit.

Group G, stacked on #3428: aborts around context-overflow recovery on the harness-backed Think.

Think calls `classifyChatError(error, ctx)` with the turn's `requestId`, so a classifier can stop that turn. It also skips compaction and the retry for a turn that was stopped.

- ThinkHarness's `classifyError` hook and the extensions' `classifyError` event now carry the model call's `session` and `operationId` (`@internal`, optional).
- The harness's `onContextOverflow` hook (from #3424) gets the operation's signal.
- The shell passes `{ requestId, stage: "stream" }` to `classifyChatError`, and doesn't compact or rerun a stopped turn.

Cost: none. The same calls, with one more argument.

Score on the harness config, with no new failures:

| File | Before | After |
| --- | --- | --- |
| `assistant-agent-loop.test.ts` | 23 | 26 of 33 (the three "does not compact or retry an aborted turn" tests) |
| `hooks.test.ts` | 110 | 110 of 153 |

The agents `harness.test.ts` and `extensions.test.ts` pass 137 of 137.

Not here: "does not run the model again for a turn stopped while its history was compacted". Its `abortAllRequests` inside the compaction function doesn't reach the running operation's signal on the shell.

**Q17:** the optional `context` argument on `classifyError`, the `session`/`operationId` on the extensions' `classifyError` event, and `signal` on `onContextOverflow` are `@internal` additions not in arch's list. They're inert for hooks that ignore them, nothing is stored, and the public-API list is unchanged.

---

## Included: #3428 harness-backed Think: TurnConfig.stopWhen (group G)

Group G, stacked on #3427: `TurnConfig.stopWhen` on the harness-backed Think.

In Think, a turn's `stopWhen` (one AI SDK stop condition or several) runs beside `maxSteps`: once a step meets one, no further model call is made after that step's tools run. The shell now keeps the turn's `stopWhen` from `beforeTurn` and checks it as each model step ends, against the turn's steps so far (`stepResultOf`). When a condition holds, it lowers the turn's `maxSteps` to the steps taken, which the harness already reads before each call. The step's tools still run, as in the AI SDK.

Cost: none without `stopWhen`. With it, one evaluation per step, as in Think.

Score on the harness config: `hooks.test.ts` 109 → 110 of 153 ("composes TurnConfig stopWhen with the maxSteps bound"). No harness change.

---

## Included: #3427 harness-backed Think: the proactive context guard (group G)

Group G, stacked on #3424: Think's proactive context guard on the harness-backed Think.

With `contextOverflow.proactive: { maxInputTokens, headroom?, maxCompactions? }`, Think compacts before a step when the previous step's reported input tokens crossed `maxInputTokens × headroom`. It then sends that step the compacted history with the turn's reply so far. Each attempt counts toward `maxCompactions` (default 1), so a compaction that can't shorten isn't tried again every step. It emits `chat:context:compacted` with `reason: "proactive"`, and `beforeStep` sees the compacted messages.

The shell does the same in `#beforeTurn`, before `beforeStep`. It reads the ended step's usage (kept since #3388), compacts through `this.session`, and builds the call's messages from `session.getHistory()` plus the reply so far. A later call reads the compacted history from the harness as usual.

Cost: none without `proactive`. With it, one comparison per model call, and when the guard fires one compaction and one history read.

Score on the harness config: `assistant-agent-loop.test.ts` 17 → 23 of 33 (0 class-only). `hooks.test.ts` 109 of 153, unchanged. No harness change.

Not here: "with BOTH layers" (a proactive compaction, then a reactive one in the same turn), plus the abort and continuation tests that #3424 lists.

---

## Included: #3424 harness-backed Think: reactive context-overflow recovery (group G)

Group G, stacked on #3422: Think's reactive context-overflow recovery on the harness-backed Think.

Before, when a model call overflowed (`classifyChatError` returned `"context_overflow"`), the harness always compacted the session and tried the call again. Think does that only with `contextOverflow.reactive`, and then:
- it emits `chat:context:compacted` (`reason`, `shortened`, `requestId`, `attempt`);
- it runs the turn again, `beforeTurn` included;
- if compaction can't shorten the history, the overflow ends the turn, and `onChatError` gets `classification: "context_overflow"`.

The shell now does the same:
- ThinkHarness takes an `@internal` `onContextOverflow` hook that answers whether room was made. Without it, the harness compacts as before.
- The shell's hook reads `contextOverflow`, a new property as on Think, then compacts through `this.session` and emits the event.
- After a shortening compaction it lets `beforeTurn` run again for the retry.
- An overflow error reaches `chat()`'s `onChatError` with Think's context.

Cost: none unless a call overflows. An agent without `contextOverflow.reactive` no longer compacts on an overflow, as on Think. That's a change only on the unreleased harness-backed Think.

Score on the harness config: `assistant-agent-loop.test.ts` 10 → 17 of 33 (0 class-only). `hooks.test.ts` 109 of 153, unchanged.

Not here:
- `maxRetries` above 1: the chat host tries an overflow once (`overflowTried`).
- Aborts during recovery.
- The proactive guard (7 tests).
- The continuation and recovery paths, which reach `_retryLastUserTurn` and `_cfRunConnectionlessContinuation`.

**Q17:** the `onContextOverflow` hook isn't one of the fields in arch's list. It's `@internal`. Unset, the harness compacts and retries byte for byte as before. Nothing is stored, and the public-API list is unchanged.

---

## Included: #3422 harness-backed Think: turn metadata from chat() (group G)

Group G, stacked on #3421: turn metadata on the harness-backed Think.

On Think, `chat(input, callback, { channel, metadata })` stamps `channel` and `turnMetadata` on the turn's user message. `activeTurnMetadata` reads it back from the transcript, so a recovered or continued turn sees the same value. The shell now stamps both in `chat()` and reads `activeTurnMetadata` the same way (`turnMetadataFromMessages`). It used to return `undefined`. A client can't forge either key: the harness already strips `channel` and `turnMetadata` from client writes (`reservedMetadataKeys`).

"strips reserved metadata keys from client-supplied messages at intake" becomes class-only, because it writes through Think's private `_persistIncomingMessage`. Its successor, "strips reserved metadata keys a client's chat request sends", sends a chat request over a WebSocket with forged `channel` and `turnMetadata`. It asserts the stored message keeps the harmless key, has no `turnMetadata`, and doesn't carry the client's channel. Think stamps its own `web` there, and the harness strips it. It passes on both configs.

Cost: none for a `chat()` without channel or metadata. With them, one object spread per user message.

Score on the harness config: `turn-metadata.test.ts` 1 → 4 of 5, plus 1 class-only. Class config: 5 of 5.

A draft because it's stacked on the question 17 drafts. It adds no harness field.

rv-4 FIX: `chat()` now stamps through `stampTurnContext` (turn-metadata.ts), so an empty channel name stamps nothing, as on Think. New test: "stamps no channel for an empty channel name, as Think". It passes on both configs and failed on a1affe0, which stamped `channel: ""`. turn-metadata is now 5 of 6 (1 class-only).

---

## Included: #3421 harness-backed Think: messageMetadata on the reply (group G)

Group G, stacked on #3413: Think's `messageMetadata` on the harness-backed Think.

Think writes metadata onto the assistant message from the model's stream parts: `TurnConfig.messageMetadata` from `beforeTurn`, else the agent's `messageMetadata` property, called with the part and whether the turn continues. The shell now has the property and passes the writer to ThinkHarness as an `@internal` `ThinkTurnConfig.messageMetadata`. The harness merges it into the `toUIMessageStream` writer it already has, so the reply's `owner` stays and wins. The metadata reaches the live start and finish chunks and the stored reply, sub-agents included.

Cost: none without a writer. With one, a call per stream part, as in Think.

Score on the harness config: `assistant-message-metadata.test.ts` 1 → 6 of 9 (0 class-only). `hooks.test.ts` 109 of 153, unchanged. The agents `harness.test.ts` passes 125 of 125.

Not here: the 3 left are about continuations. Think stores an approval's continuation as a second assistant message, and the harness continues the same one, so it's the turn's shape, not the metadata. The other two extend a message on recovery (#2321), Q10's ground.

A draft because of question 17.

**Q17:** `messageMetadata` on `ThinkTurnConfig` isn't one of the fields in arch's list. It's the same kind as item 2 (`sendReasoning`): an option of the UI message stream, `@internal`, inert when unset (the harness's `owner` writer runs as before), and nothing stored. The public-API list is unchanged.

---

## Included: #3413 harness-backed Think: runTurn's continuation runs an overridden continueLastTurn (group G)

Group G, stacked on #3409. On Think, `runTurn({ continuation: true })` runs an app's overridden `continueLastTurn` and keeps the status it returns. The harness-backed Think went straight to the harness, so an override never ran. Now, when `continueLastTurn` is overridden, `runTurn` calls it. The returned status stands, and the turn's message and structured output are read from the settled operation.

Cost: none without an override. With one, one more `wait` on an operation that has already settled.

Score on the harness config, with no new failures:

| File | Before | After |
| --- | --- | --- |
| `hooks.test.ts` | 108 | 109 of 153 |
| `run-turn.test.ts` | 14 | 15 of 35 |
| `think-session.test.ts` | 108 | 109 of 322 |

No new harness field. It's a draft only because it's stacked on the question 17 drafts.

---

## Included: #3409 harness-backed Think: a workflow prompt's structured output through think_final_answer (group G)

Group G: a workflow prompt's structured output on the harness-backed Think, stacked on #3406. It's a draft like the rest of the stack: it adds one `@internal` harness hook (question 17).

When a submission's workflow prompt asks for output, Think ends the turn with a `think_final_answer` tool built from the prompt's schema, and the tool's input is the output the workflow is told. The shell now does the same:
- The submission's `running` report arms the tool. The session's tools then offer it (suffixed if an app tool has the name), and the turn's `beforeTurn` adds Think's instruction and requires a tool call.
- The tool's call records its input and ends the turn (no model call after it). The terminal report passes that input to `sendWorkflowNotification`'s output argument (#3403).
- The tool's parts never reach the transcript. The new `@internal` `storedReply` harness hook gives the chat host's `sanitizeForPersistence` the shell's `withoutFinalAnswerParts`.
- The chat host now sanitizes before its empty check, so a reply that held only the tool isn't stored. With no hook, nothing changes.

Cost: none for a turn without a workflow output. With one, a metadata read on the `running` report and one extra tool.

Score on the harness config: `submissions.test.ts` 50 → 52 of 131 ("captures workflow structured output in terminal notifications", "does not persist the internal final-answer tool into the conversation"). `hooks.test.ts` 108 of 153. Class config: `submissions.test.ts` 131 of 131.

Not here:
- "delivers a structured output that fits a workflow event, and fails one that does not". Think fails an oversized output's submission itself (status error). The shell's submission is already completed when it's told, and failing only the notification would leave the two disagreeing.
- Recovery of a recorded output across an eviction: the output is held in memory for the running operation.

**Not here (rv-1 allowed):**
- Pinning a structured turn with no tools of its own: Think always offers its workspace tools, so a structured turn always has tools of its own through the public API. The last-step pin takes the same `{ type: "tool" }` path and is tested.
- The extensions' tool hooks not seeing the final-answer call: the shell returns before `toolCallStart`/`toolCallFinish` for it, the same early return the `beforeToolCall`/`afterToolCall` test pins. A test would need a sandboxed extension fixture in this agent.

The fixes and tests rv-1 asked for are on the stack's top (#3431), per the one-go rule: 7b6cb4d (the recovered-partial test).

---

## Included: #3406 ThinkHarness: structured output from beforeTurn, returned by runTurn (group G)

Group G's structured output, stacked on #3396. Like #3388, it's a draft until question 17 rules on `@internal` harness fields.

ThinkHarness's `beforeTurn` can set `output`: the AI SDK's spec, such as `Output.object({ schema })`, passed to `streamText`. When an operation's model call ends with an answer rather than a tool call, its parsed output is kept as the operation's. A parse failure settles the operation unanswered with the error, as a wait-mode Think turn errors. `operationOutput(session, operationId)` (`@internal`) reads a settled operation's output from its run's result. The harness-backed Think passes `TurnConfig.output` through, and `runTurn`'s wait mode returns `output` when the turn had one, including a continuation's.

Cost: none without `output`. With it, one parse of the last model call's answer, and the output stored inside the run's result, which the run already writes.

Score on the harness config: `hooks.test.ts` 101 → 107 of 152 (0 class-only). "keeps the status an overridden continueLastTurn returns" still fails: the shell's continuation doesn't go through an overridden `continueLastTurn`, which isn't output. Next: the workflow final-answer capture in `submissions.test.ts` (turn-task's 3 tests, and 2 more there).

rv-3 FIX (at 17da635):
- (1) A recovery that reuses the saved reply still has its output: the parsed output is kept on the placement (`PLACED_KEY`), which is written a second time for each turn with output.
- (2) The live caller gets the value the schema produced, as on Think. The stored JSON is used across a restart. At most one value per session is kept in memory, replaced by the next output turn, deleted on read or on reset.
- (3) `onStepFinish` runs before a parse failure fails the turn.
- (4) An output over 512 KiB fails the turn with "Structured output is N bytes; an operation's output holds at most 524288", before it settles.

Cost, added: one more placement-checkpoint write per turn with output, and one in-memory value per session.

Unit: slim/harness-score-hooks-15 @54e9a5e43
…ted in (F29)

Think starts each chat turn's Task run from inside that turn's admitted-turn context. A run started with `start: "now"` from inside an async context keeps it, so a recovery attempt that the same run made later ran as if it were still inside the turn that had started it. Code that asks "am I inside a turn?" (for example the guard on `waitForSubmission`) then answered yes for a turn that had ended.

## What changed
- `packages/think/src/think.ts`: the two attempt hooks given to the chat-turn and the recovery task definitions run inside `admittedTurnContext.exit`, so an attempt starts with no turn context of its own.
- Tests: `think-session.test.ts` "runs a recovery attempt outside the turn its run was started in". The test reads the guard itself, so it cannot pass merely because the turn has ended. It is a class-only row (`harness-class-only.json`, mechanics only): on the harness a retry is another attempt of the turn's own run and has no such context.

## Tests
`think-session.test.ts` on the class config: 340 of 340 at 97a494cb3.

## Cost
None on a hot path: one context exit per recovery attempt.

## Changeset
None. The bug is on main only and was never released.

## Review state
rv-5 and rv-1 approved this content at aa81d7d and b714038; verify passed it at 046e2e9 and carried the PASS to 1fe1f2b. 97a494cb3 is the same two commits rebased onto `slim/local-main` (range-diff `=`, `=` against 72c24c7).

Unit: slim/turn-task-f29 @97a494cb3
Hygiene in `messengers.test.ts`: the typing test ("still posts the reply when the first/refresh typing request never settles") stalled each typing request with `new Promise(() => {})`, a promise that never settles and outlives the test.

- The test now keeps the resolver of each request it stalls, and settles them all in a `finally` once its assertions have run, so nothing it started is left pending.
- Each case also checks that exactly one request stalled (requests never overlap), so the refresh case can't pass without stalling one.

This doesn't fix the intermittent "Cannot perform I/O on behalf of a different Durable Object (Lock)" unhandled rejection that Vitest attributes to this test. That rejection still shows in about 1 of 3 local runs of the file with this change, and its owner isn't found yet.

Tests only, no changeset.

Unit: slim/think-typing-test-owns-request @0a75d807b
… go green

Two of the nightly's three reds (run 46088241758) were bugs in the suites.

**codemode on Workers AI** (`llm-codemode.spec.ts` "LLM combines tools from both namespaces"). The suite's arithmetic tools had no `outputSchema`, so the types the model writes against said `AddNumbersOutput = unknown`. The model passed `addNumbers`' result (`{ result: 15 }`) to `multiply` as a number and got a tool error, then spent its steps working out the shape. In about 3 of 8 runs it used all five steps on tool calls and the reply had no text. The assertion's message is the reply, so the failure printed nothing.
- `addNumbers`, `multiply` and `divide` declare `outputSchema: { result: number }`.
- An empty reply fails with "(the reply has no text)".
- Against Workers AI locally: 12 of 12 replies answered after the change, 5 of 8 before. The LLM suite passes 8/8 and the mock suite 21/21.

**Pi and OpenCode deployed** ("finishes a tool run that a code update cut off": the code update's deploy failed with "Script startup exceeded CPU time limit"). Both harnesses were in one Worker, 26 MB, with a startup of 303-497 ms over three measured deploys. The limit is 1 s, and the redeploy went over it. Now each suite deploys only its own harness:
- `harnesses/pi.ts` and `harnesses/opencode.ts` are the two Workers, `shared.ts` has the witness object and the control routes, and each has a `wrangler.<kind>.jsonc` with only its own bindings (OpenCode drops `BROWSER` and `LOADER`, which it never read).
- Pi's Worker is 4.3 MB and starts in 19-22 ms. OpenCode's is 22 MB and starts in 470-629 ms; that's `@opencode/core`, and it's noted for the lead.
- `pnpm run harnesses` on a deployment: every fault case passes, including both code updates. The two real Workers AI conversations pass on a rerun (they missed their per-turn deadlines in the first run, at 185-238 s per turn, while Workers AI on the account was slow).

The third red, `think harness compat --check`, is the harness score's table (lane 3), not a suite bug.

Tests only, no changeset. Cost: none (nightly-only code).

Unit: slim/nightly-reds @080ad11e7
…ema.ts is deleted

- **`examples/agents-as-tools/playwright.config.ts`** was the last test config in the repo with a retry (`retries: process.env.E2E_NO_RETRY ? 0 : 1`, to ride out Workers AI 504s). It now sets `retries: 0`, like every other suite. Run against real Workers AI with no retries: 7 of 7 pass (11 min), so nothing was hidden behind the retry. No workflow runs this suite; it runs locally.
- **`packages/agents/src/experimental/channels/tool-schema.ts`** is deleted. Nothing has imported it since Channels moved to experimental (#2429), it isn't a build entry, and `agents/experimental/channels` doesn't re-export it.

Checks: agents `tsc` clean; the Channels project 172/172.

No changeset (an example's test config and an unexported file).

Unit: slim/finish-cleanup @bac07419b
…dger and detached recovery tests are class-only, with public successors through real resets

About 120 Think tests that reach the class's private recovery engine or submission ledger become rows in `harness-class-only.json`, each with a public successor that runs on both configs, or marked mechanics-only, probe-covered or ruled out with its written ruling. New successors go through real resets, real stalls and real model errors: a submission recovered after a reset before any text, a recovered reply that fails, a stalled turn answered again from the start when `onChatRecovery` says `persist: false`, a throwing `onExhausted`, and `classifyChatError`'s verdict on a failed model call (transient and rate_limit tried again and answered once; fatal, unknown and none end the turn).

The harness score counts the tests that construct Think and pass on the harness-backed path. These tests can't pass there by design:
- they seed rows in the class's shape (`insertSubmissionForTest`, `seedIncidentForTest`, `insertInterruptedFiber`) and run its recovery callbacks or start-up reconciliation by hand;
- or they read its detached recovery (scheduled continuations and retries, the successor-turn handoff, stream evidence), which the harness replaces with the turn's own next attempt.
Each row names the private seam its test reaches; a ruled-out row cites its written ruling (one id per submission; a submission's end is its run's status; a stalled stream retried inside the run, Q10; `stableTimeoutMs` has no effect); a probe-covered row names verify's deployed scenario.

Rows by theme:
- submissions (group B): 25 (15 with successors, 10 mechanics-only), from turn-task's B-9 and nightly's successors;
- recovery batch 5 (std's): 3 probe-covered, 7 ruled out, successors for onExhausted's context, persist: false after a reset, the stash, a stored reply not continued again, one reply recovered twice;
- 'Think — chatRecovery' (the ledger under recovery): 10 with successors, 10 ruled out, 1 mechanics-only;
- stalls, the recovery budget and the interrupted-attempts bound: 12 with successors;
- #2085 classifier: 8 with successors;
- hydration-budget: 3 mechanics-only (rv-6's rulings), 1 with a successor.

For every row, the old test passes on the class and fails on the harness, and its successor passes on both (`submissions`, `chat-recovery-public`, `onconnect-broadcast`, `hydration-budget` and think-session's recovery describes, both configs). Tests only, no changeset. Score: see report-parity.md.

Unit: slim/parity-unit-1 @116c154d1
Two tests that raced a timer under load now hold the moment they test with a gate. Think's 'aborts a submission cancelled while its running hook is in flight' holds the `running` status report until the cancel has been asked, instead of hoping a 150 ms delay outlasts the cancel RPC. The agents test 'waits for an in-flight connection instead of reporting it ready' holds the MCP connection in `connecting` until `addMcpServer` has been asked, instead of a 50 ms timer that could fire before the state was read.

Both failed in the train's local full run at load 43 and passed on re-run.

Each passed 3 of 3 on both Think configs and in the agents workers project. Tests only.

(Folded into `slim/parity-unit-2` with stream-cleanup's rows: four tests that read the class's reply-stream rows and cleanup schedule are mechanics-only, and the one that pins a cut-off stream's chunks staying reconstructable has the reset successor 'tells onChatRecovery the partial a reset cut off mid-reply'.)

Four onChatResponse tests drove the class's reply pump by hand (`_pumpReply`); their successors run the same replies from the model's own stream: an empty reply (onChatResponse once, completed, nothing stored), an in-band error before any part, and one after some text (the text kept, onChatResponse once with the error).
Also: an in-band error ends the reply: text the model writes after its error is not kept (successor of 'should treat in-band errors as terminal stream events').
Also: stop-reason's nine agent-tool cases wait for the run to settle through inspectAgentToolRun instead of the class's private controllers, so they run on both configs.

Unit: slim/parity-unit-2 @244a17d70
@changeset-bot

changeset-bot Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 785cc49

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 3 packages
Name Type
agents Minor
@cloudflare/think Minor
@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@3503

@cloudflare/ai-chat

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

@cloudflare/codemode

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

hono-agents

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

@cloudflare/shell

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

@cloudflare/think

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

@cloudflare/voice

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

@cloudflare/worker-bundler

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

commit: 785cc49

@agent-think

agent-think Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

🟡 agents import sizes: 1 entry point grew

Entry point Exports Largest gzip change Size now
🟡 agents/harness/think 1 resized +1 KiB (+0.45%) 230 KiB
Changed exports (1)
Import Gzip change Size now
🟡 agents/harness/think#ThinkHarness +1 KiB (+0.45%) 230 KiB
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 ca1fc52c → 785cc490 · workflow run · reported by agent-think[bot]

devin-ai-integration[bot]

This comment was marked as resolved.

… tool the turn offers; the proactive guard's compacted history is truncated as every call's is; a structured turn that its step limit ends after a tool call fails, as the AI SDK answers it; a continued reply's start keeps the metadata keys it has; a changeset line for a tool that resolves to an async iterable
devin-ai-integration[bot]

This comment was marked as resolved.

…e place of beforeTurn's structured output; the guard's compacted history counts toward the cutoff without the live reply
…ute out and makes it pass with backdateTaskWake, so the pool's own alarm can't run the run while the test drives it

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 1 new potential issue.

Devin Review

Comment thread packages/think/src/harness/think.ts Resolved
@mattzcarey
mattzcarey merged commit 0d6cba3 into main Nov 28, 2026
28 checks passed
@mattzcarey
mattzcarey deleted the slim/push-1-think-harness branch November 28, 2026 21:37
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