Skip to content

fix(providers): CLI bridges decode split UTF-8, keep the timeout on the child, and read the Gemini session id - #304

Merged
jddunn merged 11 commits into
masterfrom
fix/cli-bridge-followups-3
Oct 11, 2026
Merged

jddunn merged 11 commits into
masterfrom
fix/cli-bridge-followups-3

Conversation

@jddunn

@jddunn jddunn commented Oct 11, 2026 •

Copy link
Copy Markdown
Member

Summary

Five follow-ups for the claude-code-cli and gemini-cli providers, from the review of #289 (0.13.45) after #296 (0.13.48). Each section gives the defect, the source it was confirmed in, the fix and its test. The tests are in src/core/llm/providers/__tests__/cli-providers-subprocess.test.ts and run each provider on its real bridge, with execa stubbed in execa 10's error and stream shapes. The test commits went up first, on master's code, and the fixes after them (see How this was verified).

Sources read: execa 10.0.1 (the version in pnpm-lock.yaml); @anthropic-ai/claude-agent-sdk 0.3.296, the latest on npm (sdk.d.ts, sdk.mjs); google-gemini/gemini-cli at 9b6e0265, its default branch's tip; Node v22.23.3 (CI runs Node 22).

1. A character split between two reads of stdout came out as U+FFFD

CLISubprocessBridge.stream() decoded each piece of stdout on its own (buffer += chunk.toString()). The child's stdout gives Buffers: execa 10.0.1 sets no encoding on it (no setEncoding anywhere in lib/), and a pipe hands over what the CLI has written so far, wherever a character's bytes end. A multi-byte UTF-8 character split between two reads became replacement characters, in the text delta and in the reply. execa decodes its own copy of the output, result.stdout, through one StringDecoder per stream (lib/transform/encoding-transform.js L25-29 and L42-51; L8: "subprocess.stdout|stderr emits Buffers").

Fix: one StringDecoder('utf8') per stream holds an incomplete character until its last byte arrives, and end() flushes it when stdout ends (Node v22.23.3 lib/string_decoder.js L94-120; write() returns a string chunk as it is).

Test: "a character whose bytes two reads of stdout split", for both providers. The reply Hi 😀 (U+1F600, four bytes) is read in two pieces split after the character's second byte; the text delta and the final reply carry it whole.

2. A consumer slower than the timeout turned a finished run into TIMEOUT

execa 10.0.1 runs a run's timeout from the spawn (killAfterTimeout, lib/terminate/timeout.js L12-21) and settles the run once the process has exited and its stdio streams have finished (waitForSubprocessResult, lib/resolve/wait-subprocess.js L83-114, through lib/resolve/stdio.js L19-46 and lib/resolve/wait-stream.js L6-21). When the timer fires first, execa calls kill(), which does nothing to a process that has exited, still waits for the streams (L115-125), and fails the run with timedOut and the exit code the process had (getAsyncResult in lib/methods/main-async.js; lib/return/result.js L151-175). stream() read stdout only as its consumer asked for events, and Node ends a stream only once its buffered data has been read. A consumer slower than the timeout therefore turned a run that wrote its whole reply and exited 0 into TIMEOUT after the reply, and in the providers that error took the place of the final chunk, tool calls included.

Two fixes were open: read stdout eagerly, or take a timeout that fires after a clean exit for a success. The second does not cover the case:

  • A reply larger than the pipe's buffer and the stream's buffer (64 KiB by default, Node v22.23.3 lib/internal/streams/state.js L12) cannot leave the CLI until the consumer reads: once push() returns false, Node stops reading the pipe (onStreamRead, lib/internal/stream_base_commons.js L189-197). With a slow consumer the timer then fires while the CLI is still writing, and kills it.
  • The error of a timed-out run carries the exit code and signal the process ended with (lib/return/result.js L151-175). A CLI that exited 0 by itself before the timer and one that caught the SIGTERM kill() sent at the timer and then exited 0 give the same fields.

Fix: stream() reads stdout as the CLI writes it, into a queue its generator yields from. The run settles when the CLI exits, whatever the consumer's pace, so the timeout measures the CLI. The queue holds the events of output the consumer has not taken yet, at most the run's whole output. execa keeps that output in memory anyway for result.stdout (buffer: true and maxBuffer: 100_000_000 by default, lib/arguments/specific.js L98-101), and past maxBuffer it destroys stdout (lib/io/max-buffer.js L7-20), which ends the reading. A consumer that stops reading early still ends the process, and the bridge now also destroys stdout, as the stream's own iterator did when the generator read it directly. #296's handling of the run's outcome from the start is unchanged.

Test: "a consumer slower than the timeout", for both providers. The stub settles the run as execa does with a timeout: the timer runs from the spawn, and the run settles once stdout has ended, with timedOut and exit code 0 when the timer fired first. The CLI writes its reply and exits at once, the provider's requestTimeout is 200 ms, and the consumer spends 400 ms on each chunk. The stream must end with the whole reply and its final chunk.

3. A Gemini CLI stream carried no session id

The Gemini CLI writes the session id on the init event that opens a stream-json run, { type: 'init', session_id, model } (InitEvent, packages/core/src/output/types.ts L44-48; written at packages/cli/src/nonInteractiveCli.ts L252-260), and its result event has no such field (ResultEvent, types.ts L101-109; the results written at nonInteractiveCli.ts L403-411, L562-570 and L595-601, and at packages/cli/src/utils/errors.ts L81-90, carry none). GeminiCLIBridge.parseStreamEvent read session_id from the result line only, so no stream's result had a sessionId.

parseStreamEvent sees one line at a time, and one bridge serves concurrent streams (each provider holds a single bridge), so the id cannot be kept on the bridge. Fix: stream() hands parseStreamEvent a second argument, a StreamParseContext object of its own for each stream, the same one for every line of that stream. The Gemini bridge keeps the init event's id there and gives it to the result, and a result line that carries an id of its own keeps it. The parameter is optional in the abstract signature, so a subclass that declares parseStreamEvent(raw), or calls it with one argument, compiles as before. StreamParseContext is exported from @framers/agentos/sandbox/subprocess.

Test: "the session id of a stream", on GeminiCLIBridge.stream() as a direct reader takes it: an init event with session_id, the prompt's echo, an assistant delta and a result without the field must end with a result whose sessionId is the init event's. A second case, a result line that carries its own id, passes on master's code as well and pins that reading.

4. A Claude Code error result was dropped when the CLI exited non-zero, and became the whole JSON line at exit 0

execute(), the non-streaming path, classified a failed run from stderr and execa's fields alone; the JSON result on stdout was dropped. Claude Code can exit non-zero after a result it flags as an error: the SDK's ProcessTransport turns a non-zero exit into Claude Code process exited with code N (getProcessExitError, sdk.mjs L136), and its Query.readMessages keeps the text of the last error result (the result of a success subtype, otherwise the errors each trimmed, the blank ones left out, joined with ; ) and replaces any exit error but an abort with Claude Code returned an error result: <text> (the "Replacing exit error with result text" branch, sdk.mjs L136; the abort it keeps is its AbortError). At exit 0, parseJsonResult took an error subtype's message from result ?? message ?? response ?? stdout; the subtypes error_during_execution, error_max_turns, error_max_budget_usd and error_max_structured_output_retries have no result (SDKResultError, sdk.d.ts L5729-5784), so the provider's error was Claude Code returned an error: {"type":"result",...}.

Fix:

UNVERIFIED, left unchanged: the exit code Claude Code uses after each error subtype. The SDK handles any non-zero code, and so does the fix.

Test: "a non-streaming call whose result Claude Code flags as an error", exit codes 0 and 1: stdout holds an error_max_turns result with errors: []; generateCompletion() must reject with CRASHED and Claude Code returned an error: error_max_turns.

5. A reply Claude Code returned in structured_output was not read

ClaudeCodeCLIBridge.buildArgs passes --json-schema whenever jsonSchema is set (ClaudeCodeCLIBridge.ts L58-60), and ClaudeCodeProvider sets it to its tool-call schema whenever tools are present. With a JSON schema, Claude Code returns the reply that matches it in the result's structured_output (SDKResultSuccess.structured_output, sdk.d.ts L5860; the SDK's outputFormat: { type: 'json_schema' }, L1969-1980, which it hands to the CLI as --json-schema, sdk.mjs L136). Such a turn ends with no trailing assistant message, on a tool result followed by a structured_output attachment that holds the turn's output (the note on end-turn tool sessions, sdk.d.ts L2123-2131). The provider parsed only the result text: generateCompletion() took a reply it could not parse as the tool-call shape for a schema failure and ran the CLI a second time without the schema, and the stream ended with that text as the reply.

Fix: BridgeResult and the result StreamEvent gain an optional structuredOutput, which ClaudeCodeCLIBridge fills from structured_output. The provider reads the reply from it when it is there and parses the result text as before when it is not. A text reply in structured output ends the stream with its text.

UNVERIFIED: what Claude Code writes in result when it returns structured output. The SDK does not say, and the CLI ships as compiled binaries (@anthropic-ai/claude-code 2.1.296 installs a platform package), so its source was not read. The fix does not depend on it: structured_output is read first, and the result text is the fallback it was before.

Test: "a reply Claude Code returns as structured output", a tool call and a text reply, on generateCompletion() (one run, which carried --json-schema) and on generateCompletionStream() (the final chunk). The result text in the stub is empty.

Docs

docs/features/CLI_ERROR_CODES.md (TIMEOUT: the timeout measures the CLI; CRASHED: execute() after an error result and a non-zero exit; SCHEMA_PARSE_FAILED; the bridge's reading of stdout) and docs/getting-started/CLI_PROVIDERS.md (the base class's reading of stdout, Claude Code's structured output, the Gemini CLI's session id).

Left as they are

Linked issues

Follows #289 and #296.

Type of change

  • Bug fix
  • Feature
  • Performance
  • Documentation
  • Refactor
  • Tests
  • Build or CI

How this was verified

CI only; nothing was run on a workstation. The test commits went up first, on master's code, and the fixes after them.

  • Red, the tests on master's code: CI run 38136487312 on 4c30835, Tests 11 failed | 10052 passed | 64 skipped | 5 todo. The 11 are the new tests but one: the Gemini case of a result line that carries its own session id passes on master's code and pins that reading. Each failed on its defect: the split character came out as Hi \ufffd\ufffd\ufffd; the slow consumer's stream ended with TIMEOUT (Claude Code CLI timed out., Gemini CLI timed out.); the result's sessionId was undefined; neither error result's message was the subtype's (at exit 1 it was the bridge's Claude Code CLI exited unexpectedly (code 1).); and the structured output ended as an empty text reply (finishReason: 'stop', content: '').

  • Green, the fixes and the docs: CI run 38136979741 on 02393a1, Tests 10069 passed | 64 skipped | 5 todo, cli-providers-subprocess.test.ts 46 tests, CLISubprocessBridge.test.ts, ClaudeCodeCLIBridge.test.ts and GeminiCLIBridge.test.ts passing as before; Browser tests, Batch-1 gated tests and the release dry run green. The totals of the two runs differ by six tests of the vision suites (VisionPipeline.test.ts, createVisionPipeline.gemini.e2e.test.ts), whose count varies between runs; this change does not touch them.

Migration notes

None. Every field and the hook are optional additions; result keeps what it held.

Checklist

  • Tests cover the changed behavior.
  • Docs are updated.
  • The title follows Conventional Commits, with ! before the colon for a change that breaks users (feat!: or feat(api)!:).
  • No secrets or private data are included.
  • Every automated review thread is settled (how).
  • I have read this change and can explain every line.

Each CLI provider streams a reply whose four-byte character the stub's
stdout hands over in two pieces, split after its second byte, as a pipe
does. The text delta and the final reply must carry the character whole.
The stub settles the run as execa 10 does with a timeout: the timer runs
from the spawn, and the run settles once the CLI has exited and its stdout
has ended. The CLI writes its reply and exits 0 at once; the consumer
spends twice the timeout on each chunk. The stream must end with the whole
reply and its final chunk, not with a timeout.
The current Gemini CLI writes the session id on the init event that opens
a stream-json run, and its result event has no such field. A direct reader
of GeminiCLIBridge.stream() must get the id on the result event; a result
line that carries an id of its own keeps it.
generateCompletion() runs a CLI whose JSON result is an error_max_turns
result with no errors listed, and the CLI exits 0 or 1 after it. Either
way the call must reject with the error subtype as its message, not with
the result's whole JSON line nor with a classification of stderr alone.
With tools present the provider passes --json-schema, and Claude Code
returns the reply that matches the schema in the result's
structured_output. A tool call or a text reply returned there must reach
the caller from generateCompletion() in one run and from
generateCompletionStream() as its final chunk.
@jddunn
jddunn requested a review from Victor-Evogor as a code owner October 11, 2026 11:41
@sourcery-ai

sourcery-ai Bot commented Oct 11, 2026

Copy link
Copy Markdown

Sorry @jddunn, you've used your own review budget of 250,000 diff characters for the last 7 days.

You can request another review in 4 hours and 10 minutes by commenting @sourcery-ai review. Upgrade to get a review now.

@coderabbitai

coderabbitai Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

  • Run on-demand review

This review includes 10 billable files and costs up to $2.50.

  • Ask an admin to make reviews automatic

Open in CodeRabbit

Reviews can continue after your included limit without a manual trigger. An admin must approve usage-based billing.

Or wait 25 seconds for your next included review.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Configuration used: Repository: framerslab/agentos/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Team
  • Run ID: e1397114-3950-4e25-adb4-0e3f599c2d05

📥 Commits

Reviewing files that changed from the base of the PR and between a9cad59 and 02393a1.


📒 Files selected for processing (10)
  • docs/features/CLI_ERROR_CODES.md
  • docs/getting-started/CLI_PROVIDERS.md
  • src/core/llm/providers/__tests__/cli-providers-subprocess.test.ts
  • src/core/llm/providers/errors/ClaudeCodeProviderError.ts
  • src/core/llm/providers/implementations/ClaudeCodeCLIBridge.ts
  • src/core/llm/providers/implementations/ClaudeCodeProvider.ts
  • src/core/llm/providers/implementations/GeminiCLIBridge.ts
  • src/safety/sandbox/subprocess/CLISubprocessBridge.ts
  • src/safety/sandbox/subprocess/index.ts
  • src/safety/sandbox/subprocess/types.ts

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-11T11:43:20.610484Z 4c30835 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@sourcery-ai

sourcery-ai Bot commented Oct 11, 2026

Copy link
Copy Markdown

Reviewer's Guide

Updates both CLI providers and their shared subprocess bridge to safely decode streamed UTF-8, decouple timeout measurement from consumer backpressure, recover Gemini session IDs, preserve Claude error results, and consume Claude structured output, with focused execa-shaped integration tests and documentation.

File-Level Changes

Change Details Files
Make CLI subprocess streaming robust to fragmented UTF-8 and slow consumers without letting consumer backpressure affect timeout behavior.
  • Decode stdout incrementally with a per-stream UTF-8 StringDecoder and flush it at stream end.
  • Read subprocess stdout eagerly into an event queue while the async generator yields at consumer pace.
  • Preserve cleanup behavior when consumers stop reading and retain existing timeout outcome handling.
src/core/llm/providers/claude-code-cli.ts
src/core/llm/providers/gemini-cli.ts
src/safety/sandbox/subprocess/types.ts
src/safety/sandbox/subprocess/index.ts
Add per-stream parsing context and propagate Gemini session identifiers from initialization to result events.
  • Pass an optional context object through all lines parsed by a stream.
  • Store Gemini init session_id in stream-local context and apply it to results lacking an id.
  • Retain result-provided session IDs and preserve compatibility for existing parseStreamEvent implementations.
src/core/llm/providers/claude-code-cli.ts
src/core/llm/providers/gemini-cli.ts
src/safety/sandbox/subprocess/types.ts
Preserve and classify Claude Code error results from both successful and failed subprocess executions.
  • Add optional BridgeResult error data and parse Claude error subtype messages consistently for streaming and non-streaming paths.
  • Parse stdout JSON even when execa reports a failed run and classify Claude error results as CRASHED with exit and stderr details.
  • Keep cancellation behavior and default bridge error classification unchanged.
src/core/llm/providers/claude-code-cli.ts
src/core/llm/providers/claude-code.ts
src/core/llm/providers/gemini-cli.ts
Support Claude Code structured_output as the authoritative completion payload.
  • Expose structured_output on bridge results and result stream events.
  • Prefer structured output for tool-call or text completion parsing, falling back to the existing result text path.
  • Avoid unnecessary second CLI invocations when schema-backed tool responses are returned.
src/core/llm/providers/claude-code-cli.ts
src/core/llm/providers/claude-code.ts
src/safety/sandbox/subprocess/types.ts
Expand subprocess integration coverage and document the corrected provider behavior.
  • Test split UTF-8 characters, slow consumers, Gemini session IDs, Claude error results, and structured-output replies against both real bridges.
  • Model execa 10 failure fields and timeout behavior in subprocess stubs.
  • Document timeout semantics, error-result handling, stdout reading, session IDs, and structured output.
src/core/llm/providers/__tests__/cli-providers-subprocess.test.ts
docs/features/CLI_ERROR_CODES.md
docs/getting-started/CLI_PROVIDERS.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

test(providers): cover CLI subprocess bridge regressions

🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Add regression tests for split UTF-8 output and consumers slower than the subprocess timeout.
Diagram

graph TD
  Tests["Regression tests"] --> Providers["CLI providers"] --> Bridges["Real bridges"] --> Mock["Mocked execa"] --> Fixtures["Subprocess fixtures"]
  Tests --> Bridges
  Providers --> Assertions["Response assertions"]
  Bridges --> Assertions
Loading
High-Level Assessment

Keep the real-bridge, stubbed-execa approach: it makes byte boundaries, process settlement, and exit codes deterministic without requiring installed or authenticated CLIs. The supplied diff contains tests only, while the checked-out bridge still decodes chunks independently and reads stdout on consumer demand; these assertions need the corresponding fixes before they can pass.

Files changed (1) +283 / -8

Tests (1) +283 / -8
cli-providers-subprocess.test.tsExercise five CLI bridge regressions with subprocess fixtures +283/-8

Exercise five CLI bridge regressions with subprocess fixtures

• Extends the execa failure stub with stdout and timeout details, then adds tests for split UTF-8 bytes, slow stream consumers, and Gemini init-event session IDs. Claude Code cases assert error-result classification at exit codes 0 and 1 and structured-output replies for both completion paths. This diff adds expectations, not the bridge or provider fixes described in the PR summary.

src/core/llm/providers/tests/cli-providers-subprocess.test.ts

stream() decoded each piece of stdout on its own. The child's stdout gives
Buffers (execa 10 sets no encoding on it) and a pipe read ends wherever
the CLI's write did, so a multi-byte character split between two reads
came out as replacement characters in the reply. One StringDecoder per
stream now holds such a character until its last byte arrives, and is
flushed when stdout ends, as execa decodes its own copy of the output.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4c30835d16

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Emoji replies are corrupted across reads ✓ Resolved
Description
CLISubprocessBridge.stream() still calls toString() on each stdout chunk independently, so the
split character in the new fixture becomes replacement characters. When either CLI delivers a
multibyte character across two reads, both the text delta and final reply fail the new assertions.
Code

src/core/llm/providers/tests/cli-providers-subprocess.test.ts[R749-751]

+    // U+1F600 takes four bytes in UTF-8, and the first read ends after two of them.
+    const reply = 'Hi \u{1F600}';
+    stubCli(binary, () => splitRun(fixture.reply(reply), '\u{1F600}'));
Evidence
The fixture splits the emoji's bytes between two Buffers, while the bridge converts each Buffer to a
string before joining them.

src/core/llm/providers/tests/cli-providers-subprocess.test.ts[735-761]
src/safety/sandbox/subprocess/CLISubprocessBridge.ts[265-268]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The new split-character test fails because the bridge decodes each Buffer separately.
## Fix Focus Areas
- src/safety/sandbox/subprocess/CLISubprocessBridge.ts[263-269]
- src/core/llm/providers/__tests__/cli-providers-subprocess.test.ts[747-761]
## Recommended Fix
Use one UTF-8 StringDecoder for each stream invocation, write each chunk through it, and flush it at stdout EOF before parsing the remaining line.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Slow readers lose completed replies ✓ Resolved
Description
CLISubprocessBridge.stream() reads stdout only when its event consumer resumes the generator,
leaving the run unsettled during the pause in the new test. With the consumer paused beyond the
configured timeout, the stub rejects the run as timed out and the providers produce an error final
chunk instead of the completed reply.
Code

src/core/llm/providers/tests/cli-providers-subprocess.test.ts[R806-809]

+    for await (const chunk of provider.generateCompletionStream(model, HELLO, {})) {
+      chunks.push(chunk);
+      // A consumer that spends longer than the timeout on each chunk.
+      if (!chunk.isFinal) await new Promise((resolve) => setTimeout(resolve, 2 * timeout));
Evidence
The helper settles its run only when stdout has been fully consumed; the bridge's for await stops
advancing at each yielded event. The test deliberately holds an event for twice the timeout before
requesting the rest.

src/core/llm/providers/tests/cli-providers-subprocess.test.ts[776-818]
src/safety/sandbox/subprocess/CLISubprocessBridge.ts[265-293]
src/core/llm/providers/implementations/ClaudeCodeProvider.ts[449-466]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The slow-consumer test fails because stdout consumption waits for each event consumer, allowing the subprocess timeout to fire after the CLI has supplied its reply.
## Fix Focus Areas
- src/safety/sandbox/subprocess/CLISubprocessBridge.ts[253-301]
- src/core/llm/providers/__tests__/cli-providers-subprocess.test.ts[776-818]
## Recommended Fix
Start draining stdout as soon as the subprocess starts, queue parsed events for the generator, and preserve subprocess error handling and early-consumer-exit cleanup.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Gemini replies lose their session IDs ✓ Resolved
Description
GeminiCLIBridge.parseStreamEvent() does not handle the init event and obtains a result's session
ID only from that result line. When the new fixture supplies the ID on init but not on result,
the bridge drops the former and yields a result without the expected ID.
Code

src/core/llm/providers/tests/cli-providers-subprocess.test.ts[R834-837]

+        { type: 'init', timestamp: at, session_id: 'g1', model: 'gemini-3.5-flash' },
+        { type: 'message', timestamp: at, role: 'user', content: 'Hello' },
+        { type: 'message', timestamp: at, role: 'assistant', content: 'Hi there', delta: true },
+        { type: 'result', timestamp: at, status: 'success' },
Evidence
The first fixture places session_id exclusively on init; the Gemini parser has no init branch,
and its result branch reads only raw.session_id. The base stream discards null parse results.

src/core/llm/providers/tests/cli-providers-subprocess.test.ts[830-853]
src/core/llm/providers/implementations/GeminiCLIBridge.ts[121-174]
src/safety/sandbox/subprocess/CLISubprocessBridge.ts[272-278]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The new Gemini test fails because the bridge drops the init event's session ID before parsing the result.
## Fix Focus Areas
- src/safety/sandbox/subprocess/CLISubprocessBridge.ts[97-106]
- src/safety/sandbox/subprocess/CLISubprocessBridge.ts[263-286]
- src/core/llm/providers/implementations/GeminiCLIBridge.ts[121-174]
## Recommended Fix
Create parsing context separately for each stream, pass it to event parsing, store the init session ID there, and use it for results without their own ID.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View action required (2)
4. Claude errors lose their actual message ✓ Resolved
Description
execute() classifies a rejected subprocess without parsing its stdout, while its successful-exit
JSON parser falls back to the entire JSON line when an error result has no result field. For the
new error_max_turns fixture, exit code 1 produces a generic process error and exit code 0 produces
an error containing serialized JSON, so neither meets the asserted message.
Code

src/core/llm/providers/tests/cli-providers-subprocess.test.ts[R879-882]

+    await expect(provider.generateCompletion('claude-sonnet-4-6', HELLO, {})).rejects.toMatchObject({
+      code: 'CRASHED',
+      message: 'Claude Code returned an error: error_max_turns',
+    });
Evidence
The test supplies an error subtype but no result text. The successful path substitutes
stdout.trim() for that missing text; the failure path immediately calls classifyError(error),
which never reads error.stdout.

src/core/llm/providers/tests/cli-providers-subprocess.test.ts[865-882]
src/safety/sandbox/subprocess/CLISubprocessBridge.ts[113-127]
src/safety/sandbox/subprocess/CLISubprocessBridge.ts[166-187]
src/core/llm/providers/implementations/ClaudeCodeProvider.ts[315-320]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Neither exit-code case in the new Claude error-result test reports the result subtype as its error message.
## Fix Focus Areas
- src/safety/sandbox/subprocess/CLISubprocessBridge.ts[113-127]
- src/safety/sandbox/subprocess/CLISubprocessBridge.ts[166-187]
- src/core/llm/providers/implementations/ClaudeCodeCLIBridge.ts[128-148]
- src/core/llm/providers/implementations/ClaudeCodeProvider.ts[315-320]
## Recommended Fix
Preserve a parsed result's error message, parse available stdout on failed runs, and classify a Claude error result using that message while retaining caller-abort classification.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Structured Claude replies are discarded ✓ Resolved
Description
ClaudeCodeCLIBridge does not expose structured_output, and ClaudeCodeProvider parses only the
result text. With the new fixtures' empty result and populated structured_output, non-streaming
calls retry without the schema and streaming calls finish without the expected tool call or text.
Code

src/core/llm/providers/tests/cli-providers-subprocess.test.ts[R922-924]

+    result: '',
+    structured_output: structured,
+    session_id: 's1',
Evidence
Both new tests put their expected response only in structured_output. The bridge's JSON and stream
mappings omit that field, and the provider parses result.result or event.result, which the
fixture sets to an empty string.

src/core/llm/providers/tests/cli-providers-subprocess.test.ts[895-961]
src/safety/sandbox/subprocess/CLISubprocessBridge.ts[113-127]
src/core/llm/providers/implementations/ClaudeCodeCLIBridge.ts[91-107]
src/core/llm/providers/implementations/ClaudeCodeProvider.ts[315-334]
src/core/llm/providers/implementations/ClaudeCodeProvider.ts[409-443]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The new structured-output fixtures fail because neither Claude completion path reads their reply payload.
## Fix Focus Areas
- src/safety/sandbox/subprocess/types.ts[39-70]
- src/core/llm/providers/implementations/ClaudeCodeCLIBridge.ts[91-107]
- src/core/llm/providers/implementations/ClaudeCodeProvider.ts[315-334]
- src/core/llm/providers/implementations/ClaudeCodeProvider.ts[409-443]
## Recommended Fix
Expose structured output on Claude bridge results and result events, then prefer it when constructing tool-call or text responses; retain result text as the fallback.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Tip of the day
💡 Did you know, you can tweak Display settings with a live preview to see your comment before it ships

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

…asures the CLI

execa runs a run's timeout until the run settles, and settles it once the
process has exited and its stdout has ended. stream() read stdout only as
its consumer asked for events, and a stream ends only once its data has
been read, so a consumer slower than the timeout turned a run that wrote
its whole reply and exited 0 into a timeout, and the providers' final
chunk became that error. A reply larger than the pipe and the stream's
buffer could not even leave the CLI before the consumer caught up.

stream() now reads stdout as the CLI writes it, into a queue its generator
yields from, and the run settles when the CLI exits. The queue holds at
most the run's output, which execa keeps in memory for result.stdout up
to its maxBuffer anyway. A consumer that stops early still ends the
process, and the bridge also destroys stdout, as the stream's own iterator
did when the generator read it.
…t event

The Gemini CLI writes the session id on the init event that opens a
stream-json run, and its result event has no such field. The bridge read
the id from the result line only, so no stream had one.

parseStreamEvent sees one line at a time, and one bridge serves concurrent
streams, so stream() now hands it a second argument: a StreamParseContext
of its own for each stream, the same object for every line. The parameter
is optional, so a subclass that declares parseStreamEvent(raw) compiles as
before. The Gemini bridge keeps the init event's id there for the result,
and a result line with an id of its own keeps it. StreamParseContext is
exported from the subprocess module.
… at any exit code

execute() classified a failed run from stderr and execa's fields alone and
dropped the JSON result on stdout, though Claude Code can exit non-zero
after a result it flags as an error; its SDK replaces such an exit's error
with the result's text unless the run was aborted. At exit 0 the base
parseJsonResult took an error subtype's message from
result ?? message ?? response ?? stdout, and the subtypes have no result,
so the provider reported the result's whole JSON line.

BridgeResult gains an optional error, the failure's message, as
StreamEvent has; the Claude bridge fills it with the message the stream
already builds, and the provider reads it there. When a run fails and the
caller did not cancel it, execute() reads stdout as a JSON result too, and
a result the bridge flags as an error goes to a new protected hook,
classifyErrorResult(), whose default is classifyError(). The Claude bridge
reports the CRASHED error the result stands for, built in one place,
ClaudeCodeProviderError.fromErrorResult(), which the provider uses too.
The Claude bridge passes --json-schema whenever a call sets jsonSchema,
and the provider sets it to its tool-call schema whenever tools are
present. With a schema, Claude Code returns the reply that matches it in
the result's structured_output, and such a turn ends with no assistant
message of its own. The provider parsed only the result text:
generateCompletion() took a reply it could not parse for a schema
failure and ran the CLI again without the schema, and a stream ended with
that text as the reply.

BridgeResult and the result StreamEvent gain an optional
structuredOutput, which the Claude bridge fills from structured_output.
The provider reads the reply there when it is present, and parses the
result text as before when it is not. A text reply in structured output
ends a stream with its text.
…ession id

CLI_ERROR_CODES: the timeout measures the CLI; the Claude Code bridge's
execute() reports an error result followed by a non-zero exit as CRASHED,
through classifyErrorResult(); the provider reads a tool-call reply from
structured_output first; stream() reads stdout as the CLI writes it, as
one UTF-8 stream. CLI_PROVIDERS: the same for the base class, Claude
Code's structured output, and the Gemini CLI's session id on its init
event.
@jddunn
jddunn merged commit fe4dcee into master Oct 11, 2026
11 checks passed
@jddunn
jddunn deleted the fix/cli-bridge-followups-3 branch October 11, 2026 11:56
github-actions Bot pushed a commit that referenced this pull request Oct 11, 2026
## [0.13.52](v0.13.51...v0.13.52) (2026-10-11)

### fix

* **providers:** CLI bridges decode split UTF-8, keep the timeout on the child, and read the Gemini session id (#304) ([fe4dcee](fe4dcee))
@jddunn

jddunn commented Oct 11, 2026

Copy link
Copy Markdown
Member Author

Cold read of this change behind its merge (fe4dcee, 0.13.52). Line numbers are at fe4dcee.

Fixed forward, P1: #307 (a08104f9, released in 0.13.53). Since stream() reads stdout as the CLI writes it, execa settles the run when the CLI exits, and execa fails a run for its cancelSignal only until the run settles (execa 10.0.1 lib/terminate/cancel.js L15-20, lib/methods/main-async.js L187). A caller's abort that landed after the CLI had exited, while the consumer was still taking the queued events, ended the stream as a success: both providers yielded the reply or the tool call instead of the abort chunk IProvider requires (IProvider.ts L264-268), and the GMI, which ends a stopped turn on that chunk, went on to run the step's tool calls. Before this change the run settled at the consumer's pace, so such an abort failed it with isCanceled, except while the consumer was busy with the events of stdout's last read, a narrower window the old code's own comment names. #307 checks the signal when the consumer asks past the last event and classifies an aborted call as REQUEST_ABORTED, which closes both windows. Its test, for both providers, was red on this change's code (run 38139859211) and is green with the fix (runs 38140095863 and 38141318852). A review thread on #307 found that its docs placed the end of the window at the consumer taking the last event; the code places it at the end of the stream, where a provider yields its final chunk, and 8da7cdc words the docs that way.

Reported, not changed (P2):

  • A text reply Claude Code returns in structured_output reaches the stream's final chunk as message.content but as no responseTextDelta (ClaudeCodeProvider.ts L447-458). streamText() and StreamingReconstructor build the text from the deltas alone (streamText.ts L915-921, StreamingReconstructor.ts L52), so a tool-enabled streamText() call that ends in such a reply resolves text to ''. The GMI reads the final content when no delta came, so it is not affected. The text was '' before this change too.
  • execute() now calls parseJsonResult() on a failed run's stdout without a guard (CLISubprocessBridge.ts L271-274). A bridge whose override throws on output that is not JSON makes execute() throw that exception, not a CLISubprocessError. The two bridges in this repository both catch, so neither is affected.

Checked and found as described: the decoder flushes at the end of stdout (decoder.end() joined to the last line), and an early stop drops only what no consumer reads any more; the queue has no backpressure by design and is bounded by execa's maxBuffer, past which execa destroys stdout (lib/io/max-buffer.js L7-20); in stream(), a non-zero exit and a timeout are classified as before; the Gemini result keeps its own session_id over the init event's; execute() keeps its result for a success and for stdout that is not JSON; no exported type is narrowed; the tests run each provider on its real bridge with execa stubbed, and the red run 38136487312 shows each failing on its defect.

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