Repository navigation
fix(ai): carry the Responses system prompt via instructions, not input[0] - #130206
Conversation
…t[0] Every non-Codex OpenAI Responses request embedded the system prompt as input[0]. HTTP continuation compares input byte-for-byte against the cached previous request to decide whether it can reuse previous_response_id, and the embedded runner rebuilds the system prompt fresh every attempt from live runtime state (active background processes, watched sessions, active-memory context) -- so ordinary state churn between two turns permanently defeated continuation. Native Codex/ChatGPT already avoided this by sending the system prompt via the separate instructions field; broaden that to every Responses request (instructions was previously Codex-only) and exclude instructions from the continuation comparator, matching how input is already excluded there. xAI's /responses/compact endpoint has no instructions field (system prompt must be the first input message, confirmed against docs.x.ai/developers/advanced-api-usage/context-compaction) and was about to silently lose the system prompt on every compaction request once it stopped riding along in input. Re-embed it just for that request body via a new buildOpenAIResponsesCompactSystemMessage helper, with its own regression coverage for the developer/system role selection since that invariant no longer has any other test path.
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs changes before merge. Reviewed August 27, 2026, 12:02 PM ET / 16:02 UTC. ClawSweeper reviewWhat this changesThe branch moves eligible OpenAI Responses system prompts to top-level instructions, preserves input-embedded prompts for other routes through a compatibility setting, and re-embeds the prompt for xAI compaction. Regression provenancePossible regression — suspected (reviewed change). No predecessor PR is attributed. Merge readinessKeep open: this is a distinct current-main bug fix with credible live and boundary proof. One P3 correction remains in the new live-test explanation, and the exact head still needs its failed/incomplete CI state resolved before merge. Priority: P1 Review scores
Verification
Live VerificationCommand: Result: PASS (completed) Assertions:
How this fits togetherThe Responses transport turns agent context into provider requests and may reuse a prior response to avoid replaying history. This change controls where the system prompt is serialized, which affects continuation eligibility and xAI compaction input. flowchart LR
A[Agent runtime context] --> B[Responses request builder]
B --> C{Verified instructions route?}
C -->|Yes| D[Top-level instructions]
C -->|No| E[System prompt in request input]
D --> F[Continuation or provider request]
E --> F
F --> G[xAI compaction when requested]
Before merge
Findings
Agent review detailsSecurityNone. PR surfaceSource +107, Tests +580, Docs +1. Total +688 across 22 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Copy recommended automerge instructionTechnical reviewBest possible solution: Keep one request-builder policy for prompt placement, correct the stale live-test explanation, and land only once exact-head validation confirms the documented compatibility behavior. Do we have a high-confidence way to reproduce the issue? Yes, source reproduction is high confidence: fetched main embeds the prompt in input and compares it as continuation history, while the added resolver and live native-API tests define the failing and repaired paths. Is this the best way to solve the issue? Yes, after the route narrowing the policy is the right owner boundary: it keeps unverified routes on their existing input format and leaves current instructions on each continued native request. Full review comments:
Overall correctness: patch is correct AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 8e4075371039. LabelsLabel justifications:
EvidenceAcceptance criteria:
What I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (10 earlier review cycles; latest 8 shown)
|
Yigtwxx
left a comment
There was a problem hiding this comment.
Measured this against c02ac37d1224 (the base ClawSweeper reviewed) at head 2f27a12e5ab. Two things: the continuation proof the bot asked for, which I could produce deterministically, and one finding about the field's reach.
The proof ClawSweeper asked for
The bot's blocker is that the body shows the request shape but never the recovered continuation. That outcome is reachable without a live provider, because resolveResponsesContinuationRequest is a pure function over the exact bodies buildOpenAIResponsesParams emits.
Two turns on a proxy-like route (api: "openai-responses", configured non-native baseUrl), with only the runtime-state half of the system prompt churning between them and the conversation a clean append:
| arm | turn-1 input roles |
turn-2 input roles |
continuationStatus |
|---|---|---|---|
main c02ac37d1224 |
developer, user |
developer, user, assistant, user |
history_changed |
this branch 2f27a12e5ab |
user |
user, assistant, user |
continued |
Same model, same context objects, same probe — only the two checked-out revisions of packages/ai/src/transports/ differ. That is the claim in the PR title, reproduced end to end: the system-prompt churn is what defeated continuation on main, and moving it to instructions recovers it.
Finding: instructions reaches every route with no capability gate
buildOpenAIResponsesParams calls applyOpenAIResponsesPayloadPolicy at the end (line 369), and that policy exists specifically because non-native Responses routes do not accept everything the native one does. On a configured non-native baseUrl it currently gates or strips five things: store, prompt_cache_key + prompt_cache_retention, disabled-reasoning payload, service_tier, and input-item status — the last one carrying the comment "Strict OpenAI-compatible Responses endpoints reject output-only fields such as status on replayed input items. Strip them for non-native routes."
instructions now joins that payload for every Responses route and is the only one of those fields with no gate. Same probe, same proxy-like model:
| arm | instructions carries system prompt |
system prompt present in input |
|---|---|---|
main c02ac37d1224 |
no | yes (input[0].role = "developer") |
this branch 2f27a12e5ab |
yes | no |
So on a route that accepts the request but ignores instructions, the system prompt stops arriving and the call still returns 200. Nothing in the transport notices — this is a silent quality regression, not an error, which is what makes it worth a gate rather than a note.
The reason I do not think this is hypothetical is in this PR itself: xAI's /responses/compact is exactly such an endpoint, and you found it and hand-wrote buildOpenAIResponsesCompactSystemMessage for it. That is one confirmed counter-example to "every Responses endpoint honors instructions", handled by a special case. A second counter-example — some proxy in the custom endpoint class — would not get a special case; it would just quietly lose its system prompt.
The narrow shape that keeps your win intact: reuse the pattern already in the same module, a compat.supportsInstructions boolean read through readCompatPayloadBoolean and defaulting to on, falling back to the input embedding when an operator sets it false. That leaves the default path — including the OmniRoute routes this PR targets — exactly as you have it, and gives a broken proxy an opt-out instead of an unexplained personality change. supportsStore and supportsPromptCacheKey are already carried that way.
One hypothesis I tested and dropped
I expected the system-prompt-only turn to double up, since ensureOpenAIResponsesNonEmptyInput now runs for every model rather than Codex only. It does not: the placeholder it pushes is a single space, so that turn sends instructions plus [{role: "user", text: " "}] and the prompt text appears once. No finding there — recording it so the negative is on the record.
Environment
Probes ran on Windows under node --import tsx, calling buildOpenAIResponsesParams and resolveResponsesContinuationRequest directly; no mocks and no network. This machine is on Node 22.20, whose embedded SQLite trips OpenClaw's WAL-reset guard during module import, so a local shim fakes only the sqlite_version() string — every other runtime behaviour is the real implementation. No provider credentials were involved.
…Instructions A proxy-compatible Responses endpoint that silently ignores `instructions` (confirmed for at least xAI's compact endpoint, plausible for other custom/proxy routes with no established contract) would drop the system prompt with no error -- the request still returns 200. Add a compat.supportsInstructions escape hatch, defaulting to on, mirroring the existing supportsStore/supportsPromptCacheKey pattern: when an operator sets it false, the system prompt goes back to being embedded in `input[0]` (the pre-instructions behavior) instead of `instructions`. Addresses the maintainer review finding on openclaw#130206.
|
Thanks for this — the The Also produced my own live proof for the "does continuation actually recover" question in the meantime: ran two isolated @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
Yigtwxx
left a comment
There was a problem hiding this comment.
Thanks — I measured c0d6d3737f4 and the gate behaves exactly as described. Same deterministic harness as before (buildOpenAIResponsesParams called directly, proxy-style model, sentinel system prompt), with the default and an unrelated compat key as control arms:
compat on the model |
instructions sent |
input roles |
system prompt inside input |
|---|---|---|---|
| absent (default) | yes | ["user"] |
no |
supportsInstructions: true |
yes | ["user"] |
no |
supportsInstructions: false |
no | ["developer","user"] |
yes |
supportsStore: false (control) |
yes | ["user"] |
no |
So the opt-out reproduces the pre-instructions shape precisely, and no other compat key leaks into the decision.
On the live previous_response_id recovery you could not catch
I think that is gated before your change ever runs, and it is worth confirming so you do not keep chasing it against this PR. HTTP continuation is only ever claimed under openai-responses-client.ts:369-397:
const httpContinuationEligible =
config.httpContinuation &&
!websocketMode &&
!getAiTransportHost().requiresManagedTransport(model) &&
supportsNativeOpenAIResponsesEndpoint({ provider: model.provider, api: model.api, baseUrl: model.baseUrl });
if (httpContinuationEligible && sessionId && params.store === true && !params.previous_response_id) {supportsNativeOpenAIResponsesEndpoint (openai-responses-websocket.ts:74-84) requires all three: provider === "openai", api === "openai-responses", and a base URL whose origin is exactly https://api.openai.com with path /v1, no credentials, no query, no fragment. Measured:
| route | continuation eligible |
|---|---|
openai + https://api.openai.com/v1 |
true |
openai + https://api.openai.com/v1/ |
true |
openai + https://api.openai.com/v1?beta=1 |
false |
openai + https://my-gw.openai.azure.com/v1 |
false |
openai + proxy base URL |
false |
non-openai provider + proxy base URL |
false |
If your OmniRoute connection points anywhere other than the official base URL — which is the point of a router — claimOpenAIResponsesHttpContinuation is never called, so no request on that route can carry previous_response_id regardless of what input looks like. The second gate, params.store === true, would independently disqualify any route that runs with store stripped.
That makes the missing live recovery orthogonal to this PR rather than evidence against it: your change fixes what continuation compares (input no longer carries a per-turn-rebuilt system prompt), while route eligibility decides whether the comparison is ever reached. On a native api.openai.com connection your fix is what makes the comparison succeed; on a proxied route it was never going to run either way.
Nothing here asks for a change to the patch — this is the answer to the open question, so the missing trace does not read as an unproven claim during review.
…acts usesInstructionsField already read compat.supportsInstructions at request-build time, but strict config and catalog normalization dropped the key, so no configured model could actually set it. A proxy that silently ignores top-level instructions had no supported way to opt out. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6
|
Pushed Also fixed the pre-existing On the second rank-up move ("add a redacted provider trace showing an eligible continuation request carrying @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
…proxy routes usesInstructionsField defaulted true for any api:"openai-responses" model regardless of endpoint, including arbitrary custom/local proxies OpenClaw has no bundled knowledge of. HTTP continuation only ever engages on the exact native api.openai.com route, so an unverified proxy got nothing in return for the risk of silently losing its system prompt if it doesn't honor `instructions`. Default now follows the same known-endpoint classification the file already uses for reasoning/input-status payload shaping; xAI's already-verified main route is unaffected since it's a named endpoint class, not "custom"/"local". Also updates the one stale test this flips (xAI compact-endpoint replay no longer embeds the system prompt in input[0], matching what the original PR's instructions-field change already does for that route) and documents supportsInstructions in the custom-provider compat table. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6
|
Pushed Fix: default now follows the same known-endpoint classification ( Also fixed the two things this exposed:
Two new regression tests: an unverified custom-proxy route with no explicit compat now defaults to embedding the prompt in
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
The comparator already strips instructions before comparing requests (requestWithoutInput), matching how it already strips input -- but no fixture actually varied instructions between turns, so nothing proved continuation still engages when the rebuilt-per-turn instructions text legitimately differs, or that the current turn's instructions (not a stale copy) reaches the outgoing request. Also fixes a stale doc: the custom-provider compat table said supportsInstructions defaults true for "bundled/catalog-known routes", which was accurate for an earlier iteration of this branch but not the current, narrower default (native OpenAI and xAI's main route only). Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6
|
Pushed Cover changed instructions in the continuation regression — Correct the documented supportsInstructions default — my own docs edit from the previous fix was already stale by the time it landed (written for the intermediate, broader default before the OpenCode/GitHub-Copilot fix narrowed it). Now states the real default set precisely: native OpenAI and xAI's main route only.
Still explicitly skipping the native @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
…ation Committed, rerunnable proof of the actual open question -- does a real native OpenAI Responses request carry the system prompt via top-level instructions, and does HTTP continuation still correctly reuse previous_response_id once the prompt moved out of input. Follows the established openai-responses-client.continuation.live.test.ts pattern (gated on OPENCLAW_LIVE_TEST=1 + OPENAI_API_KEY, skipped otherwise). Captures the literal request bytes via a globalThis.fetch wrapper rather than a forward-proxy: proxying would require overriding the model's baseUrl to a loopback address, which would itself defeat the native-route classification under test (the continuation eligibility check in openai-responses-websocket.ts requires an exact https://api.openai.com/v1 origin/path match and treats any other baseUrl, including a proxy's loopback address, as non-native). Uses the same secret-recall semantic proof as the reference continuation live test: turn 2 can only produce the secret given in turn 1 if the real API actually resolved server-side state through previous_response_id, since the trimmed turn-2 request never repeats it -- structural proof (previous_response_id present) alone can't rule out a silent full-history fallback producing the same visible answer. Verified: run against the real API twice (once before, once after an unrelated lint fix) -- both passed, confirming turn 1 carries instructions with no previous_response_id, turn 2 carries previous_response_id plus the correctly-recalled secret with a single-message trimmed input. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6
|
Added real, current-head, live proof against @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
…fault usesVerifiedInstructionsEndpoint reused usesKnownNativeOpenAIRoute, which also covers azure-openai -- a boolean this file already uses elsewhere for reasoning/service-tier/input-status policy, where treating Azure as "native-like" is fine. Reusing it for the instructions default silently contradicted the PR's own stated evidence boundary (native OpenAI and xAI's main route only): Azure was never actually verified to honor `instructions`, unlike those two. Introduces a narrower usesVerifiedNativeOpenAIRoute specific to this decision, explicitly excluding azure-openai. Two pre-existing tests that happened to use an Azure model fixture to test unrelated message-item serialization structure now opt in explicitly via compat.supportsInstructions -- their actual intent (structure once instructions is in play) is unchanged. Left the shared createAzureResponsesModel() helper itself untouched since ~30 other call sites across sibling test files use it for unrelated behavior. New regression test proves Azure specifically defaults to input-embedded, unlike native OpenAI. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6
|
Pushed Introduced a narrower
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
Yigtwxx
left a comment
There was a problem hiding this comment.
CI at head 9bbac5ee5b4 is red in three jobs. One is caused by this push; the other two do not reproduce against the diff.
The real one: checks-node-compact-small-34, core-unit-support shard
packages/ai/src/transports/openai-responses-prompt-observer.test.ts:326 > "observes Azure Responses egress":
AssertionError: expected { egress: 'responses-sdk', ... } to match object { ... }
- "promptSource": "instructions",
+ "promptSource": "input.developer",
The cause is inside this PR's own diff. That line was flipped back when supportsInstructions still defaulted on for every non-Codex Responses route:
it("observes Azure Responses egress", async () => {
...
- promptSource: "input.developer",
+ promptSource: "instructions",9bbac5ee5b4 then narrowed usesVerifiedInstructionsEndpoint to openai-public | openai | xai-native, so the azure-openai fixture correctly falls back to the input-embedded prompt again, while the assertion still encodes the pre-narrowing universal default. The runtime behavior after 9bbac5e is the intended one; only the expectation is stale, so reverting that single line to "input.developer" clears the shard.
Same family as the remaining P3, with a third instance
The open finding is the supportsInstructions comment at packages/llm-core/src/types.ts:535 ("Default: true"). The header comment this PR adds in the same test file, lines 283-288, makes the same overreach:
Every non-Codex Responses request now carries the system prompt via
instructions, not aninput.developer/input.systemmessage
True for the earlier design, not after 9bbac5e - and the Azure case forty lines below is the counter-example in the same file. Correcting these two alongside the type comment leaves the exported contract, the type doc, and the test's own documentation stating one selective default instead of three different ones.
The other two reds
checks-node-compact-small-11:src/gateway/server.chat.gateway-server-chat.test.ts:2741> "agent.wait ignores lifecycle completion while same-runId chat.send is active", failing on "Gateway did not publish settled run ownership after chat.send cleanup". A timing assertion in a file this PR does not touch and that no Responses transport path reaches.build-artifacts/startup-memory:plugins list --jsonmedian 407.7 MB against an effective ceiling of 401 MB, samples 407.7 / 422.5 / 399.1 MB. The sample spread straddles the ceiling on its own, and the diff adds no import to the plugins command path.
Neither of those failed at fb2a26394e3 or 3ec479d0fe3, both of which were fully green - which is also where the Azure assertion still passed. The unit-support red is confined to the last push.
The Azure narrowing in 9bbac5e (usesVerifiedInstructionsEndpoint -> openai-public | openai | xai-native) correctly moved Azure back to embedding the prompt in input, but left one test assertion and two comments describing the pre-narrowing universal default. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6
|
Fixed in
Reran the full file (17/17 pass) plus the payload-policy, continuation, and transport-stream suites it touches (149 tests total) — no other fallout. Also checked the two other red jobs from the earlier run: @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Merged via squash.
|
…t[0] (openclaw#130206) * fix(ai): carry the Responses system prompt via instructions, not input[0] Every non-Codex OpenAI Responses request embedded the system prompt as input[0]. HTTP continuation compares input byte-for-byte against the cached previous request to decide whether it can reuse previous_response_id, and the embedded runner rebuilds the system prompt fresh every attempt from live runtime state (active background processes, watched sessions, active-memory context) -- so ordinary state churn between two turns permanently defeated continuation. Native Codex/ChatGPT already avoided this by sending the system prompt via the separate instructions field; broaden that to every Responses request (instructions was previously Codex-only) and exclude instructions from the continuation comparator, matching how input is already excluded there. xAI's /responses/compact endpoint has no instructions field (system prompt must be the first input message, confirmed against docs.x.ai/developers/advanced-api-usage/context-compaction) and was about to silently lose the system prompt on every compaction request once it stopped riding along in input. Re-embed it just for that request body via a new buildOpenAIResponsesCompactSystemMessage helper, with its own regression coverage for the developer/system role selection since that invariant no longer has any other test path. * fix(ai): gate the Responses instructions field behind compat.supportsInstructions A proxy-compatible Responses endpoint that silently ignores `instructions` (confirmed for at least xAI's compact endpoint, plausible for other custom/proxy routes with no established contract) would drop the system prompt with no error -- the request still returns 200. Add a compat.supportsInstructions escape hatch, defaulting to on, mirroring the existing supportsStore/supportsPromptCacheKey pattern: when an operator sets it false, the system prompt goes back to being embedded in `input[0]` (the pre-instructions behavior) instead of `instructions`. Addresses the maintainer review finding on openclaw#130206. * fix(ai): expose supportsInstructions through config and catalog contracts usesInstructionsField already read compat.supportsInstructions at request-build time, but strict config and catalog normalization dropped the key, so no configured model could actually set it. A proxy that silently ignores top-level instructions had no supported way to opt out. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6 * fix(ai): default the Responses instructions field off for unverified proxy routes usesInstructionsField defaulted true for any api:"openai-responses" model regardless of endpoint, including arbitrary custom/local proxies OpenClaw has no bundled knowledge of. HTTP continuation only ever engages on the exact native api.openai.com route, so an unverified proxy got nothing in return for the risk of silently losing its system prompt if it doesn't honor `instructions`. Default now follows the same known-endpoint classification the file already uses for reasoning/input-status payload shaping; xAI's already-verified main route is unaffected since it's a named endpoint class, not "custom"/"local". Also updates the one stale test this flips (xAI compact-endpoint replay no longer embeds the system prompt in input[0], matching what the original PR's instructions-field change already does for that route) and documents supportsInstructions in the custom-provider compat table. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6 * fix(ai): narrow the instructions-field default to only confirmed-verified routes usesVerifiedInstructionsEndpoint (formerly usesUnverifiedProxyEndpoint's inverse) treated every named endpointClass except custom/local as verified -- but recognizing a hostname (for SSRF/base-URL matching) is not the same as having confirmed that host's Responses API honors `instructions`. Bundled classes like OpenCode and GitHub Copilot have no such confirmation, so their existing users could silently lose their system prompt on upgrade. Narrowed the default-on set to exactly the two routes actually verified: native OpenAI (definitionally) and xAI's main route (confirmed by direct testing, per the existing compact-endpoint carve-out). Every other route, named or not, now defaults to the pre-existing input-embedded behavior unless compat.supportsInstructions opts it in explicitly. Also lands a permanent committed integration test (openai-responses-payload-policy.instructions.integration.test.ts) over a real loopback HTTP+SSE server -- no SDK mocking -- asserting the literal wire request for both the unverified-default-off and explicit-opt-in cases, following the same pattern as openai-responses-client.continuation.integration.test.ts. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6 * test(ai): cover continuation across a changed instructions value The comparator already strips instructions before comparing requests (requestWithoutInput), matching how it already strips input -- but no fixture actually varied instructions between turns, so nothing proved continuation still engages when the rebuilt-per-turn instructions text legitimately differs, or that the current turn's instructions (not a stale copy) reaches the outgoing request. Also fixes a stale doc: the custom-provider compat table said supportsInstructions defaults true for "bundled/catalog-known routes", which was accurate for an earlier iteration of this branch but not the current, narrower default (native OpenAI and xAI's main route only). Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6 * test(ai): add gated live proof for the instructions default + continuation Committed, rerunnable proof of the actual open question -- does a real native OpenAI Responses request carry the system prompt via top-level instructions, and does HTTP continuation still correctly reuse previous_response_id once the prompt moved out of input. Follows the established openai-responses-client.continuation.live.test.ts pattern (gated on OPENCLAW_LIVE_TEST=1 + OPENAI_API_KEY, skipped otherwise). Captures the literal request bytes via a globalThis.fetch wrapper rather than a forward-proxy: proxying would require overriding the model's baseUrl to a loopback address, which would itself defeat the native-route classification under test (the continuation eligibility check in openai-responses-websocket.ts requires an exact https://api.openai.com/v1 origin/path match and treats any other baseUrl, including a proxy's loopback address, as non-native). Uses the same secret-recall semantic proof as the reference continuation live test: turn 2 can only produce the secret given in turn 1 if the real API actually resolved server-side state through previous_response_id, since the trimmed turn-2 request never repeats it -- structural proof (previous_response_id present) alone can't rule out a silent full-history fallback producing the same visible answer. Verified: run against the real API twice (once before, once after an unrelated lint fix) -- both passed, confirming turn 1 carries instructions with no previous_response_id, turn 2 carries previous_response_id plus the correctly-recalled secret with a single-message trimmed input. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6 * fix(ai): exclude Azure OpenAI from the verified instructions-field default usesVerifiedInstructionsEndpoint reused usesKnownNativeOpenAIRoute, which also covers azure-openai -- a boolean this file already uses elsewhere for reasoning/service-tier/input-status policy, where treating Azure as "native-like" is fine. Reusing it for the instructions default silently contradicted the PR's own stated evidence boundary (native OpenAI and xAI's main route only): Azure was never actually verified to honor `instructions`, unlike those two. Introduces a narrower usesVerifiedNativeOpenAIRoute specific to this decision, explicitly excluding azure-openai. Two pre-existing tests that happened to use an Azure model fixture to test unrelated message-item serialization structure now opt in explicitly via compat.supportsInstructions -- their actual intent (structure once instructions is in play) is unchanged. Left the shared createAzureResponsesModel() helper itself untouched since ~30 other call sites across sibling test files use it for unrelated behavior. New regression test proves Azure specifically defaults to input-embedded, unlike native OpenAI. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6 * fix(ai): correct stale instructions-field defaults in Azure test and doc The Azure narrowing in 9bbac5e (usesVerifiedInstructionsEndpoint -> openai-public | openai | xai-native) correctly moved Azure back to embedding the prompt in input, but left one test assertion and two comments describing the pre-narrowing universal default. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6 * test(ai): correct native base URL explanation --------- Co-authored-by: Claude Sonnet 5 <[email protected]> Co-authored-by: Patrick Erichsen <[email protected]>
What Problem This Solves
HTTP continuation (
previous_response_idreuse) for the OpenAI Responses transport was permanently defeated for any non-Codex connection (native OpenAI direct-API-key, xAI, and OmniRoute-style custom Responses endpoints) whenever the system prompt changed between two turns — which happens routinely, since the embedded runner rebuilds the system prompt fresh on every attempt from live runtime state (active background processes, watched sessions, active-memory context, current date).Why This Change Was Made
convertOpenAIResponsesMessagesForRequestembedded the system prompt asinput[0]for every non-Codex Responses request.resolveResponsesContinuationRequest(packages/ai/src/transports/openai-responses-continuation.ts) compares the cached previous request'sinputbyte-for-byte against the current one to decide whether it can reuseprevious_response_id; any drift in that first item — including ordinary runtime-state churn that has nothing to do with the actual conversation — forced ahistory_changedverdict and threw away continuation.Native Codex/ChatGPT already avoided this by sending the system prompt via the separate
instructionsfield, which sits outside the comparedinputarray (confirmed viaisOpenAICodexResponsesModel/resolveOpenAICodexResponsesInstructions).isOpenAICodexResponsesModelis narrowly scoped to the ChatGPT/Codex-OAuth API variant only, so every other Responses route (native OpenAI with an API key, xAI, custom/proxy endpoints) never got this protection.Fix: broaden
instructionsto every Responses-API request (previously Codex-only), and excludeinstructionsfromrequestWithoutInput's comparison, matching howinputis already excluded there.instructionsis still sent on the wire every request regardless of continuation status, so no freshness is lost — only the false-positive continuation rejection is removed.While rolling this out I found and fixed a second, related bug: xAI's server-side
/responses/compactendpoint (used for xAI/opted-in compaction, seedocs/providers/xai.md) has noinstructionsfield — confirmed live againsthttps://docs.x.ai/developers/advanced-api-usage/context-compaction, which documents the system prompt as required to be the firstinputmessage.postOpenAIResponsesCompactionposts only{ model, input }built from the samebuildOpenAIResponsesParamsresult the streaming path uses, so once the system prompt moved out ofinputit would have silently vanished from every compaction request. Fixed by re-embedding it just for that request body via a newbuildOpenAIResponsesCompactSystemMessagehelper, which reproduces the same developer/system role selection the old inline embedding used.User Impact
instructionswas already a valid, already-observed (promptSource: "instructions") prompt-egress state; it's just no longer Codex-exclusive.input, since that's xAI's endpoint contract) — this PR prevents what would otherwise have been a silent compaction-quality regression.Evidence
/responses/compactcontract (noinstructionsfield, system prompt must beinput[0]):https://docs.x.ai/developers/advanced-api-usage/context-compaction.packages/ai/full suite: 108 files / 1910 tests passing.src/agents/surfaces (openai-transport-stream.*,openai-responses*,openai-thinking-contract,embedded-agent-helpers/openai,prompt-cache-observability,provider-prompt-state,stream-resolution): all passing.src/agents/embedded-agent-runner/run/(the runner's own consumer of these request-building helpers): 98 files / 1180 tests passing.packages/ai/src/transports/openai-responses-params-internal.test.tscoveringbuildOpenAIResponsesCompactSystemMessage's developer/system role selection, since that invariant lost its only other test path once the main streaming builder stopped embedding the role-bearing message ininput.pnpm tsgo -p tsconfig.core.jsonclean.This is a companion fix to #130166 (the heartbeat/cron inbound-metadata continuation fix, already merged) — that fix addressed one mechanism defeating continuation on OmniRoute; this addresses a second, broader one affecting the system-prompt path across all non-Codex Responses connections. Marking as draft pending live deployment/verification against a real OmniRoute-backed session, following the same pattern used for #130166.
Live Deployment Verification
Deployed to Ping's real OmniRoute-backed gateway (daemonbitch,
ping-deploy-v2branch, stacked on top of the already-merged #130166 heartbeat/cron fix). Restarted the gateway and inspected OmniRoute's own request-artifact log directly for the first live requests built by the new binary:POST /v1/responsesat2026-08-26T16:13:12.083Z(sessionagent:main:main, 225 prior input items):requestBody.instructionsis present (29,365 chars) and contains the actual system prompt verbatim (Tooling/Runtime/model-identity blocks) — confirmed by reading the full text, not the unrelated<context_handoff>string a different in-flight feature also happens to put ininstructions.requestBody.input[0].roleis"user", not"system"— the system prompt is no longer embedded ininput.16:43:00.169Z) and on two further requests in the same session 12s apart (16:43:27.980Z/16:43:40.053Z).previous_response_idpresent on the wire) genuinely engaging 4 times prior to this deploy — all attributable to fix(ai): stabilize runtime context across Responses tool rounds #130166 (the heartbeat/cron metadata-stripping fix), confirming the underlying continuation pipeline (idle TTL, connection-identity matching) is healthy in this environment when its one remaining precondition (byte-stableinput) holds.previous_response_id-carrying request in the ~40-minute post-deploy observation window. Continuation only engages for same-session follow-ups issued within the ~90-minute idle TTL that are not immediately preceded by a context-compaction turn; both requests I observed in the same session were compaction-boundary turns (the request body opens withThe conversation history before this point was compacted into the following summary:), which correctly cannot reuse aprevious_response_idregardless of this fix — theinputarray is intentionally rebuilt from scratch after compaction. This is expected behavior, not a gap in the fix. I'm not blocking on catching a rarer non-compaction same-session follow-up live; the unit-level reproduction (packages/ai/src/transports/openai-responses-continuation.test.tsand the newopenai-responses-params-internal.test.ts) already proves the exact byte-comparison behavior deterministically.Marking ready for review — the fix is confirmed both by full test coverage and by direct inspection of the live request shape it produces.
Update: real native OpenAI continuation proof at current head (
7bed52a189d)Closed the "final-head native OpenAI trace after prompt drift" gap. Added
openai-responses-payload-policy.instructions.live.test.ts, gated onOPENCLAW_LIVE_TEST=1+OPENAI_API_KEY(matching the establishedopenai-responses-client.continuation.live.test.tspattern), run twice against the realapi.openai.com:provider: "openai",baseUrl: "https://api.openai.com/v1", nocompatoverride — the exact default-on route this PR targets): the real captured request carriesinstructions: "You are a terse test assistant."at top level, noinput[0]system/developer role, noprevious_response_id.previous_response_id(a real non-empty string returned by the API),instructionsstill present with the current text, and a single-message trimmedinput(no repeated history). The model correctly recalled a secret code that was given only in turn 1's now-omitted history — this is semantic proof, not just structural: a silent full-history fallback would produce the same visible answer with the same request shape claim but a different actualinput(full history, secret repeated) — the trimmed-input assertion together with the correct recall rules that out.Captured via a
globalThis.fetchwrapper rather than a forward-proxy, deliberately: a proxy would need to override the model'sbaseUrlto a loopback address, which would itself fail the exact-origin checksupportsNativeOpenAIResponsesEndpoint(continuation eligibility) uses — the same reason a plain custom endpoint never got continuation for free before this PR.Ran twice (once before, once after an unrelated lint fix); both passed.
check:changedandautoreviewboth clean.