Repository navigation
[reopen #62] /v1/responses: implement SSE streaming so Codex CLI stops crashing - #65
Merged
Merged
Conversation
The Codex CLI (any openai-python ≥ 2 with stream:true on .responses) always sends `"stream": true` and the previous handler returned a hard 400 unsupported_streaming. The SDK doesn't gracefully fall back to non-streaming for that error — it surfaces it as a client crash. PR #61 fixed the non-streaming response shape but never runs in the Codex flow because the request never reaches the success path. This PR replaces the 400 with actual SSE event emission. The tool loop still runs synchronously server-side (Phase A scope — Phase B will add tool passthrough so Codex can execute its own tools); once Loop.Content is set we emit the full Responses-API event sequence in the order the SDK's streaming parser expects: response.created { status:in_progress, output:[] } response.in_progress response.output_item.added { empty message item } response.content_part.added { empty output_text part } response.output_text.delta { full text as a single delta } response.output_text.done response.content_part.done response.output_item.done response.completed { status:completed, full output, usage } The delta is the whole completed text as one chunk rather than true partial streaming — the synchronous tool loop has no incremental text callback exposed at this layer. The SDK accepts a single big delta fine; the user-visible difference is first-byte time matching last-byte time instead of incremental rendering. A follow-up will hook OnText for real partial streaming once tool passthrough is in. New helpers in PasClaw.Gateway.Server: EmitResponsesEvent(Streamer, EventType, Payload): Boolean Writes one SSE frame in the `event: <type>\ndata: <json>\n\n` shape. Bails early if the underlying connection is already closed (client hung up mid- stream). EmitResponsesStream(AContext, AResp, AResponseStarted, RespId, Model, Content, Usage, DebugIO) Sets up the SSE response headers using the same chunked-encoding pattern HandleChatCompletions uses (Cache-Control: no-cache, X-Accel-Buffering: no, Transfer-Encoding: chunked, ContentLength: -1, drain WriteBufferingActive). Builds the message-item / content-part / response objects once, re-serialises them per event using helpers that read like the JSON shapes the SDK validators expect. The added vs done forms differ only by status and part text, so the helpers parameterise cleanly. HandleResponses changes: - Drop the early `if WantsStream then return 400` branch. - Run the tool loop unconditionally; on failure, still emit a 502 JSON because no SSE headers have been committed yet. - On success, branch on WantsStream: WantsStream -> EmitResponsesStream otherwise -> existing WriteJSON path (PR #61 shape) Codex test path that previously failed: Codex CLI POST /v1/responses {stream:true, tools:[…shell, kai, …]} -> tool loop runs server-side -> stream emits text-only response with full event sequence -> openai-python SDK parses without ValidationError, surfaces response.output_text to Codex -> Codex displays the answer Known limitation in this PR (called out for Phase B): Codex sends tool definitions and expects to execute them itself via function_call output items. We currently swallow the request's tools array and run our own internal tool loop, so the model's tool calls (if any) get executed server-side and only the final text reaches Codex. This is fine for read-only questions like "what does file X say" but not for any agentic task where Codex needs to drive the tools. The Phase B PR will pass through tools, do one round-trip (no internal loop), emit function_call output items in the stream, and accept function_call_output items in follow-up requests. https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
…xt events P1 review finding from chatgpt-codex on PR #62 — legit. The openai-python Responses streaming validators require: 1. `sequence_number` (monotonically increasing) on EVERY event in the stream. Missing the field on `response.created` causes the SDK to raise ValidationError on the very first event, before any text reaches the application — exactly the "client chokes" symptom PR #62 was supposed to fix. 2. `logprobs: []` on `response.output_text.delta` and `response.output_text.done` when no logprob data is available (Codex never asks for logprobs but the field is required in the schema regardless). Fix: - Every event-builder helper (CreatedEvent, InProgressEvent, ItemAddedEvent, ContentPartAddedEvent, TextDeltaEvent, TextDoneEvent, ContentPartDoneEvent, ItemDoneEvent, CompletedEvent) now takes `SeqNum: Integer` as its first parameter and embeds `"sequence_number":N` in its JSON payload. - The two text-event helpers additionally emit `"logprobs":[]`. - Three new helpers (CreatedEvent / InProgressEvent / CompletedEvent) replace the inline Format(...) calls in EmitResponsesStream so every event goes through the same "shape" path — no more chance of forgetting sequence_number on a future event addition. - EmitResponsesStream declares a local `Seq: Integer`, initial 0, bumped via `Inc(Seq)` after each emit. The validators reject gaps and duplicates, so the increment after the call (rather than before) keeps the first event at 0. No call-site logic changed — same event order, same content. Only the JSON shape is enriched. Verified against github.com/openai/openai-python src/openai/types/responses/ response_stream_event.py: every event subclass has `sequence_number: int` (required, no default) inherited via the discriminated union; the text events additionally have `logprobs: List[Logprob]` (required field, but defaults are not specified so an empty array is the right "no logprobs requested" value). Test plan additions to PR #62's test plan: - Confirm via curl that each emitted event JSON contains a sequence_number, starting at 0 and incrementing by 1 - openai-python streaming parser progresses past response.created without ValidationError (which is what blocked the previous run) https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
This was referenced May 29, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Re-opening PR #62 which got stranded — it was merged into the
claude/pr61-responses-required-fieldsbranch but never propagated tomainwhen #61 landed. The branch still has the original Phase A streaming work (commits61064b6+ab9f938).Original PR #62 description follows
The Codex CLI (any openai-python ≥ 2 with
stream:trueon.responses) always sends"stream": trueand the previous handler returned a hard 400unsupported_streaming. The SDK doesn't gracefully fall back to non-streaming for that error — it surfaces it as a client crash.PR #61 fixed the non-streaming response shape but never runs in the Codex flow because the request never reaches the success path.
This PR replaces the 400 with actual SSE event emission. The tool loop still runs synchronously server-side (Phase A scope — PR #63 adds tool passthrough); once
Loop.Contentis set we emit the full Responses-API event sequence:The delta is the whole completed text as one chunk (synchronous tool loop has no incremental text callback at this layer). The SDK accepts a single big delta fine — PR #64 adds true partial streaming for the tool-passthrough path.
What this PR contains
EmitResponsesEvent(Streamer, EventType, Payload)event:…\ndata:…\n\nshape; bails early if the connection's closedEmitResponsesStream(AContext, AResp, RespId, Model, Content, Usage, DebugIO)HandleResponseschanges:if WantsStream then return 400branchWantsStream→EmitResponsesStreamvs the existingWriteJSONpathAlso includes the P1 review fix (
sequence_numberon every event +logprobs:[]on text events).Stacking
Stack reopens: this is the bottom of the chain (#62 → #63 → #64 → main). Merge this first; the next PR's diff will automatically shrink to just the next phase's changes.
https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Generated by Claude Code