Skip to content

feat(opencode): send the Session Scope to the gateway provider - #2903

Merged
hidb4ai merged 6 commits into
oceanbase:masterfrom
Fengzdadi:feat/opencode-gateway-scope-header
Dec 3, 2026
Merged

hidb4ai merged 6 commits into
oceanbase:masterfrom
Fengzdadi:feat/opencode-gateway-scope-header

Conversation

@Fengzdadi

@Fengzdadi Fengzdadi commented Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator

Which issue or RFC does this PR close?

Part of #2250 (step 5: plugins behind the gateway).

Rationale for this change

When OpenCode's model requests go through the PowerContext gateway and POWERCONTEXT_OPENCODE_PROMPT_RECALL=false leaves prompt-time context to the gateway, the gateway prepares, checks, and captures each turn. Until now it did that in PC_GATEWAY_DEFAULT_SCOPE, while the plugin's own pc_* tools used the Scope the plugin resolves for the Session. One gateway serving several workspaces therefore mixed their turns into one Scope, and the guide asked users to set the header or the gateway default by hand.

#2810 lets a request select its Scope with X-PowerContext-Scope-ID. RFC 2199 §3 limits Scope selection to that header or a credential bound to one Scope, so the gateway does not infer a Scope from session IDs or prompts. The plugin already resolves the Session's Scope, so this PR has it send that Scope on its gateway requests, as #2893 does for Pi.

What changes are included in this PR?

OpenCode plugin (integrations/opencode/plugins/powercontext):

  • New setting POWERCONTEXT_OPENCODE_GATEWAY_PROVIDER: the OpenCode provider ID (its key under provider in the OpenCode configuration) that points at the gateway. While prompt recall is off, a new chat.headers hook sets X-PowerContext-Scope-ID: <Session Scope> on every model request whose model.providerID equals it. The Scope is the one the plugin's pc_* tools use: POWERCONTEXT_OPENCODE_SCOPE_ID, then the Session binding, then the workspace binding (with the linked-worktree fallback), then the Server default.
  • Decision: send the Scope only to the named provider. chat.headers receives the request's model and provider, so the plugin can tell gateway requests from requests that OpenCode sends straight to a provider. Requests to any other provider carry no Scope header, so Scope IDs do not reach third-party endpoints.
  • Decision: the setting is a provider ID rather than a URL match against the plugin's Server URL. The plugin's Server URL may or may not be the gateway's address, and matching on it would silently drop the header in a split deployment. This is the same choice as feat(pi): send the workspace Scope to the gateway provider #2893.
  • Decision: send the header only while prompt recall is off, as feat(pi): send the workspace Scope to the gateway provider #2893 does. Recall off is the documented gateway mode. With recall on, the plugin adds its own prepared-context block, which Core rejects behind the gateway, so recall-on gateway traffic is not a supported setup and gains nothing from the header. Keeping one switch also keeps recall-on behavior exactly as before, and keeps the two hosts' rules the same.
  • The Scope stays fixed for the Session. The plugin resolves the Session's Scope with resolveScopeId(..., persistSession: true): each resolution sends POST /v1/scope-bindings/resolve and, unless POWERCONTEXT_OPENCODE_SCOPE_ID is set, writes the result as the Session binding with PUT /v1/scope-bindings. The resolve request lists the Session binding key before the workspace keys, and the Server returns the Scope of the first key that has a binding, so every resolution after the first returns the Session's Scope, also after the workspace binding changes or the Session is resumed. Resolution is not limited to once per Session: the session.created/session.updated handler, already on master, starts a fresh resolution on every such event and replaces the cached result, and chat.headers and the pc_* tools resolve whenever nothing is cached. With OpenCode 1.19.6 and recall and capture both off, two turns of one Session made seven resolve requests and seven binding writes. This PR leaves that refresh as it is and documents it.
  • If the Scope cannot be resolved (Server unavailable, Session without a directory, invalid response), the request carries no Scope header and proceeds, so the gateway uses PC_GATEWAY_DEFAULT_SCOPE. The plugin logs the content-free event {"event":"gateway_scope","outcome":"failed"} at warn through OpenCode's app log. A failed resolution is not cached, so the next request tries again, bounded by the plugin's per-request timeout.
  • If the resolved Scope ID is outside the header's syntax (1–256 characters, each U+0021–U+007E except ,), the request also carries no Scope header and proceeds in PC_GATEWAY_DEFAULT_SCOPE. Scope resolution is unchanged, so the pc_* tools and the plugin's other Server calls keep that Scope. The plugin logs {"event":"gateway_scope","outcome":"skipped","reason":"scope_id_unsupported"} at warn, once per Session; the event never includes the ID. The check matches the one _scope_headers applies in prefixed_extraction.py (feat(gateway): bind model requests to an explicit Scope #2810).
  • lib/index.js and lib/tui.js (lib/tui.d.ts) are regenerated with pnpm build. The TUI bundle changes only because it shares ResolvedConfig.

Host hook this relies on: the plugin's minimum @opencode-ai/plugin 1.18.21 declares chat.headers (input {sessionID, agent, model, provider, message}, output {headers}). In the installed OpenCode 1.19.6 runtime, the LLM request builder triggers chat.headers once per model request and spreads its headers last into the request headers (...model.headers, ...pluginHeaders), which go to the AI SDK streamText call (and to the native runtime path). A header that the model's headers configuration also sets with the same spelling is therefore replaced by the plugin's value. The real-host runs below confirm that the header reaches the HTTP request on both @ai-sdk/openai-compatible (Chat) and @ai-sdk/openai (Responses).

Gateway contract this relies on (#2810, deploy-server.md "Gateway request Scope" and "Gateway authentication boundaries"): the header takes one Scope ID of 1–256 visible ASCII characters without commas; anything else gets HTTP 400 invalid_scope_id. The Server accepts any Scope ID of 1–256 characters with one non-space and keeps the exact IDs of Scopes from early releases, and resolve_scope_binding returns such an ID for an explicit POWERCONTEXT_OPENCODE_SCOPE_ID or a Session or workspace binding. Sending one outside the header's syntax would fail every model request of the Session: in Node 22, team,alpha, team alpha and café pass Headers.set and the gateway answers them with the 400, while 团队 throws a ByteString TypeError before the request is sent. The plugin therefore sends only IDs inside the header's syntax. Any client that can call the gateway can select any Scope that the gateway's Core credential can access, and the gateway prepares, checks, and captures under that credential.

Docs (docs/en/docs/integrations/opencode.md, docs/zh/docs/integrations/opencode.md), section "Leave prompt-time context to the gateway":

  • The settings example exports POWERCONTEXT_OPENCODE_GATEWAY_PROVIDER=powercontext-gateway, the provider ID that agent-install.md uses for the gateway.
  • The Scope paragraph now describes the setting: the provider rule, that the header carries the Session's Scope and stays fixed for the Session, when the plugin resolves the Scope and why each resolution returns the same one, the fallback to PC_GATEWAY_DEFAULT_SCOPE (also for a Scope whose ID the header cannot carry, with a warning), and not adding the header to the provider configuration by hand.
  • A new paragraph states the gateway's Core grants in the wording of the OpenClaw and Hermes guides: when Core enforces authentication, PC_GATEWAY_CORE_TOKEN is an authenticated service identity with server.observer on the Server resource and, when capture is enabled, scope.contributor on PC_GATEWAY_DEFAULT_SCOPE and on every Session Scope the plugin sends (otherwise scope.viewer). It repeats that any client that can call the gateway can select any Scope the gateway's Core credential can access, and links "Gateway authentication boundaries".
  • The plugin README lists the setting and the fallback for a Scope ID the header cannot carry.

Tests:

  • tests/plugin.spec.ts: the named provider gets the Session Scope; another provider gets none; the Scope is resolved once for repeated requests; recall on sends none; no setting sends nothing and makes no Server request; a failed resolution (Server 503, Session without a directory) sends no header and logs gateway_scope; a Scope ID with a comma (team,alpha) and a non-Latin-1 one (团队) each get no header and no error across two requests of the Session, with exactly one warn that does not contain the ID, while a valid ID is still sent. tests/config.spec.ts reads the variable.
  • tests/e2e/test_opencode_service_chain.py::test_opencode_sends_the_session_scope_only_to_the_gateway_provider runs real OpenCode with the plugin bundle and a real Server. The Session resolves its Scope through a workspace binding. The test checks that every model request to the named provider (@ai-sdk/openai-compatible) carries that Scope, also after the workspace binding moves to another Scope, and that with another provider named, requests carry no Scope header. The model fixture stands in for the gateway, so this case checks what OpenCode sends; no gateway runs in it. To support this, HostModelFixture (tests/e2e/zcode_acceptance/protocol.py) now also keeps each request's headers in request_headers, index-aligned with requests.

Overlap with open PRs, checked on 10dbf51 before the master merge: #2860 also edits the plugin sources and bundle. It, #2889 and #2898 each merge cleanly with this branch (git merge-tree). For the merge with #2860, a rebuild reproduces the committed bundles, and the plugin tests and typecheck pass. #2725 conflicts with this branch only in files it does not touch, the same conflicts it has with master.

Are there any user-facing changes?

Yes, one new opt-in setting for the OpenCode plugin, POWERCONTEXT_OPENCODE_GATEWAY_PROVIDER. Without it, nothing changes. With it and prompt recall off, the gateway works in each Session's Scope instead of PC_GATEWAY_DEFAULT_SCOPE. Turns captured from then on land in a different Scope than before for setups whose default differed from the Session Scope. When Core enforces authentication, the gateway's Core identity needs access to those Scopes (scope.contributor with capture on). Turns captured earlier stay where they are. No API or persisted-format changes.

How was this change tested?

On the merged tree, d0289b8 (this branch merged with master at 667f77e, which includes #2920, plus the grant-wording commit), offline:

  • In integrations/opencode/plugins/powercontext: pnpm test (166 passed), pnpm typecheck, and pnpm build; the rebuilt lib/ matches the commit.
  • uv run pytest tests/test_ci_changes.py: 185 passed.
  • OPENCODE_CLI_BIN=<opencode 1.19.6> uv run pytest tests/e2e/test_opencode_service_chain.py tests/e2e/test_opencode_plugin_host.py tests/test_zcode_acceptance_protocol.py: 27 passed. These run real OpenCode and a real Server against a fixture model; no gateway runs in them.
  • A manual run of real OpenCode 1.19.6 (opencode serve), a gateway built from this tree's gateway/ (cargo build --locked -p pc-gateway-app), and a real Server over UDS with access control enforced and an enforcing privacy mode. The gateway used master's restored configuration: PC_GATEWAY_UPSTREAM_URL_RESPONSES pointing at a stub Responses upstream, PC_GATEWAY_UPSTREAM_API_KEY, PC_GATEWAY_UPSTREAM_PROFILE naming Core's target, and PC_GATEWAY_SEDIMENT=on. Its Core token was the Server's bootstrap token, which has static Scope roles, so no grants were created. The powercontext-gateway provider used @ai-sdk/openai through a header-recording proxy to the gateway, and a second provider called a header-recording Chat stub directly. Two Scopes, each with a different Memory: the workspace Scope (bound to the workspace, no POWERCONTEXT_OPENCODE_SCOPE_ID) and PC_GATEWAY_DEFAULT_SCOPE. Results:
    • the gateway request carried X-PowerContext-Scope-ID: <workspace Scope>, the gateway returned 200, and OpenCode received the stub's answer;
    • the upstream request held the workspace Memory and not the default Scope's;
    • the gateway captured the turn in the workspace Scope, and the default Scope got no gateway turn;
    • the direct provider's request carried x-opencode-session-id and no Scope header.
  • prek run --files on every file this PR changes passed. Every relative link and anchor in both OpenCode guides and the plugin README resolves on the merged tree, checked by hand; the website build (make docs-test) was not run.

Before the merge, on 10dbf51:

Not covered: OpenCode 1.18.21, the plugin's minimum (the hook's types were checked in @opencode-ai/plugin 1.18.21, but its runtime was not run; the runs used 1.19.6); a live model or provider; OpenCode's TUI; a Chat-route turn through the gateway (an enforcing Core withholds streamed Chat Completions, so the guide documents Responses for the gateway, and the Chat header path was run against the fixture only); subagent Sessions (each resolves its own Session Scope, like the plugin's tools); a gateway without #2810; a gateway Core identity other than the bootstrap token, so the per-Scope grants the guide lists were not exercised, nor what a Session Scope without them, or one that does not exist, gets on the merged tree. The Gateway path in docs/en/docs/get-started/agent-install.md and docs/zh/docs/get-started/agent-install.md still sets up the powercontext-gateway provider without POWERCONTEXT_OPENCODE_GATEWAY_PROVIDER; that change is left for a follow-up.

AI usage statement

Claude Code (Claude Opus 5.5) wrote the change, ran the tests and the real OpenCode, gateway, and Server runs listed above, and wrote this description. After #2920 reverted #2630, Claude Code also merged master into this branch, moved the guide's gateway grants to master's restored contract, and reran the checks on the merged tree. Another Claude Code session (Claude Opus 5.5) reviewed the merge resolution and the grant commit against master's gateway docs and code and checked this description's changed claims, without rerunning the tests.

With prompt recall off, the OpenCode plugin now sets X-PowerContext-Scope-ID
on model requests to the provider named by
POWERCONTEXT_OPENCODE_GATEWAY_PROVIDER, using the Scope it resolves for the
Session. Other providers get no Scope header, and an unresolved Scope sends
none, so the gateway falls back to PC_GATEWAY_DEFAULT_SCOPE.

Part of oceanbase#2250.
The gateway takes X-PowerContext-Scope-ID only as one ID of 1-256 visible
ASCII characters without a comma, but Scopes from early releases can have
other IDs. For such a Session the plugin now sends no Scope header, so the
request proceeds in the gateway's default Scope instead of failing with
HTTP 400 (or a Headers TypeError for non-Latin-1 IDs), and it logs one
content-free warning per Session. Scope resolution is unchanged.
@AlexStocks AlexStocks added the 1.6.2 v1.6.2 release tracking label Nov 30, 2026

@hidb4ai hidb4ai 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.

The real OpenCode → Gateway → Core → live-LLM path preserved Session Scope across a workspace-binding change, including recall and capture. One non-blocking documentation correction below. Validation used SQLite and disabled inference protection; it does not establish enforcing-mode or Responses acceptance. No database changes; the new gateway-provider environment setting is a public configuration interface, so automatic approval is withheld under the requested review criteria.

Comment thread docs/en/docs/integrations/opencode.md Resolved
The plugin resolves the Session Scope on every session.created and
session.updated event and whenever it needs the Scope without a cached
result, not once per Session. Each resolution also writes the Session
binding, which takes precedence over the workspace binding, so the Session
keeps one Scope.

@hireview001 hireview001 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM

@hidb4ai hidb4ai added module:core Core: PR changes under src/ module:gateway Primary module: model gateway, protocols and context injection and removed module:core Core: PR changes under src/ labels Dec 2, 2026
@hireview001

Copy link
Copy Markdown
Collaborator

The affected modules are Gateway. @frf12, please coordinate follow-up. Gateway: @frf12 @happy-v587 @NeverENG. Please coordinate the review of the affected changes.

@hireview001 hireview001 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM

@happy-v587 happy-v587 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewed independently (branch @ 75c1889b, full clone, real runs on macOS):

Verified green locally

  • Plugin suite: 166/166 passed (pnpm test), tsc --noEmit clean, tsdown rebuild reproduces the committed lib/index.js byte-for-byte (git status clean after build).
  • Real e2e with OpenCode 1.19.6 (OPENCODE_CLI_BIN=/opt/homebrew/bin/opencode): all 8 cases in test_opencode_service_chain.py pass, including the new test_opencode_sends_the_session_scope_only_to_the_gateway_provider (header follows the Session Scope across a workspace rebind; absent for other providers).
  • Regex contract check: GATEWAY_SCOPE_ID rejects team,alpha, team alpha, café, 团队; accepts 1–256 visible-ASCII-without-comma, exactly matching the gateway's _scope_headers rule (#2810).
  • CI on this head is green (I checked the non-skipping list).

Design assessment: sound.

  • Scoping the header to the named provider (not a URL match) is the right call for split deployments, and not sending it while recall is on keeps unsupported gateway traffic from double-adding context.
  • Fail-open without the header (gateway falls back to PC_GATEWAY_DEFAULT_SCOPE) is the correct failure mode; the once-per-Session warn (content-free, ID never logged, bounded cache with the same 256 eviction pattern as turns) is proportionate.
  • The PR body's honest "not covered" list (1.18.21 runtime, Chat-route through a real gateway, agent-install.md follow-up) matches what I found; nothing overstated.

Non-blocking observations:

  1. Misconfiguration risk: if POWERCONTEXT_OPENCODE_GATEWAY_PROVIDER is accidentally pointed at a third-party provider, that provider receives X-PowerContext-Scope-ID. It leaks only the internal Scope ID, not data, and the README documents the setting's meaning — acceptable, but a one-line warning in the docs' settings example ("this provider receives the header") would harden it further.
  2. chat.headers resolves the Session context on cache misses inside the request path (documented: 4 resolve + 4 binding writes after turn 1, 7 after turn 2 in your count; I did not re-count). Since resolution is bounded by requestTimeoutMs and fail-open, fine as-is; the PR already leaves refresh optimization for later.
  3. The PR is mergeable-blocked on review approvals, not checks.

No blockers from me.

@happy-v587 happy-v587 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Verified locally in my earlier review (full clone + real test runs, see my COMMENTED review below): all relevant suites pass, no blockers. Approving as confirmed by the project owner.

@NeverENG NeverENG left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-review report — host integration

Reviewed head: 75c1889bb2e6c2e2f9961cbae87ffc6424572b54.

Result: no additional actionable findings in the reviewed host-integration changes.

Confirmed that chat.headers adds the Scope only with prompt recall disabled and for the named gateway provider. Session binding takes precedence over workspace binding. Unsupported header IDs are omitted with a bounded warning path; the source and published bundle agree. Documentation now correctly describes event-triggered Scope resolution instead of claiming a single resolution per Session. The two existing findings are addressed in the reviewed head.

Reviewed configuration, Session resolution and caching, request headers, generated bundle, bilingual documentation, and relevant tests. Existing CI for this head passed 166 package tests and 8 real-OpenCode service-chain tests. The header acceptance case uses a recording model fixture in place of the gateway: it verifies what OpenCode sends, not the complete Gateway/Core chain.

Validation scope: I inspected the current source, complete PR diff, existing review threads, and CI logs for this head. No new local test run was performed in this re-review. The cited CI ran a test merge with its then-current base; it is not proof of a merge with the latest master. This is a comment-only report, not an approval or an unconditional merge recommendation.

@hidb4ai
hidb4ai merged commit 57461d6 into oceanbase:master Dec 3, 2026
49 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

1.6.2 v1.6.2 release tracking module:gateway Primary module: model gateway, protocols and context injection

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants