Repository navigation
/v1/responses: implement SSE streaming so Codex CLI stops crashing - #62
FMXExpress merged 2 commits into
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
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 61064b6d35
ℹ️ 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".
| EmitResponsesEvent(Streamer, 'response.created', | ||
| Format('{"type":"response.created","response":%s}', [CreatedJSON])); |
There was a problem hiding this comment.
Add required fields to Responses SSE events
For stream:true /v1/responses, the first frame emitted here is missing the sequence_number required by the Responses streaming event models, and the same applies to the rest of the event sequence; the text delta/done events also omit the required logprobs array. Current Codex/openai-python validates these events as they arrive, so it will raise a validation error on response.created (or on the text event after sequence numbers are added) instead of rendering the answer. Please emit monotonically increasing sequence_number values on every Responses event and empty logprobs arrays for text events when no logprobs are available.
Useful? React with 👍 / 👎.
…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
[reopen #62] /v1/responses: implement SSE streaming so Codex CLI stops crashing
After Phase A (#62) PasClaw's /v1/responses handler emitted parseable SSE events but ran an internal tool loop — Codex CLI's tool definitions and tool execution lived only client-side, so the model's function_call attempts vanished into PasClaw's fs_/shell_/skills/ handlers instead of reaching Codex. Codex would receive text but never have its `apply_patch` / `shell_command` / `mcp__Kai__*` tools invoked, which is the whole point of running it. This PR adds the passthrough path: 1. Parse request.tools[] -> TToolDefinitionArray of function-type tools, plus ToolsRawJSON capturing the verbatim array for echo in response.tools. Custom-type tools (Codex's grammar-constrained apply_patch) are skipped at the provider boundary -- Anthropic / OpenAI Chat-Completions don't natively support Lark-grammar output constraints -- but they still appear in ToolsRawJSON so the SDK validator doesn't trip. The model just won't attempt them; the user-visible degradation is "model writes apply_patch text directly instead of as a structured tool call." Proper custom-tool support would require provider- side grammar plumbing that's well out of scope. 2. Extend input-item parsing to handle function_call and function_call_output items in addition to the existing message items. function_call -> synthesize an mrAssistant TMessage carrying a single TToolCall with call_id, name, arguments. One per item; consecutive ones group fine with Anthropic / OpenAI's tolerant multi-assistant-message handling. function_call_output -> mrTool TMessage with ToolCallId = call_id and Content = output. Provider request builders match tool_result blocks by this id. Unknown item types (reasoning, image, computer_call, …) are logged at debug and skipped. Phase 2 covers the two Codex needs; the rest are future scope. 3. Branch the execution path: HasFunctionTools = True -> FProvider.Chat(Msgs, ToolDefs, Model, Options). Single round- trip. No internal tool loop. No BuildSystemPrompt either, because Codex sends its own developer message + AGENTS.md and injecting a PasClaw identity preamble on top confuses the model. otherwise -> existing RunToolLoop path (unchanged behaviour for non- Codex flows like curl /v1/responses -d '{"input":"hi"}'). 4. Unify the output via OutContent / OutToolCalls / OutUsage locals so the final EmitResponsesStream / BuildResponsesObject call is the same shape regardless of which path produced them. 5. Extend BuildResponsesObject signature to accept ToolCalls and ToolsRawJSON: function BuildResponsesObject(const Id, Model, Status, Content: string; const ToolCalls: array of TToolCall; const ToolsRawJSON: string; Usage: TUsageInfo): TJsonObject; Each ToolCall produces a function_call output item via the new FunctionCallItemJSON helper: { "id": "fc_<resp-suffix>_<n>", -- item id "type": "function_call", "status": "completed", "call_id": "<tool call id from model>", "name": "<func name>", "arguments": "<raw json string>" -- string per schema } ToolsRawJSON, when non-empty, is pasted verbatim into the response.tools field; otherwise the field is "[]". 6. Extend EmitResponsesStream to emit a function_call sub- sequence per tool call, after any message sub-sequence: response.output_item.added { function_call in_progress, args="" } response.function_call_arguments.delta { full args, one delta } response.function_call_arguments.done response.output_item.done { function_call completed with args } ItemAddedEvent / ItemDoneEvent / ContentPart*Event / Text*Event helpers all gain an OutputIdx parameter so the output_index field tracks which item we're inside; message events stay at index 0, function_calls follow. Two new helpers FunctionCallArgsDeltaEvent / FunctionCallArgsDoneEvent serialize the args-streaming events with the same sequence_number discipline as the text events (PR #62 review fix). Codex test path after this lands: POST /v1/responses {stream:true, tools:[…], input:[…user…]} -> tools parsed; function tools forwarded; custom skipped -> Provider.Chat() single shot -> if model emits text only: standard text sub-sequence (Codex displays the answer) -> if model emits function_call: function_call sub-sequence (Codex executes the tool, posts function_call_output back on the next turn) -> multi-turn agentic loop works end-to-end https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Closes two of the three known limitations from PR #63's description (custom-type grammar tools remain documented future work — that one needs provider-side change to support Lark-grammar output constraints that neither Anthropic nor OpenAI Chat-Completions natively expose). 1. tool_choice forwarding TChatOptions gains a ToolChoice: string field, with the three string forms every provider can represent: "" => emit nothing (provider default; typically "auto" when tools are present) "auto" => model decides "none" => model must not call any tool "required" => model must call one of the tools Provider mappings: Anthropic Messages API: emits tool_choice object alongside tools[]. auto -> {type: "auto"}, required -> {type: "any"}, none -> field omitted (the cleaner Anthropic convention). OpenAI Chat Completions: emits tool_choice as the bare string form ("auto" / "none" / "required") — 1:1 mapping. Gemini: skipped. The generateContent API has tool_config but the mapping is more involved; deferred until a real Gemini Codex-flow user shows up. HandleResponses reads request.tool_choice. Only the three string forms are accepted; the object form (force a specific function by name) is logged at debug and dropped — needs per- provider translation that's substantial enough to be its own PR if a client actually needs it. 2. Real partial streaming The passthrough+stream path now uses Provider.ChatStream with an OnChunk callback that emits response.output_text.delta events as the model produces fragments. Replaces the single-delta whole-text approach from PR #62. First-byte-time improves dramatically for streaming-capable providers (Anthropic streams natively; OpenAI-compat's ChatStream currently delegates to Chat and returns the whole text — for that case the new code feeds the whole text through OnChunk as one synthesized chunk, so the event shape stays consistent). New module-level event helpers Res*Evt() replace the previous local-inside-EmitResponsesStream helpers so both the single-delta (EmitResponsesStream, used by the legacy RunToolLoop path) and the true-streaming (StreamResponsesViaProvider, used by the passthrough path) variants build events from the same code. All take Seq as first arg, all carry the per-event sequence_number openai-python validators require (PR #62 review fix). TResponsesStreamState class holds the streaming state (Streamer, MsgItemId, Seq counter, TextStarted flag, accumulated text, EmptyItem/EmptyPart JSON for lazy message sub-sequence open) and exposes OnChunk as a method-of-object the provider's TStreamCallback can bind to. Event sequence the new path emits: response.created { in_progress, empty output } response.in_progress [ on first text chunk — lazy open ] response.output_item.added { message in_progress } response.content_part.added { empty output_text part } [ per text chunk ] response.output_text.delta { just-this-fragment } [ after ChatStream returns, if any text was emitted ] response.output_text.done { accumulated text } response.content_part.done { full part } response.output_item.done { message completed } [ per tool call in Resp.ToolCalls ] response.output_item.added { function_call in_progress } response.function_call_arguments.delta { full args, one delta } response.function_call_arguments.done response.output_item.done { function_call completed } response.completed { full output, usage } The Codex flow with PR #63 + this PR works end-to-end: incremental text rendering during model output, function_call items streamed back as the model emits them, multi-turn agentic loop with client-side tool execution. HandleResponses dispatch: HasFunctionTools + WantsStream -> StreamResponsesViaProvider (Exit) HasFunctionTools + not stream -> Provider.Chat() + WriteJSON (PR #63 path) not HasFunctionTools + stream -> RunToolLoop + EmitResponsesStream (PR #62 single-delta — RunToolLoop is synchronous so there are no incremental data to stream) not HasFunctionTools + not stream -> RunToolLoop + WriteJSON (legacy) https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Closes two of the three known limitations from PR #63's description (custom-type grammar tools remain documented future work — that one needs provider-side change to support Lark-grammar output constraints that neither Anthropic nor OpenAI Chat-Completions natively expose). 1. tool_choice forwarding TChatOptions gains a ToolChoice: string field, with the three string forms every provider can represent: "" => emit nothing (provider default; typically "auto" when tools are present) "auto" => model decides "none" => model must not call any tool "required" => model must call one of the tools Provider mappings: Anthropic Messages API: emits tool_choice object alongside tools[]. auto -> {type: "auto"}, required -> {type: "any"}, none -> field omitted (the cleaner Anthropic convention). OpenAI Chat Completions: emits tool_choice as the bare string form ("auto" / "none" / "required") — 1:1 mapping. Gemini: skipped. The generateContent API has tool_config but the mapping is more involved; deferred until a real Gemini Codex-flow user shows up. HandleResponses reads request.tool_choice. Only the three string forms are accepted; the object form (force a specific function by name) is logged at debug and dropped — needs per- provider translation that's substantial enough to be its own PR if a client actually needs it. 2. Real partial streaming The passthrough+stream path now uses Provider.ChatStream with an OnChunk callback that emits response.output_text.delta events as the model produces fragments. Replaces the single-delta whole-text approach from PR #62. First-byte-time improves dramatically for streaming-capable providers (Anthropic streams natively; OpenAI-compat's ChatStream currently delegates to Chat and returns the whole text — for that case the new code feeds the whole text through OnChunk as one synthesized chunk, so the event shape stays consistent). New module-level event helpers Res*Evt() replace the previous local-inside-EmitResponsesStream helpers so both the single-delta (EmitResponsesStream, used by the legacy RunToolLoop path) and the true-streaming (StreamResponsesViaProvider, used by the passthrough path) variants build events from the same code. All take Seq as first arg, all carry the per-event sequence_number openai-python validators require (PR #62 review fix). TResponsesStreamState class holds the streaming state (Streamer, MsgItemId, Seq counter, TextStarted flag, accumulated text, EmptyItem/EmptyPart JSON for lazy message sub-sequence open) and exposes OnChunk as a method-of-object the provider's TStreamCallback can bind to. Event sequence the new path emits: response.created { in_progress, empty output } response.in_progress [ on first text chunk — lazy open ] response.output_item.added { message in_progress } response.content_part.added { empty output_text part } [ per text chunk ] response.output_text.delta { just-this-fragment } [ after ChatStream returns, if any text was emitted ] response.output_text.done { accumulated text } response.content_part.done { full part } response.output_item.done { message completed } [ per tool call in Resp.ToolCalls ] response.output_item.added { function_call in_progress } response.function_call_arguments.delta { full args, one delta } response.function_call_arguments.done response.output_item.done { function_call completed } response.completed { full output, usage } The Codex flow with PR #63 + this PR works end-to-end: incremental text rendering during model output, function_call items streamed back as the model emits them, multi-turn agentic loop with client-side tool execution. HandleResponses dispatch: HasFunctionTools + WantsStream -> StreamResponsesViaProvider (Exit) HasFunctionTools + not stream -> Provider.Chat() + WriteJSON (PR #63 path) not HasFunctionTools + stream -> RunToolLoop + EmitResponsesStream (PR #62 single-delta — RunToolLoop is synchronous so there are no incremental data to stream) not HasFunctionTools + not stream -> RunToolLoop + WriteJSON (legacy) https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
What was actually wrong
The log line you pasted shows
responses <-— that's incoming. The 48 KB JSON is the request body Codex CLI sent. Buried in it:"stream": true. The current handler:returns a hard 400
unsupported_streaming, and the openai-python SDK doesn't gracefully fall back on that — it surfaces it to the client as a parse / crash. PR #61's non-streaming shape fix never runs because the request never reaches the success path.The
client_metadata.x-codex-installation-id+$CODEX_HOMEreferences confirm this is Codex CLI, which always streams.What this PR ships
Replaces the 400 with actual SSE event emission. The tool loop still runs server-side (Phase A scope — see below); once
Loop.Contentis set we emit the full Responses-API event sequence in the order the SDK's streaming parser expects:The delta is the whole text as one chunk rather than true partial streaming — the synchronous tool loop has no incremental text callback exposed at this layer. SDK accepts this; the user-visible difference is first-byte time matching last-byte time instead of incremental rendering.
New helpers in
PasClaw.Gateway.ServerEmitResponsesEvent(Streamer, EventType, Payload): Booleanevent: …\ndata: …\n\nshape; bails early if the connection's closedEmitResponsesStream(AContext, AResp, …, Content, Usage, DebugIO)HandleChatCompletions), then the 9-event sequence aboveHandleResponseschangesif WantsStream then return 400branchWantsStream→EmitResponsesStreamvs the existingWriteJSONpath (PR /v1/responses: emit fields the openai-python SDK marks required #61's shape)What this fixes for you
Codex CLI POST
/v1/responses {stream:true, tools:[…]}previously got 400; now it gets a parseable SSE stream andresponse.output_textreaches Codex. You can ask read-only questions ("is the structure of pasclaw.dpr normal?") and Codex displays the answer.What this doesn't fix yet (Phase B)
Codex sends a
toolsarray and expects to execute its own tools (Kai MCP, shell_command, apply_patch) viafunction_calloutput items in the stream. 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 works for read-only questions but not for agentic tasks. The Phase B PR will:
request.tools[]→ provider tool definitionsfunction_calloutput items +response.function_call_arguments.deltaevents in the streamfunction_call_outputinput items on follow-up requestsI'll ship that as the next PR once you've verified this one unblocks the immediate crash.
Stacked on PR #61
When PR #61 lands, this PR's base auto-rebases to
mainand the diff collapses to just the streaming commit.Test plan
pasclaw serve→ point Codex CLI at it → "is the structure of pasclaw.dpr normal?" — model answer streams back, Codex displays it, no SDK ValidationErrorcurl -N -X POST http://127.0.0.1:8088/v1/responses -d '{"model":"…","input":"hi","stream":true}'— see the 9 events flow past in order, ending withresponse.completedstream:false) — unchanged, still goes through PR /v1/responses: emit fields the openai-python SDK marks required #61's JSON pathstream:true— emits 502 JSON (no SSE headers committed before failure)EmitResponsesEventbails early onStreamer.Closed, no crashhttps://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Generated by Claude Code