Skip to content

[reopen #62] /v1/responses: implement SSE streaming so Codex CLI stops crashing - #65

Merged
FMXExpress merged 2 commits into
mainfrom
claude/pr62-responses-streaming
May 29, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/pr62-responses-streaming

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Re-opening PR #62 which got stranded — it was merged into the claude/pr61-responses-required-fields branch but never propagated to main when #61 landed. The branch still has the original Phase A streaming work (commits 61064b6 + ab9f938).

Original PR #62 description follows

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 — PR #63 adds tool passthrough); once Loop.Content is set we emit the full Responses-API event sequence:

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 (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

Helper Purpose
EmitResponsesEvent(Streamer, EventType, Payload) Writes one SSE frame in event:…\ndata:…\n\n shape; bails early if the connection's closed
EmitResponsesStream(AContext, AResp, RespId, Model, Content, Usage, DebugIO) Headers + nested-buffer drain + the 9-event sequence above

HandleResponses changes:

  • Drop the early if WantsStream then return 400 branch
  • Run tool loop unconditionally; on failure still emit 502 JSON
  • On success branch on WantsStream → EmitResponsesStream vs the existing WriteJSON path

Also includes the P1 review fix (sequence_number on 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

claude added 2 commits May 28, 2026 23:20
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
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.

2 participants