Repository navigation
feat(opencode): send the Session Scope to the gateway provider - #2903
Conversation
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.
hidb4ai
left a comment
There was a problem hiding this comment.
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.
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.
Resolve opencode.md (en/zh) in favor of master's restored gateway target paragraph from oceanbase#2920.
|
The affected modules are Gateway. @frf12, please coordinate follow-up. Gateway: @frf12 @happy-v587 @NeverENG. Please coordinate the review of the affected changes. |
happy-v587
left a comment
There was a problem hiding this comment.
Reviewed independently (branch @ 75c1889b, full clone, real runs on macOS):
Verified green locally
- Plugin suite: 166/166 passed (
pnpm test),tsc --noEmitclean,tsdownrebuild reproduces the committedlib/index.jsbyte-for-byte (git status clean after build). - Real e2e with OpenCode 1.19.6 (
OPENCODE_CLI_BIN=/opt/homebrew/bin/opencode): all 8 cases intest_opencode_service_chain.pypass, including the newtest_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_IDrejectsteam,alpha,team alpha,café,团队; accepts 1–256 visible-ASCII-without-comma, exactly matching the gateway's_scope_headersrule (#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 asturns) 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:
- Misconfiguration risk: if
POWERCONTEXT_OPENCODE_GATEWAY_PROVIDERis accidentally pointed at a third-party provider, that provider receivesX-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. chat.headersresolves 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 byrequestTimeoutMsand fail-open, fine as-is; the PR already leaves refresh optimization for later.- The PR is mergeable-blocked on review approvals, not checks.
No blockers from me.
happy-v587
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
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=falseleaves prompt-time context to the gateway, the gateway prepares, checks, and captures each turn. Until now it did that inPC_GATEWAY_DEFAULT_SCOPE, while the plugin's ownpc_*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):POWERCONTEXT_OPENCODE_GATEWAY_PROVIDER: the OpenCode provider ID (its key underproviderin the OpenCode configuration) that points at the gateway. While prompt recall is off, a newchat.headershook setsX-PowerContext-Scope-ID: <Session Scope>on every model request whosemodel.providerIDequals it. The Scope is the one the plugin'spc_*tools use:POWERCONTEXT_OPENCODE_SCOPE_ID, then the Session binding, then the workspace binding (with the linked-worktree fallback), then the Server default.chat.headersreceives 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.resolveScopeId(..., persistSession: true): each resolution sendsPOST /v1/scope-bindings/resolveand, unlessPOWERCONTEXT_OPENCODE_SCOPE_IDis set, writes the result as the Session binding withPUT /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: thesession.created/session.updatedhandler, already on master, starts a fresh resolution on every such event and replaces the cached result, andchat.headersand thepc_*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.PC_GATEWAY_DEFAULT_SCOPE. The plugin logs the content-free event{"event":"gateway_scope","outcome":"failed"}atwarnthrough OpenCode's app log. A failed resolution is not cached, so the next request tries again, bounded by the plugin's per-request timeout.,), the request also carries no Scope header and proceeds inPC_GATEWAY_DEFAULT_SCOPE. Scope resolution is unchanged, so thepc_*tools and the plugin's other Server calls keep that Scope. The plugin logs{"event":"gateway_scope","outcome":"skipped","reason":"scope_id_unsupported"}atwarn, once per Session; the event never includes the ID. The check matches the one_scope_headersapplies inprefixed_extraction.py(feat(gateway): bind model requests to an explicit Scope #2810).lib/index.jsandlib/tui.js(lib/tui.d.ts) are regenerated withpnpm build. The TUI bundle changes only because it sharesResolvedConfig.Host hook this relies on: the plugin's minimum
@opencode-ai/plugin1.18.21 declareschat.headers(input{sessionID, agent, model, provider, message}, output{headers}). In the installed OpenCode 1.19.6 runtime, the LLM request builder triggerschat.headersonce per model request and spreads its headers last into the request headers (...model.headers, ...pluginHeaders), which go to the AI SDKstreamTextcall (and to the native runtime path). A header that the model'sheadersconfiguration 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 400invalid_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, andresolve_scope_bindingreturns such an ID for an explicitPOWERCONTEXT_OPENCODE_SCOPE_IDor 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 alphaandcafépassHeaders.setand the gateway answers them with the 400, while团队throws a ByteStringTypeErrorbefore 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":POWERCONTEXT_OPENCODE_GATEWAY_PROVIDER=powercontext-gateway, the provider ID thatagent-install.mduses for the gateway.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.PC_GATEWAY_CORE_TOKENis an authenticated service identity withserver.observeron the Server resource and, when capture is enabled,scope.contributoronPC_GATEWAY_DEFAULT_SCOPEand on every Session Scope the plugin sends (otherwisescope.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".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 logsgateway_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 onewarnthat does not contain the ID, while a valid ID is still sent.tests/config.spec.tsreads the variable.tests/e2e/test_opencode_service_chain.py::test_opencode_sends_the_session_scope_only_to_the_gateway_providerruns 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 inrequest_headers, index-aligned withrequests.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 ofPC_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.contributorwith 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:
integrations/opencode/plugins/powercontext:pnpm test(166 passed),pnpm typecheck, andpnpm build; the rebuiltlib/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.opencode serve), a gateway built from this tree'sgateway/(cargo build --locked -p pc-gateway-app), and a real Server over UDS with access controlenforcedand an enforcing privacy mode. The gateway used master's restored configuration:PC_GATEWAY_UPSTREAM_URL_RESPONSESpointing at a stub Responses upstream,PC_GATEWAY_UPSTREAM_API_KEY,PC_GATEWAY_UPSTREAM_PROFILEnaming Core's target, andPC_GATEWAY_SEDIMENT=on. Its Core token was the Server's bootstrap token, which has static Scope roles, so no grants were created. Thepowercontext-gatewayprovider used@ai-sdk/openaithrough 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, noPOWERCONTEXT_OPENCODE_SCOPE_ID) andPC_GATEWAY_DEFAULT_SCOPE. Results:X-PowerContext-Scope-ID: <workspace Scope>, the gateway returned 200, and OpenCode received the stub's answer;x-opencode-session-idand no Scope header.prek run --fileson 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:
src/index.tsreverted to master, the two new hook tests fail. With the provider check removed, the provider test fails. With the Scope ID check or the once-per-Session guard removed, the unsupported-ID test fails. The new e2e case fails against master'slib/index.js(the requests carry no Scope header).test_opencode_service_chain.py) recorded 4 resolve requests and 4 binding writes after the first turn and 7 of each after the second, and every model request carried the same Scope.git merge-treewith refactor(integrations): generate the recall query bound from integrations/lifecycle #2860 (391609c), feat(cli): add setup --remove to undo one agent's setup #2889 (dc5ffc1) and fix(opencode): skip the activation probe when the plugin is not configured #2898 (b22f5e2) was clean; rebuilding the merges with refactor(integrations): generate the recall query bound from integrations/lifecycle #2860 and fix(opencode): skip the activation probe when the plugin is not configured #2898 reproduced the committed bundles, with the plugin tests (166) and typecheck passing. These were not rerun after the merge.make checkpassed.Not covered: OpenCode 1.18.21, the plugin's minimum (the hook's types were checked in
@opencode-ai/plugin1.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 indocs/en/docs/get-started/agent-install.mdanddocs/zh/docs/get-started/agent-install.mdstill sets up thepowercontext-gatewayprovider withoutPOWERCONTEXT_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.