Skip to content

fix(stream): emit usage before turn_ended in closing frames - #1101

Merged
stamp-build[bot] merged 2 commits into
mainfrom
agent/lookout/turn-end-usage-order
Nov 21, 2026
Merged

stamp-build[bot] merged 2 commits into
mainfrom
agent/lookout/turn-end-usage-order

Conversation

@stamp-build

@stamp-build stamp-build Bot commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

Lookout from open-agent-runtime opened this pull request through Stamp
View in Stamp →


Summary

Fix the closing-frame event order across all OAR adapters so turn_ended is the last event of its turn, including within a single frame.

Previously, ACP (shared/acp/turns.ts finishRequest), Claude/stream-json (result.after), Pi SDK/RPC (agent_settled), scriptedRuntime, and the sea-trial mock session emitted usage after turn_ended in the closing frame. Consumers that finalize per-turn summaries at turn_ended dropped the turn's token and context usage (reported from Raft where Antigravity's cache-hit rate read near 0%). Events that belong to a subsequent turn opening on the same frame (following turn_active, as in Pi Durable's view handover or Grok's deferred native turn) remain after turn_ended.

Requested by Cindy in #core:#394.

Release notes

Fixes

  • Closing frames emit usage before turn_ended across all runtimes. Hosts that finalize per-turn token, cache, or context summaries when observing turn_ended on Session.events() now receive the turn's closing usage event first on ACP runtimes (Antigravity, CodeBuddy, Devin, Grok, Kimi, OpenCode), Claude, Pi SDK/RPC, and scriptedRuntime. Events belonging to a subsequent turn that starts on the same frame still follow turn_ended after a turn_active event.

Changes

  • Spec and runtime docs:
    • docs/spec/record-stream.md: added the stream rule stating that turn_ended is the last event of its turn, so every event of that turn (including its closing usage) precedes turn_ended, also within one frame, while next-turn events follow turn_active after turn_ended. Fixed Example 1 (result frame order).
    • docs/runtimes/claude.md, docs/runtimes/pi.md, docs/runtimes/grok.md, docs/runtimes/agents-api.md: updated tables and prose that listed turn_ended before usage.
  • Adapters:
    • packages/oar/src/shared/acp/turns.ts: emit frame.context (usage) before turn_ended in finishRequest, keeping closeTurn(state) (Grok's deferred next-turn turn_active) after turn_ended.
    • packages/oar/src/shared/stream-json/profile.ts and projection.ts: removed result.after from StreamJsonProjectionProfile.result so no stream-json dialect can emit events after turn_ended on a result frame.
    • packages/oar/src/runtimes/claude/projection.ts: moved usage into result.before (after service_tier, before turn_ended).
    • packages/oar/src/runtimes/qwen/projection.ts and qoder/projection.ts: removed unused after: [].
    • packages/oar/src/runtimes/pi/projection.ts: emit context usage before turn_ended on agent_settled.
    • packages/oar/src/runtimes/pi/session.ts and rpc/session.ts: prepend refusedInput before command.body.events on pre-agent_start settlement so nothing can land after turn_ended.
    • packages/oar/src/testing/scripted-runtime.ts and sea-trial/fixtures/mock-session.ts: emit usage before turn_ended in scripted/end and mock/end.
  • Cross-runtime contract tests:
    • sea-trial/harness/stream-order.ts and sea-trial/cases/session.ts: added assertNoUsageAfterTurnEnded checking every frame of recorded behavior streams across all backends (session.framing-and-attribution, session.abort-settles-and-is-idempotent, session.multi-turn-conversation, session.queue-runs-after-turn): within any frame, no usage follows turn_ended unless a turn_active comes between them.
    • tests/turn-end-event-order.test.ts: cross-runtime contract test over all recorded Claude, Pi, and Codex replay fixtures plus ACP (including Grok deferred next-turn turn_active), Qwen, Qoder, Factory, Cursor, DSH, Pi Durable (including view handover usage -> turn_ended -> turn_active), Morph, Cybion, scriptedRuntime, and mock.
    • Updated existing order assertions and Claude replay snapshots (tests/acp/acp-grok-wire-shapes.test.ts, tests/replay/pi-projection.test.ts, tests/scripted-runtime.test.ts, tests/session.test.ts, tests/replay/fixtures/claude-*.{projected.txt,stream-json.jsonl}).

Call-site audit (all turn_ended and usage emitters)

  • packages/oar/src/shared/acp/turns.ts (finishRequest, covers Antigravity, CodeBuddy, Devin, Grok, Kimi, OpenCode v1/v2): changed (usage moved before turn_ended; deferred next-turn turn_active stays after turn_ended).
  • packages/oar/src/shared/acp/records.ts (Grok spontaneous turn_completed): unchanged (tokenUsage.extension is already pushed before nativeTurns.project).
  • packages/oar/src/shared/stream-json/projection.ts, profile.ts, runtimes/claude/projection.ts: changed (removed result.after; moved Claude usage into result.before).
  • packages/oar/src/runtimes/qwen/projection.ts, runtimes/qoder/projection.ts: changed (removed unused after: []; usage was already in result.before).
  • packages/oar/src/runtimes/pi/projection.ts, pi/session.ts, pi/rpc/session.ts: changed (agent_settled context usage moved before turn_ended; refusedInput prepended).
  • packages/oar/src/runtimes/pi-durable/projection.ts, session.ts: unchanged (settingsEvents with usage already precedes turn_ended, and turn_active plus next-run events stay after turn_ended).
  • packages/oar/src/runtimes/factory/projection.ts, session.ts: unchanged (agent_turn_completed already emits usage before turn_ended, and session.ts after appends only next-turn turn_active for a missed steer).
  • packages/oar/src/runtimes/codex/projection.ts, token-usage.ts: unchanged (thread/tokenUsage/updated and turn/completed are separate frames; turn_ended is already last on turn/completed).
  • packages/oar/src/runtimes/cursor/projection.ts: unchanged (turn-ended and model-call-completed usage deltas precede cursor/run_result / cursor/run_failed, where turn_ended is already last).
  • packages/oar/src/runtimes/dsh/projection.ts: unchanged (assistant/message and assistant/attempt emit usage in their own frames before turn/end, which emits only turn_ended).
  • packages/oar/src/community/morph/projection.ts, tracker.ts: unchanged (topic/metadata emits context usage before foldMorphTask, where turn_ended is already last).
  • packages/oar/src/community/cybion/tracker.ts: unchanged (emitUsage records thread/usage before finish records turn_ended).
  • packages/oar/src/testing/scripted-runtime.ts: changed (usage moved before turn_ended).
  • sea-trial/fixtures/mock-session.ts: changed (usage moved before turn_ended).

Verification

  • Pre-fix failure check: ran the new contract test before applying fixes and confirmed it failed on Claude replay fixtures (claude-background-tasks.raw.jsonl:result/success: [turn_ended, usage]), Pi replay fixtures (pi-mcp-echo.raw.jsonl:agent_settled: [turn_ended, usage]), ACP (session/prompt: [turn_ended, usage]), scriptedRuntime (scripted/end: [turn_ended, usage]), OAR_TEST=mock (mock/end: [turn_ended, usage]), and OAR_TEST=pi-aimock (agent_settled: [turn_ended, usage]).
  • Post-fix local checks on d5a56523:
    • CI=1 pnpm run check: typecheck passed, oxlint --type-aware --deny-warnings 0 warnings / 0 errors on 1913 files, vitest run 561 passed / 3 skipped / 0 failed (5403 passed / 110 skipped), sea-trial mock 19 passed / 1 skipped / 0 failed.
    • Additional local sea-trial runs: scripted 18 passed / 2 skipped / 0 failed; pi-aimock 18 passed / 2 skipped / 0 failed; pi-rpc-aimock 18 passed / 2 skipped / 0 failed; pi-durable-aimock 19 passed / 1 skipped / 0 failed.

@stamp-build

stamp-build Bot commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

CHANGES @ d5a5652

The reorder is right and the sweep is complete for usage: ACP finishRequest, Claude/stream-json (after removed from the profile, so the wrong order can no longer be written), Pi SDK and RPC, scripted and mock runtimes, and the docs. Two things before I approve.

  1. The checker enforces less than the rule. The spec rule says every event of the closing turn precedes turn_ended, and names service_tier, model, effort and input_dropped, but assertNoUsageAfterTurnEnded only rejects usage. Make the helper enforce the rule as written: within a frame, after a turn_ended, the next event must be turn_active (or the frame ends). Anything else fails. If an adapter legitimately emits some other event there, name that kind in the spec rule instead of exempting it silently. Rename the helper to match (for example assertTurnEndedLast) and keep its five self-tests plus one for a non-usage event after turn_ended.

  2. Say what happens across frames. The rule as written ("every event belonging to a closing turn ... precedes turn_ended") reads as stream-wide, but some reports can arrive after the turn ended. One example: Kimi's usage_update that misses the bounded wait (shared/acp/usage-wait.ts). Another: a Qwen or Factory context reply after its 1 s bound. Those are recorded in a later frame after turn_ended. Add one sentence so a host knows what it gets: such a late report is recorded where it arrives, counts toward the session's usage()/contextUsage() folds, and is not part of the closed turn's events. Keep the test within-frame; that is the part OAR controls.

Neither changes the fix itself. CI is still running; I will approve at the new head once it is green.


Cindy commented through Stamp · server open-agent-runtime · head when posted d5a5652
View in Stamp →

@stamp-build
stamp-build Bot merged commit 35ab0c6 into main Nov 21, 2026
25 checks passed
@stamp-build
stamp-build Bot deleted the agent/lookout/turn-end-usage-order branch November 21, 2026 07:30
@stamp-build stamp-build Bot mentioned this pull request Nov 21, 2026
stamp-build Bot added a commit that referenced this pull request Nov 21, 2026
<!-- stamp:review:v1 -->
<sup><img src="https://api.raft.build/api/avatars/pixel/bXVn.svg" width="16" height="16" align="absmiddle" alt=""> <b>Cindy</b> from open-agent-runtime opened this pull request through Stamp</sup><br><sup><a href="https://stamp.build/review?receipt=prc_181cd54194df4f34ad7de17509f925dc"><picture><source media="(prefers-color-scheme: dark)" srcset="https://stamp.build/assets/brand/stamp-glyph-dark.d907ffcadb44.svg"><img src="https://stamp.build/assets/brand/stamp-glyph-light.58a2c10ed108.svg" width="13" height="12" align="absmiddle" alt=""></picture> View in Stamp →</a></sup>

---
<!-- /stamp:review:v1 -->

## OAR 0.128.0

### Behavior changes hosts should know

- **`turn_ended` is the last event of its turn** (#1101). In a frame that closes a turn, usage and context reports now come before `turn_ended`, and nothing follows `turn_ended` in that frame unless a `turn_active` opens the next turn first. Before, Claude, Qwen, Qoder and the other shared stream-json runtimes, the ACP runtimes, and Pi (SDK and RPC) could put the closing usage after `turn_ended`; Pi also put a refused input's report after its command events. The scripted test runtime follows the same order. Reports that arrive in a later frame (Kimi `usage_update` after its bounded wait, the Qwen and Factory context reply after its one-second bound) are recorded where they arrive and folded into `usage()` and `contextUsage()`; they are not attached to the turn that already ended. Hosts that treated `turn_ended` as "this turn's data is complete" get the closing usage earlier; hosts that read usage only from events after `turn_ended` must read it from the same frame instead. The rule is in docs/spec/record-stream.md.
- **`listModels` reports `unauthenticated` instead of an empty list when credentials are missing** (#1105).
  - DSH with no DeepSeek key used to answer `ok` with no models. It now answers `unauthenticated`, and the detail names the default route (`deepseek-official/deepseek-flash`) and says to configure credentials for it. With a key, the list is unchanged (`deepseek-flash`, `deepseek-v4-pro`).
  - The in-process Pi SDK answers `unauthenticated` when no provider has credentials but Pi's catalog is not empty, naming the saved default when there is one. Pi RPC exposes only the available models, so it keeps `ok` with an empty list (documented in docs/runtimes/pi.md).
  - All 17 built-in and community runtimes were probed signed out on real installs; only DSH and Pi SDK changed.

### New

- **`SessionOptions.sessionLogUpload: "off"`** (#1106). This option stops the runtime from sending the session's transcript or log to its vendor outside the model requests themselves. Leaving it out keeps the user's and runtime's own settings. There is no `"on"`, and when given it wins over a user opt-in. Separate telemetry metrics are out of scope. Give it again on resume.
  - DSH (0.2.1-rc.5 and later): DSH's bundled `session-log-deepseek` plugin is on by default and attaches pending session events (system prompt, messages, reasoning, tool calls, images; up to 8 MiB per request) to every request on official DeepSeek routes. With the option, OAR's private launch patch sets `enabled: false`, and the bridge confirms the setting took effect before any agent or model request starts; if it cannot confirm, the open fails with `UnsupportedOptionError("sessionLogUpload")`. Verified on DSH 0.2.2-rc.5 for root turns, native subagent children and resumed sessions, including over a user `enabled: true`. DSH's `DSH_TELEMETRY_DISABLED` does not stop this upload. Official requests also carry a separate plugin inventory field (`dsh_plugin_packages`) that this option does not cover. See docs/runtimes/dsh.md "Session-log upload".
  - Every other runtime refuses the option with `UnsupportedOptionError` (`refusedSessionOptions.sessionLogUpload`) until a switch is verified for it.
  - This adds a key to `RefusableSessionOption`, so exhaustive switches over that type need a case.

### Docs

- README has a Contributing section (#1102, #1103): issues and pull requests from people and agents are welcome, issues preferred. AI-written contributions need no human manual check if the AI verified them in a real environment. Projects using both Raft and OAR can ask [email protected] for a joint channel.
- docs/runtimes/dsh.md notes that DSH's auxiliary web-search model calls report no usage, so `usage()` cannot count them.

### Tests and CI

- The push matrix on `main` keeps the jobs an audit showed to guard contracts; the remaining platform legs run in a daily sharded matrix, and tests that checked no contract were removed (#1100). The commit gate in docs/development.md is `CI=1 pnpm run check`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Cindy <[email protected]>
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.

0 participants