Skip to content

fix(openai-shim): always emit message_delta with usage to match Claude Code stream protocol - #2599

Merged
kevincodex1 merged 2 commits into
Twigpine:mainfrom
slx618:fix/openai-shim-message-delta-usage
Dec 4, 2026
Merged

kevincodex1 merged 2 commits into
Twigpine:mainfrom
slx618:fix/openai-shim-message-delta-usage

Conversation

@slx618

@slx618 slx618 commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • openaiStreamToAnthropic emitted a message_delta without a usage object whenever the finish_reason chunk carried no usage, then a second delta once usage arrived on a later chunk.
  • Providers that deliver finish_reason and usage on separate chunks (Aliyun MaaS, OpenRouter) hit this on every streamed assistant message. Claude Code's stream protocol always carries usage on message_delta, so SDK consumers that read event.usage unguarded (e.g. Claudian, any includePartialMessages listener) crash with Cannot read properties of undefined (reading 'input_tokens').
  • Fix: defer the terminal message_delta until usage is available (or the stream ends), so exactly one delta is emitted and it always carries a usage object; the truncated-stream path gets a zeroed usage. Also keeps the most recently seen chunk usage so a usage-before-finish ordering is no longer dropped.

Impact

  • user-facing: Agent-SDK hosts pointed at OpenClaude over OpenAI-compatible providers stop crashing on message_delta; usage accounting is preserved (compaction and cost tracking read it).
  • developer/maintainer: stream-shape guarantee is now protocol-conformant (single terminal delta, always with usage) — documented in code comments; five stream tests updated to pin the new shape.

Testing

  • I followed Validation, including applicable lint/static/type checks and regression tests.
  • affected surfaces and selected checks: root source + test change under src/services/api/openaiShim/ → core checks + focused provider-stream regression tests.
  • for follow-ups, prior validated revision and unaffected results reused: follow-up e04864d3 (drop dead hasEmittedFinalUsage assignment flagged by CodeQL — one-line deletion, no behavior change) reran the focused stream suite and the intent scan; all other results from the initial revision remain applicable (inputs unchanged).
  • exact commands and results:
    • bun run test ./src/services/api/openaiShim/ — 489 pass / 0 fail (5 assertions updated to the new single-delta shape; rerun green after e04864d3).
    • bun run test ./src/services/api/openaiShim/requestExecutor.integration.test.ts ./src/services/api/openaiShim/requestExecutor.test.ts — 240 pass / 0 fail.
    • bun run check:static — pass (0 ESLint errors; 7 pre-existing any warnings in src/entrypoints/sdk*, unchanged by this PR).
    • bun run typecheck:type-tests — pass (11 files).
    • node bin/openclaude --version and NODE_DISABLE_COMPILE_CACHE=1 node bin/openclaude --version — both print 0.37.0 (OpenClaude).
    • bun run build — succeeds; runtime re-check of the failing shape: message_delta count: 1, all have usage: True.
    • PR intent scan: git fetch https://github.com/Twigpine/openclaude.git main && bun run security:pr-scan -- --base FETCH_HEAD --head HEAD — no suspicious additions (rerun after follow-up commit).
  • focused tests: covered above (streamConversion + requestExecutor integration).
  • inapplicable checks and reasons; blocked checks, platform limits, or verified pre-existing failures:
    • bun run typecheck:fast is blocked locally: its script shells out to bun check from the filesystem root, and the local Bun 1.3.11 has no check builtin (error: Script not found "check"). bun run typecheck (tsc) was run instead — no errors in the changed files; the reported errors are pre-existing in unrelated files (e.g. src/components/HighlightedCode/Fallback.test.tsx, src/entrypoints/sdk/sdkUtilityTypes.ts) and exist on the base as well. CI runs the authoritative typecheck:fast.
    • Website checks not applicable (no web/ inputs changed).
  • CI and CodeRabbit status: CodeQL useless-assignment finding resolved by e04864d3; monitoring the re-run.

Notes

  • provider/model path tested: Aliyun MaaS compatible-mode (glm-5.3) via a live --print --output-format stream-json --include-partial-messages run before/after the fix (two deltas → one delta with usage); unit tests cover the split finish/usage chunk shape directly.
  • screenshots attached (if UI changed): n/a, no UI change.
  • follow-up work or known limitations: none.

Summary by CodeRabbit

  • Bug Fixes
    • Streaming responses now consistently include token usage information when completion events arrive without usage data, retaining usage reported earlier in the stream.
    • Responses that end without a finish reason also include usage information, defaulting token counts to zero when none was provided.
    • Completion events are emitted in a consistent order, including when a response contains no choices: text is followed by a terminal completion event and then the stop event.

…e Code stream protocol

Some providers (Aliyun MaaS, OpenRouter) deliver finish_reason and usage
on separate chunks; the shim emitted a usage-less message_delta first,
crashing SDK consumers (e.g. Claudian) that read event.usage unguarded.
Defer the terminal delta until usage arrives or the stream ends, with a
zeroed usage fallback.
@coderabbitai

coderabbitai Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The stream converter retains the latest available usage and includes it in terminal message_delta events. If usage is unavailable, it supplies zero-valued token fields. Tests cover completion paths and event ordering.

Changes: Streaming usage completion

Layer / File(s) Summary
Capture and emit terminal usage
src/services/api/openaiShim/streamConversion.ts, src/services/api/openaiShim/streamConversion.test.ts
The converter retains converted usage from stream chunks. Terminal deltas include the latest usage or zero-valued token fields. Tests cover finish reasons, incomplete streams, tool-call completion, [DONE], and event ordering.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Suggested reviewers: jatmn, chioarub

Merge Risk: Minimal · up to e0486

Streamed responses now always end with a single message_delta that includes usage, so consumers that read usage unguarded should no longer crash. The change is small and localized, and I found no remaining merge-blocking risk.

Pre-merge checks: Passed 5 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Risk Surface Disclosed Warning Summary: The check applies. The PR changes the OpenAI-compatible provider shim (src/services/api/openaiShim/streamConversion.ts and its test). That code converts provider streams into the Anthro… Add a risk-surface statement to the PR description or to a maintainer review comment. It should: 1. Name the touched surface: provider routing via src/services/api/openaiShim/ (OpenAI-compatible provider stream-to-Anthropic conversion, te…
Passed Passed checks: 5 passed

Check name Status Explanation
Title check Passed The title uses a conventional fix(openai-shim) prefix and names the change: terminal message_delta always carries usage to match the Claude Code stream protocol. The diff defers the terminal delta unt…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description follows the repository template and covers the Summary, Impact, and Testing sections in detail. It states the root cause: a message_delta without usage was emitted, followed by a secon…
No Hidden Policy Change Passed The check is inapplicable to this change set, so it passes. The PR (slx618, #2599, Twigpine/openclaude, base main) changes two files: src/services/api/openaiShim/streamConversion.ts and its test fil…
Full details: Title check

Explanation

The title uses a conventional fix(openai-shim) prefix and names the change: terminal message_delta always carries usage to match the Claude Code stream protocol. The diff defers the terminal delta until usage arrives or the stream ends, and updates tests to match. The title is specific and matches the main change. It is somewhat long at 91 characters, but the title requirements only ask for concise, scoped, and accurate titles, so this does not block the check.

Full details: Description check

Explanation

The description follows the repository template and covers the Summary, Impact, and Testing sections in detail. It states the root cause: a message_delta without usage was emitted, followed by a second delta. It names the fix (defer the terminal delta, zero usage on truncated streams, retain latest chunk usage). It lists exact commands, results, the blocked typecheck:fast step with its reason, and a live provider run. The Notes section covers the provider/model path tested. Minor gaps: the CI and CodeRabbit status line is still pending (CodeQL finding resolved by e04864d, re-run being monitored), and the author does not confirm whether CI is green. The template asks for this before maintainer review. The Impact and Testing sections are otherwise complete.

Full details: No Hidden Policy Change

Explanation

The check is inapplicable to this change set, so it passes. The PR (slx618, #2599, Twigpine/openclaude, base main) changes two files: src/services/api/openaiShim/streamConversion.ts and its test file. Both changes are confined to the stream-shape logic for message_delta. The change defers the terminal delta until usage is available or the stream ends, retains the latest chunk usage, and uses zeroed usage on the truncated-stream path. A keyword scan of the added lines found no telemetry, network endpoint, routing default, permission, trust-model, or consent changes. The only keyword hit was a code comment. The PR body and objectives describe the same protocol fix and do not mention any policy change. The change is a bug fix in the stream protocol. It does not alter product, trust, routing, telemetry, or permission policy, so no maintainer policy alignment is required.

Full details: Risk Surface Disclosed

Explanation

Summary: The check applies. The PR changes the OpenAI-compatible provider shim (src/services/api/openaiShim/streamConversion.ts and its test). That code converts provider streams into the Anthropic stream protocol, so it sits on the provider-routing surface. No risk-surface callout appears in the review record. Evidence: - Changed files (git diff --name-status): streamConversion.ts and streamConversion.test.ts only. - The diff changes terminal message_delta emission. It defers the delta until usage arrives or the stream ends, and it adds a ZERO_USAGE fallback and a lastStreamUsage retention path. - Review comments: "No CodeRabbit review threads were returned." No review text calls out the provider-routing surface or states a blocker decision. - PR description: the Impact section covers user-facing crash avoidance for Agent-SDK hosts and usage accounting. It does not name the provider-routing or stream-protocol surface as a risk, and it does not state whether the risk is a blocker. Its Testing section lists the validation runs, which is not a risk-surface callout. - Primary PR identity: Twigpine/openclaude PR #2599, base main, head fix/openai-shim-message-delta-usage, author slx618. Assessment: The provider-routing surface is touched. The required callout (surface named, blocker status stated) is absent. The likely blocker status is non-blocking, because the change is a stream-shape fix with tests, but the review does not say so. Blocking: The missing risk-surface disclosure is the single blocking item. The code change itself is not assessed here as defective. Non-blocking: The described validation is extensive. It does not replace the required disclosure.

Resolution

Add a risk-surface statement to the PR description or to a maintainer review comment. It should: 1. Name the touched surface: provider routing via src/services/api/openaiShim/ (OpenAI-compatible provider stream-to-Anthropic conversion, terminal message_delta shape). Note that no auth, permission, outbound-network, background-execution, startup/config, skills/plugins/MCP, CI, or release-script code changes, if that is accurate. 2. State the blocker status explicitly. For example: "Not a blocker. Single terminal delta with usage; no provider-routing or auth change," or name the blocker if one exists. 3. Note the affected consumers: OpenAI-compatible providers and SDK consumers that read event.usage. Once that statement is posted, re-run this check.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between d59b24d and e04864d.

Files selected for processing: 1

  • src/services/api/openaiShim/streamConversion.ts
Files with no reviewable changes: 1

  • src/services/api/openaiShim/streamConversion.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

Recent review details

Context from checks skipped due to timeout: 11

  • GitHub Check: CodeRabbit
  • GitHub Check: unit-tests (8)
  • GitHub Check: unit-tests (5)
  • GitHub Check: unit-tests (2)
  • GitHub Check: unit-tests (4)
  • GitHub Check: unit-tests (1)
  • GitHub Check: unit-tests (3)
  • GitHub Check: unit-tests (7)
  • GitHub Check: smoke-and-tests
  • GitHub Check: typecheck
  • GitHub Check: CodeQL (javascript-typescript)
Additional context used

Learnings: 1

Common learnings

Learnt from: CR
Repo: Twigpine/openclaude PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-10-29T17:48:03.316Z
Learning: Source excerpt:
# AGENTS.md - AI Agent Coding Guide

## Things To Avoid

- Do not skip tests for behavior changes.
Learnt from: CR
Repo: Twigpine/openclaude PR: 0
File: CONTRIBUTING.md:0-0
Timestamp: 2026-11-04T04:34:30.318Z
Learning: Applicability reference:
AGENTS.md: # AGENTS.md - AI Agent Coding Guide
This guide is for AI coding agents working in the OpenClaude repository. Read it before changing code, and also follow [CONTRIBUTING.md](CONTRIBUTING.md) for contributor policy, PR expectations, review follow-up, and project scope.

AGENTS.md: # AGENTS.md - AI Agent Coding Guide
## Work Style
- For new features, larger refactors, dependencies, or runtime changes, follow the issue-first guidance in [CONTRIBUTING.md](CONTRIBUTING.md).

AGENTS.md: # AGENTS.md - AI Agent Coding Guide
## Work Style
- Keep PR branches mergeable using [CONTRIBUTING.md § Keep Your Branch Current](CONTRIBUTING.md#keep-your-branch-current). Rebase for conflicts or a specific maintainer-requested upstream dependency, not routinely for every follow-up. Never overwrite remote PR-head updates with an unguarded force-push.

AGENTS.md: # AGENTS.md - AI Agent Coding Guide
## Work Style
- Apply [CONTRIBUTING.md § Validation](CONTRIBUTING.md#validati...
Learnt from: CR
Repo: Twigpine/openclaude PR: 0
File: CONTRIBUTING.md:0-0
Timestamp: 2026-10-31T02:49:58.324Z
Learning: Applicability reference:
AGENTS.md: # AGENTS.md - AI Agent Coding Guide
This guide is for AI coding agents working in the OpenClaude repository. Read it before changing code, and also follow [CONTRIBUTING.md](CONTRIBUTING.md) for contributor policy, PR expectations, review follow-up, and project scope.

AGENTS.md: # AGENTS.md - AI Agent Coding Guide
## Work Style
- For new features, larger refactors, dependencies, or runtime changes, follow the issue-first guidance in [CONTRIBUTING.md](CONTRIBUTING.md).

AGENTS.md: # AGENTS.md - AI Agent Coding Guide
## Work Style
- Keep PR branches mergeable using [CONTRIBUTING.md § Keep Your Branch Current](CONTRIBUTING.md#keep-your-branch-current). Rebase for conflicts or a specific maintainer-requested upstream dependency, not routinely for every follow-up. Never overwrite remote PR-head updates with an unguarded force-push.

AGENTS.md: # AGENTS.md - AI Agent Coding Guide
## Work Style
- Apply [CONTRIBUTING.md § Validation](CONTRIBUTING.md#validati...

coderabbitai[bot]
coderabbitai Bot previously approved these changes Dec 4, 2026
@kevincodex1
kevincodex1 merged commit 7f971ac into Twigpine:main Dec 4, 2026
28 checks passed
@slx618
slx618 deleted the fix/openai-shim-message-delta-usage branch December 4, 2026 06:07
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.

3 participants