Skip to content

fix(ai): unify Responses stream processing - #114263

Merged
steipete merged 4 commits into
mainfrom
codex/responses-stream-canonical
Jul 27, 2026
Merged

steipete merged 4 commits into
mainfrom
codex/responses-stream-canonical

Conversation

@steipete

@steipete steipete commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Related: #114230

What Problem This Solves

OpenClaw had two private OpenAI Responses stream processors with different state models and observable correctness gaps. Interleaved output items could be misrouted, raw reasoning deltas could disappear, unterminated streams could report success, terminal encrypted reasoning and compatible-provider output could be lost, and finalized tool calls could retain streaming-only scratch state.

Why This Change Was Made

This replaces both legacy processors with one indexed canonical processor owned by the private Responses transport module. The OpenAI, Azure, ChatGPT SSE, and ChatGPT WebSocket callers now converge on that implementation; mapCodexEvents remains the only Codex alias/error adapter. Transport timing/debug/cooperative scheduling stays in an iterator wrapper, while terminal recovery, usage, signatures, slot routing, and failure validation settle once in the canonical machine.

The provider-side processor and its forwarding surface are deleted. The private structural event union is not exported from any public @openclaw/ai entrypoint. text_delta.partial is omitted globally, matching the llm-core optional-field memory contract.

AI-assisted: implemented and reviewed with Codex under maintainer direction.

User Impact

Responses-based OpenAI, Azure, and ChatGPT/Codex streams now preserve interleaved reasoning/text/tool output, fail closed on malformed or unterminated streams, recover compatible terminal-only output safely, and persist replayable reasoning/tool results without streaming scratch fields.

Evidence

  • node scripts/run-vitest.mjs packages/ai/src/transports/openai-responses-stream-parity.test.ts packages/ai/src/providers/openai-responses-shared.test.ts packages/ai/src/providers/openai-responses.test.ts packages/ai/src/providers/azure-openai-responses.test.ts packages/ai/src/providers/openai-chatgpt-responses.test.ts packages/ai/src/providers/openai-chatgpt-responses.retry.test.ts packages/ai/src/providers/openai-responses-terminal-usage.test.ts — 152 passed on the rebased head
  • node scripts/run-vitest.mjs src/agents/openai-transport-stream.base.test.ts src/agents/openai-transport-stream.streaming.test.ts src/agents/openai-transport-stream.incomplete-output.test.ts src/agents/openai-transport-stream.replay-and-tools.test.ts — 139 passed on the rebased head
  • /Users/steipete/.claude/skills/autoreview/scripts/autoreview --mode branch --base origin/main — clean, no accepted/actionable findings
  • Hosted Testbox run 30232572256 — production and test typechecks passed; its initial lint run exposed the max-lines split subsequently fixed without suppression
  • Targeted boundary lint/type generation, formatting, max-lines ratchet, and git diff --check — pass after the final split
  • Exact-head CI run 30235912543 attempt 2 at c93725c5ab8b81869aa353a11927e7462e8ab8bf — success, including build artifacts, prod/test types, lint, dead-code dependencies/exports, package boundaries, all selected Node shards, and openclaw/ci-gate; the unrelated TUI PTY flake passed on its targeted rerun

ClawSweeper reports no code findings and asks the landing orchestrator to add or explicitly waive live OpenAI/Azure/ChatGPT provider-stream proof before merge. This worker stopped at the batch-authorized exact-head CI boundary and did not start credentialed live-provider traffic.

Divergence Fix Checklist

  • Indexed non-tool routing — indexed interleaved reasoning items
  • Full reasoning event coverage — raw reasoning delta with empty summary
  • Strict terminal validation — stream close without terminal response
  • Terminal encrypted-reasoning backfill — terminal encrypted reasoning backfill
  • Null completed-message snapshot protection — null completed message content preserves streamed text
  • Streaming scratch cleanup — finalized tool call drops streaming scratch
  • Fail-closed active slot reuse — reused indexed output slot fails closed

Additional canonical fixtures cover terminal-only compatible output, deltas without content-part events, terminal failures, nullable terminal recovery, and deferred text materialization across an unindexed tool boundary.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Jul 27, 2026
@steipete
steipete marked this pull request as ready for review July 27, 2026 03:33
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Jul 27, 2026
@clawsweeper

clawsweeper Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 27, 2026, 12:22 AM ET / 04:22 UTC.

ClawSweeper review

What this changes

The branch replaces separate private OpenAI Responses stream processors with one transport-owned indexed processor, updating OpenAI, Azure, and ChatGPT/Codex callers plus regression coverage for terminal, reasoning, text, and tool-call state.

Merge readiness

⚠️ Ready for maintainer review - 5 items remain

This PR remains necessary: it is the implementation follow-up to the merged parity-fixture baseline and consolidates private Responses stream handling across OpenAI, Azure, and ChatGPT/Codex callers. The supplied diff and prior review cycles show no discrete patch defect, and the contributor has now posted real OpenAI provider-stream evidence; keep it open for the protected maintainer review path and refresh the current-base proof before merge.

Priority: P2
Reviewed head: b8386fca7ca29047030de55a95eff84177dce092
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The PR has focused regression coverage, successful reported exact-head validation, and direct live OpenAI evidence; remaining confidence work is current-base refresh and a maintainer decision on optional provider lanes.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The contributor posted redacted after-fix live OpenAI Responses evidence from a hydrated Linux/Node 24 Testbox: 4/4 tests passed through the shared canonical processor, including a real structured tool call and terminal result; Azure is optional and no ChatGPT live lane is available.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The contributor posted redacted after-fix live OpenAI Responses evidence from a hydrated Linux/Node 24 Testbox: 4/4 tests passed through the shared canonical processor, including a real structured tool call and terminal result; Azure is optional and no ChatGPT live lane is available.
Evidence reviewed 5 items Merged baseline fixture: The related parity-fixture pull request established the shared private event contract and regression matrix before this implementation; it merged as commit 7846a32.
Canonical processor integration: The proposed head moves processResponsesStream into the private transport stream module and changes OpenAI/ChatGPT callers to use that shared implementation, while retaining provider-specific request and service-tier adapters.
Caller coverage: The branch updates the OpenAI Responses client and ChatGPT Responses SSE/WebSocket paths, and the supplied focused test list covers OpenAI, Azure, ChatGPT, retry, terminal-usage, agent streaming, incomplete-output, and replay/tool paths.
Findings None None.
Security None None.

How this fits together

Responses-based providers emit streamed OpenAI-compatible events into OpenClaw’s AI transport layer. The transport validates and observes those events, converts them into assistant content and tool-call events, and returns finalized replayable output to the agent runtime.

flowchart LR
  A[OpenAI Azure and ChatGPT streams] --> B[Responses transport callers]
  B --> C[Stream observer and validation]
  C --> D[Canonical Responses processor]
  D --> E[Indexed text reasoning and tool slots]
  E --> F[Terminal usage and failure handling]
  F --> G[Assistant events and replayable result]
  G --> H[Agent runtime]
Loading

Decision needed

Question Recommendation
Is the OpenAI live-stream proof plus the shared provider regression matrix sufficient to land the unified processor without separate Azure and ChatGPT/Codex live-provider runs? Accept the scoped proof set: Explicitly accept the OpenAI live run and shared Azure/ChatGPT caller matrix as sufficient because the canonical processor is common and the unavailable live lanes are documented.

Why: The patch intentionally changes common runtime behavior for three provider surfaces, while available real-provider proof directly covers OpenAI and the other two surfaces are covered through shared tests and caller-specific suites.

Before merge

  • Resolve merge risk (P1) - The canonical processor changes terminal validation and persisted reasoning/tool output for several provider adapters; a regression could affect existing Responses conversations, replay state, or failure handling even though the intended behavior is fail-closed.
  • Resolve merge risk (P1) - The branch is behind current main; the supplied successful exact-head CI run predates the final head and does not by itself prove the three-way merge result.
  • Resolve merge risk (P1) - Live proof directly exercises OpenAI only. Azure is explicitly optional and no dedicated ChatGPT live-test lane exists, so a maintainer should explicitly accept that the shared regression matrix and OpenAI live run are sufficient for those adapter paths.
  • Complete next step (P2) - No mechanical repair is identified; the remaining action is protected maintainer review of the current-base validation and provider-proof scope.
Agent review details

Security

None.

PR surface

Source -387, Tests -63, Other -1. Total -451 across 14 files.

View PR surface stats
Area Files Added Removed Net
Source 9 1056 1443 -387
Tests 4 151 214 -63
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 14 1207 1658 -451

Review metrics

None.

Stored data model

Persistent data-model change detected: serialized state: packages/ai/src/transports/openai-responses-debug.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: canonical
Canonical: #114263
Summary: This PR is the canonical runtime implementation for the Responses-stream divergence matrix introduced by the already-merged fixture baseline.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Refresh proof on the current merge result (recommended)
    Rebase or validate the merge result against current main, then rerun the focused stream matrix and the available live OpenAI provider test before landing.
  2. Accept scoped provider coverage
    A maintainer may accept the current OpenAI live proof and adapter-specific regression suites as sufficient while Azure remains optional and no ChatGPT live lane exists.
  3. Pause for provider-lane expansion
    Pause this PR if maintainers require real Azure and ChatGPT/Codex stream evidence before consolidating their shared processor.

Technical review

Best possible solution:

Rebase or otherwise validate the clean merge result against current main, retain the single private canonical processor, and record the maintainer’s acceptance of the OpenAI live proof plus shared Azure/ChatGPT regression coverage before landing.

Do we have a high-confidence way to reproduce the issue?

Yes, at source level: the branch supplies focused fixtures for interleaving, missing terminal events, encrypted reasoning recovery, and tool scratch cleanup, and the contributor reports a real OpenAI Responses live run. I did not independently execute that provider path in this read-only review.

Is this the best way to solve the issue?

Yes, with a final current-base validation: centralizing the two private processors avoids preserving divergent state machines while keeping transport-specific timing, service-tier, and alias adaptation at their callers.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against b699a93c8710.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The contributor posted redacted after-fix live OpenAI Responses evidence from a hydrated Linux/Node 24 Testbox: 4/4 tests passed through the shared canonical processor, including a real structured tool call and terminal result; Azure is optional and no ChatGPT live lane is available.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The contributor posted redacted after-fix live OpenAI Responses evidence from a hydrated Linux/Node 24 Testbox: 4/4 tests passed through the shared canonical processor, including a real structured tool call and terminal result; Azure is optional and no ChatGPT live lane is available.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: The PR repairs bounded but user-visible provider-stream correctness across OpenAI-compatible Responses callers.
  • merge-risk: 🚨 compatibility: Replacing two private processors with one stricter terminal and slot-routing path can change error and completion behavior for existing provider setups.
  • merge-risk: 🚨 session-state: The patch changes reasoning replay metadata, completed message recovery, and finalized tool-call state that may be persisted or replayed by agent sessions.
  • merge-risk: 🚨 availability: The new common fail-closed validation path can make malformed or unterminated provider streams terminate with errors across several adapters.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The contributor posted redacted after-fix live OpenAI Responses evidence from a hydrated Linux/Node 24 Testbox: 4/4 tests passed through the shared canonical processor, including a real structured tool call and terminal result; Azure is optional and no ChatGPT live lane is available.
  • proof: sufficient: Contributor real behavior proof is sufficient. The contributor posted redacted after-fix live OpenAI Responses evidence from a hydrated Linux/Node 24 Testbox: 4/4 tests passed through the shared canonical processor, including a real structured tool call and terminal result; Azure is optional and no ChatGPT live lane is available.

Evidence

What I checked:

  • Merged baseline fixture: The related parity-fixture pull request established the shared private event contract and regression matrix before this implementation; it merged as commit 7846a32. (packages/ai/src/transports/openai-responses-stream-parity.test.ts, 7846a327576d)
  • Canonical processor integration: The proposed head moves processResponsesStream into the private transport stream module and changes OpenAI/ChatGPT callers to use that shared implementation, while retaining provider-specific request and service-tier adapters. (packages/ai/src/transports/openai-responses-stream-internal.ts, b8386fca7ca2)
  • Caller coverage: The branch updates the OpenAI Responses client and ChatGPT Responses SSE/WebSocket paths, and the supplied focused test list covers OpenAI, Azure, ChatGPT, retry, terminal-usage, agent streaming, incomplete-output, and replay/tool paths. (packages/ai/src/transports/openai-responses-client.ts, b8386fca7ca2)
  • Real provider behavior proof: The contributor’s July 27, 2026 comment reports a hydrated Linux/Node 24 Testbox live OpenAI Responses run with 4/4 tests passing, including terminal usage, low output-token handling, interleaved reasoning/tool state, context-overflow classification, and traversal through the shared canonical processor. (packages/ai/src/providers/openai-responses.live.test.ts, b8386fca7ca2)
  • Current merge state: GitHub reports the head as mergeable but behind its base; two current check runs remain in progress, so the final merge result still needs a current-base refresh rather than assuming the older exact-head run proves the merge result. (b8386fca7ca2)

Likely related people:

  • steipete: Authored the merged parity-fixture prerequisite and all four commits in the active canonical Responses stream implementation, providing the clearest available history trail for this private transport behavior. (role: feature owner and recent area contributor; confidence: high; commits: 7846a327576d, cfaee00f51ad, 255d930593fd; files: packages/ai/src/transports/openai-responses-stream-internal.ts, packages/ai/src/transports/openai-responses-client.ts, packages/ai/src/transports/openai-responses-stream-parity.test.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Rebase or validate the merge result against current main and let its required checks complete.
  • Record whether the existing OpenAI live proof and shared Azure/ChatGPT regression coverage are accepted for landing.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (3 earlier review cycles)
  • reviewed 2026-07-27T03:38:28.847Z sha d5b3e5de74f7ed1f31e49fd8d852700dc7aecf64 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-27T03:53:01.356Z sha dab46ef14d12e3e6b5976c0c0d3b9813badf50e9 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-27T04:04:14.747Z sha c93725c5ab8b81869aa353a11927e7462e8ab8bf :: needs real behavior proof before merge. :: none

@steipete
steipete force-pushed the codex/responses-stream-canonical branch 2 times, most recently from dab46ef to c93725c Compare July 27, 2026 03:59
@steipete steipete self-assigned this Jul 27, 2026
@steipete
steipete force-pushed the codex/responses-stream-canonical branch from c93725c to b8386fc Compare July 27, 2026 04:15
@steipete

Copy link
Copy Markdown
Contributor Author

Live provider-stream gate passed on the rebased exact head b8386fca7ca29047030de55a95eff84177dce092.

In response to the ClawSweeper gate comment: #114263 (comment)

  • Environment: Blacksmith Testbox tbx_01kygwm51shjqgqcb35q7428h0 (swift-prawn-d6b2), Linux/Node 24, repository-hydrated provider profile; Actions run https://github.com/openclaw/openclaw/actions/runs/30236642815
  • Command: OPENCLAW_LIVE_TEST=1 OPENCLAW_LIVE_TEST_QUIET=0 CI=1 pnpm test:live -- packages/ai/src/providers/openai-responses.live.test.ts --reporter=verbose
  • Result: 1 live suite passed, 4/4 tests passed in 3.26s
  • Real-stream coverage: terminal completion with usage accounting; sub-floor output-token handling; interleaved reasoning plus finalized tool-call state; current provider context-overflow classification
  • Canonical-path proof: the real OpenAI streamed Responses turn entered streamOpenAIResponses and completed through the shared canonical Responses processor, including the live tool call with the expected structured argument and a valid terminal result.

No dedicated openai-chatgpt-responses live test file exists in the current live-test lane, so no separate ChatGPT suite was available. Azure was left optional as requested. Credentials came from the existing Testbox hydration mechanism and were neither printed nor copied.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 27, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

Maintainer decision for the latest ClawSweeper review: accept the scoped provider proof set for landing.

  • The real OpenAI Responses stream is the canonical shared-processor proof: 4/4 live tests passed, including terminal usage and an interleaved reasoning + structured tool-call turn.
  • Azure remains optional for this landing, as requested.
  • No dedicated openai-chatgpt-responses live test file exists; the ChatGPT/Codex caller remains covered by its caller-specific regression suites and the common processor parity matrix.
  • Fresh exact-head CI is green on b8386fca7ca29047030de55a95eff84177dce092 (openclaw/ci-gate succeeded), and OPENCLAW_TESTBOX=1 scripts/pr prepare-run 114263 passed against current main at 2026-07-27 04:26 UTC, verifying the remote PR tree and hosted/current-base gates.

This addresses both Rank-up moves in #114263 (comment). No ClawSweeper code finding remains.

@steipete
steipete merged commit fdfe512 into main Jul 27, 2026
142 of 150 checks passed
@steipete
steipete deleted the codex/responses-stream-canonical branch July 27, 2026 04:28
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 27, 2026
* refactor(ai): unify Responses stream processing

* fix(ai): preserve unindexed output boundaries

* refactor(ai): remove obsolete Responses helpers

* refactor(ai): trim canonical stream surface
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant