Repository navigation
fix(stream): emit usage before turn_ended in closing frames - #1101
Conversation
|
CHANGES @ d5a5652 The reorder is right and the sweep is complete for usage: ACP
Neither changes the fix itself. CI is still running; I will approve at the new head once it is green.
|
<!-- 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]>
Summary
Fix the closing-frame event order across all OAR adapters so
turn_endedis the last event of its turn, including within a single frame.Previously, ACP (
shared/acp/turns.tsfinishRequest), Claude/stream-json (result.after), Pi SDK/RPC (agent_settled),scriptedRuntime, and the sea-trialmocksession emittedusageafterturn_endedin the closing frame. Consumers that finalize per-turn summaries atturn_endeddropped 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 (followingturn_active, as in Pi Durable's view handover or Grok's deferred native turn) remain afterturn_ended.Requested by Cindy in
#core:#394.Release notes
Fixes
usagebeforeturn_endedacross all runtimes. Hosts that finalize per-turn token, cache, or context summaries when observingturn_endedonSession.events()now receive the turn's closingusageevent first on ACP runtimes (Antigravity, CodeBuddy, Devin, Grok, Kimi, OpenCode), Claude, Pi SDK/RPC, andscriptedRuntime. Events belonging to a subsequent turn that starts on the same frame still followturn_endedafter aturn_activeevent.Changes
docs/spec/record-stream.md: added the stream rule stating thatturn_endedis the last event of its turn, so every event of that turn (including its closingusage) precedesturn_ended, also within one frame, while next-turn events followturn_activeafterturn_ended. Fixed Example 1 (resultframe order).docs/runtimes/claude.md,docs/runtimes/pi.md,docs/runtimes/grok.md,docs/runtimes/agents-api.md: updated tables and prose that listedturn_endedbeforeusage.packages/oar/src/shared/acp/turns.ts: emitframe.context(usage) beforeturn_endedinfinishRequest, keepingcloseTurn(state)(Grok's deferred next-turnturn_active) afterturn_ended.packages/oar/src/shared/stream-json/profile.tsandprojection.ts: removedresult.afterfromStreamJsonProjectionProfile.resultso no stream-json dialect can emit events afterturn_endedon aresultframe.packages/oar/src/runtimes/claude/projection.ts: movedusageintoresult.before(afterservice_tier, beforeturn_ended).packages/oar/src/runtimes/qwen/projection.tsandqoder/projection.ts: removed unusedafter: [].packages/oar/src/runtimes/pi/projection.ts: emit contextusagebeforeturn_endedonagent_settled.packages/oar/src/runtimes/pi/session.tsandrpc/session.ts: prependrefusedInputbeforecommand.body.eventson pre-agent_startsettlement so nothing can land afterturn_ended.packages/oar/src/testing/scripted-runtime.tsandsea-trial/fixtures/mock-session.ts: emitusagebeforeturn_endedinscripted/endandmock/end.sea-trial/harness/stream-order.tsandsea-trial/cases/session.ts: addedassertNoUsageAfterTurnEndedchecking 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, nousagefollowsturn_endedunless aturn_activecomes 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-turnturn_active), Qwen, Qoder, Factory, Cursor, DSH, Pi Durable (including view handoverusage -> turn_ended -> turn_active), Morph, Cybion,scriptedRuntime, andmock.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_endedandusageemitters)packages/oar/src/shared/acp/turns.ts(finishRequest, covers Antigravity, CodeBuddy, Devin, Grok, Kimi, OpenCode v1/v2): changed (usagemoved beforeturn_ended; deferred next-turnturn_activestays afterturn_ended).packages/oar/src/shared/acp/records.ts(Grok spontaneousturn_completed): unchanged (tokenUsage.extensionis already pushed beforenativeTurns.project).packages/oar/src/shared/stream-json/projection.ts,profile.ts,runtimes/claude/projection.ts: changed (removedresult.after; moved Claudeusageintoresult.before).packages/oar/src/runtimes/qwen/projection.ts,runtimes/qoder/projection.ts: changed (removed unusedafter: [];usagewas already inresult.before).packages/oar/src/runtimes/pi/projection.ts,pi/session.ts,pi/rpc/session.ts: changed (agent_settledcontextusagemoved beforeturn_ended;refusedInputprepended).packages/oar/src/runtimes/pi-durable/projection.ts,session.ts: unchanged (settingsEventswithusagealready precedesturn_ended, andturn_activeplus next-run events stay afterturn_ended).packages/oar/src/runtimes/factory/projection.ts,session.ts: unchanged (agent_turn_completedalready emitsusagebeforeturn_ended, andsession.tsafterappends only next-turnturn_activefor a missed steer).packages/oar/src/runtimes/codex/projection.ts,token-usage.ts: unchanged (thread/tokenUsage/updatedandturn/completedare separate frames;turn_endedis already last onturn/completed).packages/oar/src/runtimes/cursor/projection.ts: unchanged (turn-endedandmodel-call-completedusage deltas precedecursor/run_result/cursor/run_failed, whereturn_endedis already last).packages/oar/src/runtimes/dsh/projection.ts: unchanged (assistant/messageandassistant/attemptemitusagein their own frames beforeturn/end, which emits onlyturn_ended).packages/oar/src/community/morph/projection.ts,tracker.ts: unchanged (topic/metadataemits contextusagebeforefoldMorphTask, whereturn_endedis already last).packages/oar/src/community/cybion/tracker.ts: unchanged (emitUsagerecordsthread/usagebeforefinishrecordsturn_ended).packages/oar/src/testing/scripted-runtime.ts: changed (usagemoved beforeturn_ended).sea-trial/fixtures/mock-session.ts: changed (usagemoved beforeturn_ended).Verification
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]), andOAR_TEST=pi-aimock(agent_settled:[turn_ended, usage]).d5a56523:CI=1 pnpm run check:typecheckpassed,oxlint --type-aware --deny-warnings0 warnings / 0 errors on 1913 files,vitest run561 passed / 3 skipped / 0 failed (5403 passed / 110 skipped),sea-trialmock19 passed / 1 skipped / 0 failed.sea-trialruns:scripted18 passed / 2 skipped / 0 failed;pi-aimock18 passed / 2 skipped / 0 failed;pi-rpc-aimock18 passed / 2 skipped / 0 failed;pi-durable-aimock19 passed / 1 skipped / 0 failed.