Repository navigation
fix(providers): CLI bridges decode split UTF-8, keep the timeout on the child, and read the Gemini session id - #304
Conversation
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.
|
Warning Review limit reached
This review includes 10 billable files and costs up to $2.50.
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. View limit details
Comment |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Reviewer's GuideUpdates 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
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
PR Summary by Qodotest(providers): cover CLI subprocess bridge regressions
AI Description
Diagram
High-Level Assessment
Files changed (1)
|
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.
There was a problem hiding this comment.
💡 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".
Code Review by Qodo
1.
|
…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.
## [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))
|
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 Reported, not changed (P2):
Checked and found as described: the decoder flushes at the end of stdout ( |
Summary
Five follow-ups for the
claude-code-cliandgemini-cliproviders, 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 insrc/core/llm/providers/__tests__/cli-providers-subprocess.test.tsand 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-sdk0.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 (nosetEncodinganywhere inlib/), 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 oneStringDecoderper stream (lib/transform/encoding-transform.jsL25-29 and L42-51; L8: "subprocess.stdout|stderremits Buffers").Fix: one
StringDecoder('utf8')per stream holds an incomplete character until its last byte arrives, andend()flushes it when stdout ends (Node v22.23.3lib/string_decoder.jsL94-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
timeoutfrom the spawn (killAfterTimeout,lib/terminate/timeout.jsL12-21) and settles the run once the process has exited and its stdio streams have finished (waitForSubprocessResult,lib/resolve/wait-subprocess.jsL83-114, throughlib/resolve/stdio.jsL19-46 andlib/resolve/wait-stream.jsL6-21). When the timer fires first, execa callskill(), which does nothing to a process that has exited, still waits for the streams (L115-125), and fails the run withtimedOutand the exit code the process had (getAsyncResultinlib/methods/main-async.js;lib/return/result.jsL151-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 intoTIMEOUTafter 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:
lib/internal/streams/state.jsL12) cannot leave the CLI until the consumer reads: oncepush()returns false, Node stops reading the pipe (onStreamRead,lib/internal/stream_base_commons.jsL189-197). With a slow consumer the timer then fires while the CLI is still writing, and kills it.lib/return/result.jsL151-175). A CLI that exited 0 by itself before the timer and one that caught the SIGTERMkill()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 forresult.stdout(buffer: trueandmaxBuffer: 100_000_000by default,lib/arguments/specific.jsL98-101), and pastmaxBufferit destroys stdout (lib/io/max-buffer.jsL7-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, withtimedOutand exit code 0 when the timer fired first. The CLI writes its reply and exits at once, the provider'srequestTimeoutis 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-jsonrun,{ type: 'init', session_id, model }(InitEvent,packages/core/src/output/types.tsL44-48; written atpackages/cli/src/nonInteractiveCli.tsL252-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 atpackages/cli/src/utils/errors.tsL81-90, carry none).GeminiCLIBridge.parseStreamEventreadsession_idfrom the result line only, so no stream's result had asessionId.parseStreamEventsees 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()handsparseStreamEventa second argument, aStreamParseContextobject 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 declaresparseStreamEvent(raw), or calls it with one argument, compiles as before.StreamParseContextis 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 withsession_id, the prompt's echo, an assistant delta and a result without the field must end with a result whosesessionIdis 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'sProcessTransportturns a non-zero exit intoClaude Code process exited with code N(getProcessExitError,sdk.mjsL136), and itsQuery.readMessageskeeps the text of the last error result (theresultof asuccesssubtype, otherwise theerrorseach trimmed, the blank ones left out, joined with;) and replaces any exit error but an abort withClaude Code returned an error result: <text>(the "Replacing exit error with result text" branch,sdk.mjsL136; the abort it keeps is itsAbortError). At exit 0,parseJsonResulttook an error subtype's message fromresult ?? message ?? response ?? stdout; the subtypeserror_during_execution,error_max_turns,error_max_budget_usdanderror_max_structured_output_retrieshave noresult(SDKResultError,sdk.d.tsL5729-5784), so the provider's error wasClaude Code returned an error: {"type":"result",...}.Fix:
BridgeResultgains an optionalerror, the failure's message, set besideisError, asStreamEventhas since fix(providers): CLI bridges read the current stream shapes, end the child on early close, and keep error causes #289.ClaudeCodeCLIBridge.parseJsonResultfills it with the message fix(providers): CLI bridges read the current stream shapes, end the child on early close, and keep error causes #289 built for the stream (errorResultMessage: the result text of an API error, or the subtype followed by the trimmed, non-blank errors joined with;), andClaudeCodeProvider.generateCompletion()reads it there.resultholds what it held before, as fix(providers): CLI bridges read the current stream shapes, end the child on early close, and keep error causes #289 kept it for the stream.execute()reads stdout as a JSON result too. If the bridge'sparseJsonResultflags it as an error, a new protected hook,classifyErrorResult(result, error), builds the error; its default isclassifyError(error), so a bridge that does not override it classifies the failure as before.ClaudeCodeCLIBridgeoverrides it with theCRASHEDerror an error result stands for,Claude Code returned an error: <message>, with the exit code and stderr indetails. A call the caller cancelled is classified as before (REQUEST_ABORTED), as the SDK keeps an abort. The error is built in one place,ClaudeCodeProviderError.fromErrorResult(), which the provider's own error for an error result now uses as well.handleError,packages/cli/src/utils/errors.tsL94-106), so its bridge keeps the default.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_turnsresult witherrors: [];generateCompletion()must reject withCRASHEDandClaude Code returned an error: error_max_turns.5. A reply Claude Code returned in structured_output was not read
ClaudeCodeCLIBridge.buildArgspasses--json-schemawheneverjsonSchemais set (ClaudeCodeCLIBridge.tsL58-60), andClaudeCodeProvidersets 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'sstructured_output(SDKResultSuccess.structured_output,sdk.d.tsL5860; the SDK'soutputFormat: { type: 'json_schema' }, L1969-1980, which it hands to the CLI as--json-schema,sdk.mjsL136). Such a turn ends with no trailing assistant message, on a tool result followed by astructured_outputattachment that holds the turn's output (the note on end-turn tool sessions,sdk.d.tsL2123-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:
BridgeResultand the resultStreamEventgain an optionalstructuredOutput, whichClaudeCodeCLIBridgefills fromstructured_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 itstext.UNVERIFIED: what Claude Code writes in
resultwhen it returns structured output. The SDK does not say, and the CLI ships as compiled binaries (@anthropic-ai/claude-code2.1.296 installs a platform package), so its source was not read. The fix does not depend on it:structured_outputis 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 ongenerateCompletionStream()(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) anddocs/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
StreamEvent.result(fix(providers): CLI bridges read the current stream shapes, end the child on early close, and keep error causes #289's migration note stands).GEMINI_CLI_EXP_AGENT.Linked issues
Follows #289 and #296.
Type of change
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 asHi \ufffd\ufffd\ufffd; the slow consumer's stream ended withTIMEOUT(Claude Code CLI timed out.,Gemini CLI timed out.); the result'ssessionIdwasundefined; neither error result's message was the subtype's (at exit 1 it was the bridge'sClaude 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.ts46 tests,CLISubprocessBridge.test.ts,ClaudeCodeCLIBridge.test.tsandGeminiCLIBridge.test.tspassing 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;
resultkeeps what it held.Checklist
!before the colon for a change that breaks users (feat!:orfeat(api)!:).