Skip to content

fix: OpenCode Go/Zen requests are missing the required x-opencode-session header - #137464

Merged
VACInc merged 7 commits into
openclaw:mainfrom
Ghilteras:fix/opencode-session-affinity
Sep 6, 2026
Merged

VACInc merged 7 commits into
openclaw:mainfrom
Ghilteras:fix/opencode-session-affinity

Conversation

@Ghilteras

@Ghilteras Ghilteras commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Closes #137165. Related: #135588.

Summary

High Level TLDR

OpenCode requires a stable conversation header in addition to the User-Agent added by #135588. This PR sends x-opencode-session through all four bundled OpenCode model transports, including when prompt caching is disabled.

What Problem This Solves

Fixes an issue where OpenCode Go and Zen model requests omit the conversation identity required by the provider. The vendor notice warns that requests without it may fail starting September 6, 2026. The requirement is documented at https://opencode.ai/docs/go/.

Why This Change Was Made

One shared header resolver covers both standalone SDK adapters and the managed transports selected by normal Gateway turns: Anthropic, Gemini, OpenAI Chat Completions, and OpenAI Responses. Managed Google receives the header at its provider-plugin boundary; managed Responses shares the HTTP/WebSocket header builder. It uses the existing stream sessionId independently of optional cache-affinity headers, avoiding four separate compatibility policies. It applies only to HTTPS requests to opencode.ai, accepts the DNS trailing-dot spelling, preserves explicit model and stream headers case-insensitively, and leaves unrelated endpoints unchanged. The Google SDK header merge now uses the existing case-insensitive transport helper, preventing model and stream spellings of the same header from becoming a comma-joined value. Sessionless SDK calls do not invent a shared ID; direct callers must supply their conversation's sessionId.

Root Cause

#135588 implemented User-Agent identification only. The original patch in this PR added the session header to Chat Completions and Anthropic but left bundled Responses and Gemini routes uncovered. It also coupled the required identity to cache-session selection. The revised implementation supplies the required header before each SDK receives its request headers, keeping optional cache behavior unchanged. Follow-up review also identified the separate managed transport implementations; those now use the same policy, with regression coverage through the runtime transport selector and fetch egress.

User Impact

OpenCode conversations carry the required identity across all four API families and retain it with cacheRetention: "none". No configuration, dependency, storage, or protocol changes are needed. The original contributor's commits are preserved; the maintainer follow-up resolves the merge conflict and completes the missing transport coverage.

Verification

Evidence

Real behavior proof

Passed on September 6, 2026 against real OpenCode Go, using the reviewed source at 88f3d1bda27ec49f442ce22076c968ae1bf573ce in a separate process. The probe called createBoundaryAwareStreamFnForModel with opencode-go/minimax-m2.5, the normal Go Chat Completions endpoint, and the existing configured API-key credential loaded read-only. It supplied synthetic conversation IDs and no explicit x-opencode-session header. The fetch observer asserted the automatically generated header immediately before forwarding the original request to OpenCode; it did not add or replace headers or responses.

Procedure:

  1. Run the pre-patch managed transport with a synthetic key and a capture-only fetch: the outgoing request has no session header. No baseline request leaves the process.
  2. Run the patched managed transport against OpenCode with cacheRetention: "none" and synthetic conversation A. Require HTTP 200 and the exact text OPENCODE_SESSION_OK.
  3. Append the assistant response and a second synthetic user turn in conversation A, use cacheRetention: "short", and require the same conversation header and successful reply.
  4. Start conversation B with a distinct generated ID and cacheRetention: "none"; require its distinct header and the same successful reply.

Command shape (checkout paths redacted):

TSX_TSCONFIG_PATH=<PR-checkout>/tsconfig.json \
  node --import <installed-checkout>/node_modules/tsx/dist/loader.mjs \
  /tmp/opencode-session-live-proof.mts

Observed output, reduced to the synthetic test fields:

baseline-no-network: sessionHeaderPresent=false
request=1 conversation=A cacheRetention=none  headerMatchesConversation=true HTTP=200 expectedReply=true stopReason=stop totalMs=1959
request=2 conversation=A cacheRetention=short headerMatchesConversation=true HTTP=200 expectedReply=true stopReason=stop totalMs=2390
request=3 conversation=B cacheRetention=none  headerMatchesConversation=true HTTP=200 expectedReply=true stopReason=stop totalMs=1696
PASS stableWithinConversation=true distinctAcrossConversations=true disabledCachingProven=true liveRequests=3

Environment: Linux, Node 25.9.0, tsx 4.23.12, existing installed OpenAI SDK 7.5.0. CI separately tested the PR's locked dependencies. Only synthetic prompts were sent; credentials, actual generated conversation IDs, account data, and private endpoints are omitted from this evidence.

Deployed compiled transport follow-up

Repeated the same three live requests using the deployed packages/ai/dist/index.mjs and packages/ai/dist/transports.mjs, built from base 9d20f0b07accf2566251380ff2204e710653d363 plus this PR at 88f3d1bda27ec49f442ce22076c968ae1bf573ce. This run used the pinned OpenAI SDK 7.8.0. The observer again only asserted headers and forwarded the original requests.

request=1 conversation=A cacheRetention=none  headerMatchesConversation=true HTTP=200 expectedReply=true stopReason=stop totalMs=2665
request=2 conversation=A cacheRetention=short headerMatchesConversation=true HTTP=200 expectedReply=true stopReason=stop totalMs=2436
request=3 conversation=B cacheRetention=none  headerMatchesConversation=true HTTP=200 expectedReply=true stopReason=stop totalMs=2777
PASS stableWithinConversation=true distinctAcrossConversations=true disabledCachingProven=true liveRequests=3
Gateway RPC: successful
Gateway health: ok=true

The deployment owner verified build/source transfer before restarting the Gateway. Its finalization command nevertheless exited nonzero because an existing legacy config-audit archive failed migration; the preserved archive was not altered to bypass that refusal. The recovery path started the verified new runtime, and separate RPC and health checks then passed. Thus the deployed transport proof passed, but the broader update finalization is not claimed as successful.

What was not tested

Live completion proof covers OpenCode Go Chat Completions. Anthropic, Responses, and Gemini are covered by passing request-egress regressions, not successful live completions in these runs. The probes used isolated processes executing the actual managed transport, including the deployed compiled package in the follow-up; they were not full Gateway agent/channel turns. Timings are observations, not a statistically meaningful before/after performance benchmark; no baseline live completion benchmark was run.

OpenCode Go/Zen (opencode.ai) enforces an x-opencode-session header from 2026-09-06 and uses it for prompt-cache routing. Add an "opencode" session-affinity mode detected by baseUrl host (covers zen/go/v1 and zen/v1, OpenAI-completions and Anthropic transports). For opencode hosts the header is sent whenever a stable session id is available, without requiring the sendSessionAffinityHeaders opt-in; the flag-gated generic modes are unchanged.

Fixes openclaw#137165
…e endpoints

Review follow-up: extract isOpencodeEndpoint (trailing-dot safe, parse guarded) shared by both transports; the compliance header now survives cacheRetention none; add Anthropic zen/go and OpenAI zen/v1 regression coverage.
@clawsweeper

clawsweeper Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added size: S triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. and removed triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Sep 3, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 3, 2026
@clawsweeper

clawsweeper Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 6, 2026, 11:58 AM ET / 15:58 UTC.

ClawSweeper review

What this changes

Adds stable OpenCode conversation headers across four model transports while preserving explicit headers and working independently of prompt caching.

Merge readiness

✅ Ready for maintainer review

This PR remains necessary and has no actionable correctness findings. The earlier coverage and header-precedence defects are resolved, and the supplied live transport evidence satisfies the proof requirement.

Priority: P1
Reviewed head: 88f3d1bda27ec49f442ce22076c968ae1bf573ce

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with sufficient live proof, meaningful boundary coverage, and no remaining actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The supplied Linux traces exercise the actual managed Go Completions transport at the reviewed head and repeat through compiled packages: six successful requests demonstrate stable and distinct conversation headers, including disabled caching. Other transports have supplemental egress regressions.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The supplied Linux traces exercise the actual managed Go Completions transport at the reviewed head and repeat through compiled packages: six successful requests demonstrate stable and distinct conversation headers, including disabled caching. Other transports have supplemental egress regressions.
Evidence reviewed 9 items Pinned patch and header policy: The complete new helper restricts automatic identity to HTTPS opencode.ai endpoints, preserves explicit model or stream headers case-insensitively, and does not invent sessionless identity. The previously truncated new tests were read from the local diff.
Prior findings resolved: The managed selector covers all four API families; Google receives identity before plugin dispatch and merges headers using the existing case-insensitive helper. Managed Responses passes the original sessionId into its shared HTTP/WebSocket header builder. These address the concrete earlier findings retained in the supplied review history.
Current main still lacks automatic identity: The scoped current-main search found no x-opencode-session implementation in the provider adapters, transports, or OpenCode plugins. Direct inspection also confirmed that the managed Completions path still passes only options.headers and the shared Responses header builder returns without adding OpenCode identity.
Findings None None.
Security None None.

How this fits together

OpenClaw’s model transports turn agent conversations into requests to hosted model providers. This change carries the existing conversation identifier through SDK and managed transport paths to OpenCode.

flowchart LR
  A[Agent conversation] --> B[Model transport selection]
  B --> C[OpenCode endpoint check]
  C --> D[Preserve explicit header or use conversation ID]
  D --> E[SDK or managed transport]
  E --> F[OpenCode model response]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +64, Tests +230, Docs +5. Total +299 across 16 files.

View PR surface stats
Area Files Added Removed Net
Source 9 83 19 +64
Tests 6 240 10 +230
Docs 1 5 0 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 16 328 29 +299

Review metrics

None.

Technical review

Best possible solution:

Use the existing conversation ID consistently at request construction, preserving configured header precedence and optional cache behavior.

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

Yes: inspected current-main request construction omits the required header, matching the supplied capture-only baseline. This review did not execute a failing live request.

Is this the best way to solve the issue?

Yes: the shared resolver repairs existing request paths without new configuration or storage, and the supplied real completions validate the central Go workflow.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against b3f87ed37006.

Labels

Label justifications:

  • P1: The reported vendor enforcement date has arrived, putting existing OpenCode conversations at risk of rejected requests without the required header.
  • 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 (terminal): The supplied Linux traces exercise the actual managed Go Completions transport at the reviewed head and repeat through compiled packages: six successful requests demonstrate stable and distinct conversation headers, including disabled caching. Other transports have supplemental egress regressions.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied Linux traces exercise the actual managed Go Completions transport at the reviewed head and repeat through compiled packages: six successful requests demonstrate stable and distinct conversation headers, including disabled caching. Other transports have supplemental egress regressions.

Evidence

What I checked:

  • Pinned patch and header policy: The complete new helper restricts automatic identity to HTTPS opencode.ai endpoints, preserves explicit model or stream headers case-insensitively, and does not invent sessionless identity. The previously truncated new tests were read from the local diff. (packages/ai/src/transports/session-affinity.ts:13, 88f3d1bda27e)
  • Prior findings resolved: The managed selector covers all four API families; Google receives identity before plugin dispatch and merges headers using the existing case-insensitive helper. Managed Responses passes the original sessionId into its shared HTTP/WebSocket header builder. These address the concrete earlier findings retained in the supplied review history. (packages/ai/src/transports/provider-transport-stream.ts:74, 88f3d1bda27e)
  • Current main still lacks automatic identity: The scoped current-main search found no x-opencode-session implementation in the provider adapters, transports, or OpenCode plugins. Direct inspection also confirmed that the managed Completions path still passes only options.headers and the shared Responses header builder returns without adding OpenCode identity. (packages/ai/src/transports/openai-transport-params.ts:346, b3f87ed37006)
  • Latest release comparison: The supplied latest release, v2026.9.2, has the shared header builder without the OpenCode addition. No merged fixing replacement is established by the related-item context. (packages/ai/src/transports/openai-transport-params.ts:348, 3928bad9badf)
  • Vendor contract: The current official OpenCode Go documentation explicitly requires the x-opencode-session header for prompt-cache optimization: https://opencode.ai/docs/go/#where-can-i-use-it. This establishes the external provider contract; the change does not depend on the Codex harness.
  • Real transport proof: The fully supplied PR body, retained under sourceRevision 90c823c259628669f05f6faabc0c4645dd1892522fe389f583704a532f609602, records three live OpenCode Go completions through createBoundaryAwareStreamFnForModel at the reviewed head. All returned HTTP 200 and the expected reply; headers remained stable within conversation A, distinct for B, and present with caching disabled. A compiled-package follow-up repeated all three successfully using pinned OpenAI SDK 7.8.0. The observer asserted and forwarded requests without injecting headers. Other API families have request-egress regression coverage, not live completion proof; broader deployment finalization was explicitly not claimed successful. (packages/ai/src/transports/openai-completions-transport.ts:233, 88f3d1bda27e)

Likely related people:

  • VACInc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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 (6 earlier review cycles)
  • reviewed 2026-09-03T18:16:32.704Z sha 916da1b :: needs real behavior proof before merge. :: [P1] Cover the bundled Responses and Gemini transports
  • reviewed 2026-09-06T14:27:02.007Z sha aaafc90 :: needs real behavior proof before merge. :: [P1] Apply the header policy to the managed agent transports | [P1] Preserve explicit model-level session headers
  • reviewed 2026-09-06T14:42:34.995Z sha bf648e0 :: needs real behavior proof before merge. :: [P2] Make the new Gemini precedence case pass at fetch egress
  • reviewed 2026-09-06T14:56:36.920Z sha 88f3d1b :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-06T15:11:46.439Z sha 88f3d1b :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-06T15:36:19.936Z sha 88f3d1b :: needs maintainer review before merge. :: none

@openclaw-barnacle openclaw-barnacle Bot added the docs Improvements or additions to documentation label Sep 6, 2026
@VACInc VACInc self-assigned this Sep 6, 2026
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. label Sep 6, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 6, 2026
@VACInc
VACInc enabled auto-merge (squash) September 6, 2026 17:42
@VACInc
VACInc merged commit b53c4e9 into openclaw:main Sep 6, 2026
182 of 183 checks passed
vincentkoc added a commit that referenced this pull request Sep 6, 2026
* origin/main: (25 commits)
  docs(releases): keep the release-notes nav group to version routes (#140353)
  fix(ui): hide trust wrappers in imported chat history
  fix(subagents): subagent list building decodes unrelated saved prompts in large session stores (#139540)
  test(process): share relay startup fixtures (#140345)
  refactor(doctor): inline GitHub skill discovery inputs (#140343)
  refactor(ui): share channel status type definitions (#140331)
  refactor: simplify queue state and infrastructure dispatch (#140311)
  fix: require saved agent turns before update verification succeeds (#140274)
  fix(update): keep the service profile when switching to Git (#140263)
  fix(ui): prevent image avatars overlapping mobile chat (#140341)
  fix(test): accept release subpages in docs route shape (#140337)
  refactor(plugins): share uninstall mutation ownership (#140322)
  refactor(agents): use canonical tool execution arguments (#140280)
  perf(cli): keep inference metadata and domain help lazy (#140327)
  refactor(plugins): simplify self-hosted setup results (#140332)
  refactor(config): reuse parent lookup for unset operations (#140326)
  fix(plugins): preserve exact installed-index mutation receipts (#140328)
  test(agents): simplify MCP and LSP boundary fixtures (#140312)
  fix(ui): preserve literal source previews and copied whitespace (#140306)
  fix: OpenCode Go/Zen requests are missing the required x-opencode-session header (#137464)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 7, 2026
…sion header (openclaw#137464)

* fix: send x-opencode-session header on OpenCode endpoints

OpenCode Go/Zen (opencode.ai) enforces an x-opencode-session header from 2026-09-06 and uses it for prompt-cache routing. Add an "opencode" session-affinity mode detected by baseUrl host (covers zen/go/v1 and zen/v1, OpenAI-completions and Anthropic transports). For opencode hosts the header is sent whenever a stable session id is available, without requiring the sendSessionAffinityHeaders opt-in; the flag-gated generic modes are unchanged.

Fixes openclaw#137165

* fix: emit x-opencode-session regardless of cache retention on OpenCode endpoints

Review follow-up: extract isOpencodeEndpoint (trailing-dot safe, parse guarded) shared by both transports; the compliance header now survives cacheRetention none; add Anthropic zen/go and OpenAI zen/v1 regression coverage.

* fix(opencode): identify conversations across all model transports

* fix(opencode): cover managed transports and preserve configured identity

* fix(google): merge model and stream headers case-insensitively

* test(opencode): use transport-specific model fixtures

---------

Co-authored-by: Ghilteras <[email protected]>
Co-authored-by: VACInc <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M 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.

opencode-go: send required x-opencode-session header (vendor enforcing from 2026-09-06)

2 participants