Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 26 additions & 5 deletions docs/en/docs/integrations/opencode.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,12 @@ available for explicit retrieval.

When OpenCode sends its model requests through the PowerContext gateway, the gateway prepares and injects context for
each turn and, with `PC_GATEWAY_SEDIMENT=on`, captures the turn. Turn the plugin's prompt-time recall and prompt
capture off before starting OpenCode:
capture off, and name the gateway provider, before starting OpenCode:

```bash
export POWERCONTEXT_OPENCODE_PROMPT_RECALL=false
export POWERCONTEXT_OPENCODE_CAPTURE_PROMPTS=false
export POWERCONTEXT_OPENCODE_GATEWAY_PROVIDER=powercontext-gateway
opencode
```

Expand All @@ -105,10 +106,30 @@ a complete PowerContext prepared-context block, the gateway replaces that result
`PowerContext plugin prepared context omitted by the gateway.` and keeps its tool call ID. The request and response
still go through Core's normal checks.

With recall off, prompt-time context comes only from the gateway. The gateway prepares and captures in the Scope
selected by `X-PowerContext-Scope-ID` and uses `PC_GATEWAY_DEFAULT_SCOPE` when the header is absent. To match the Scope
the plugin resolves for the Session or workspace, use that Scope in the header or as the default. See
[Gateway request Scope](../operate/deploy-server.md#gateway-request-scope).
With recall off, prompt-time context comes only from the gateway. `POWERCONTEXT_OPENCODE_GATEWAY_PROVIDER` names the
OpenCode provider that points at the gateway, by its key under `provider` in the OpenCode configuration. While recall
is off, the plugin sends the Session's Scope, the one its `pc_*` tools use, as `X-PowerContext-Scope-ID` on every model
request to that provider. The gateway then prepares, checks, and captures each turn in that Scope instead of
`PC_GATEWAY_DEFAULT_SCOPE`. Requests to any other provider carry no Scope header. A Session keeps the Scope it resolved
first, so all of its requests select the same Scope, also after a resume. Even with recall and capture both off, the
plugin resolves the Scope each time OpenCode reports that the Session was created or updated, which can happen several
times in one turn, and whenever it needs the Scope and has none cached, for example after a restart or a failed
resolution. 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 Session binding takes precedence over
the workspace binding, so every later resolution returns the Scope of the first one. When the variable is unset or the
plugin cannot resolve the Session's Scope, the request carries no Scope header and the gateway uses
`PC_GATEWAY_DEFAULT_SCOPE`; with the variable unset, set that default to the Scope the plugin resolves.
The plugin sets the header itself, so do not also add it to the provider's configuration. A Scope whose ID the header
cannot carry (Scopes from early releases can have one) also gets no header: the gateway uses its default Scope, and the
plugin logs a warning once per Session. See [Gateway request Scope](../operate/deploy-server.md#gateway-request-scope)
for the header's rule.

When Core enforces authentication, set `PC_GATEWAY_CORE_TOKEN` to an authenticated service identity. Grant it
`server.observer` on the Server resource for `POWERCONTEXT_SERVER_ACCESS_DEPLOYMENT_ID` (default `powercontext`),
and, when capture is enabled, `scope.contributor` (which includes `scope.read`) on `PC_GATEWAY_DEFAULT_SCOPE` and on
every Session Scope the plugin sends. Otherwise `scope.viewer` is sufficient for the gateway's read-side calls. Any
client that can call the gateway can select any Scope that the gateway's Core credential can access. See
[Gateway authentication boundaries](../operate/deploy-server.md#gateway-authentication-boundaries).

OpenCode sends its session ID in the `x-opencode-session-id` header of every model request. A gateway connected to
the Core over UDS therefore prepares and injects each OpenCode turn by default; a standalone gateway needs
Expand Down
31 changes: 27 additions & 4 deletions docs/zh/docs/integrations/opencode.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,12 @@ HTTPS 证书校验仍然启用。安装与持久化同意见[连接远程 Server
## 把提示词时上下文交给 gateway

OpenCode 的模型请求经过 PowerContext gateway 时,gateway 为每一轮准备并注入上下文;设置 `PC_GATEWAY_SEDIMENT=on`
后,gateway 也会采集这一轮。启动 OpenCode 前,关闭插件的提示词时召回和提示词采集:
后,gateway 也会采集这一轮。启动 OpenCode 前,关闭插件的提示词时召回和提示词采集,并指定 gateway provider:

```bash
export POWERCONTEXT_OPENCODE_PROMPT_RECALL=false
export POWERCONTEXT_OPENCODE_CAPTURE_PROMPTS=false
export POWERCONTEXT_OPENCODE_GATEWAY_PROVIDER=powercontext-gateway
opencode
```

Expand All @@ -94,9 +95,31 @@ opencode
gateway 会将该结果的文本替换为 `PowerContext plugin prepared context omitted by the gateway.`,并保留工具调用 ID。
请求和响应仍会经过 Core 的常规检查。

关闭召回后,提示词时上下文只来自 gateway。gateway 在 `X-PowerContext-Scope-ID` 选择的 Scope 中准备和采集,
未发送该请求头时使用 `PC_GATEWAY_DEFAULT_SCOPE`。若要使用插件为 Session 或 workspace 解析的 Scope,请在请求头
中指定该 Scope,或将其设为默认值。见 [Gateway 请求 Scope](../operate/deploy-server.md#gateway-请求-scope)。
关闭召回后,提示词时上下文只来自 gateway。
`POWERCONTEXT_OPENCODE_GATEWAY_PROVIDER` 指定指向 gateway 的 OpenCode provider,取值为它在 OpenCode 配置 `provider` 下的键名。
关闭召回时,插件会把 Session 的 Scope(即 `pc_*` 工具使用的 Scope)作为 `X-PowerContext-Scope-ID`,
发送到这个 provider 的每个模型请求上。
gateway 随后在这个 Scope 而不是 `PC_GATEWAY_DEFAULT_SCOPE` 中准备、检查和采集每一轮。
发给其他 provider 的请求不带 Scope 请求头。Session 始终使用它最初解析的 Scope,因此它的所有请求都选择同一个 Scope,
恢复会话后也是如此。
即使召回和采集都已关闭,每当 OpenCode 报告 Session 已创建或已更新时,插件都会解析 Scope,
这在一轮中可能发生多次;插件需要 Scope 而没有缓存结果时(例如重启后或解析失败后),也会解析。
每次解析都发送 `POST /v1/scope-bindings/resolve`;未设置 `POWERCONTEXT_OPENCODE_SCOPE_ID` 时,
还会用 `PUT /v1/scope-bindings` 把结果写为 Session binding。
Session binding 优先于 workspace binding,因此之后的每次解析都返回第一次解析的 Scope。
未设置这个变量,或插件无法解析 Session 的 Scope 时,请求不带 Scope 请求头,
gateway 使用 `PC_GATEWAY_DEFAULT_SCOPE`;未设置这个变量时,请把这个默认值设为插件解析的 Scope。
插件会自行设置这个请求头,因此不要再在 provider 配置中添加它。
如果 Scope 的 ID 无法放入这个请求头(早期版本的 Scope 可能有这样的 ID),请求同样不带 Scope 请求头:
gateway 使用默认 Scope,插件在每个 Session 中记录一次警告。
请求头的规则见 [Gateway 请求 Scope](../operate/deploy-server.md#gateway-请求-scope)。

Core 启用鉴权时,把 `PC_GATEWAY_CORE_TOKEN` 设为经过认证的服务身份。
请在 `POWERCONTEXT_SERVER_ACCESS_DEPLOYMENT_ID`(默认 `powercontext`)对应的 Server 资源上授予它 `server.observer`;
启用采集时,还要在 `PC_GATEWAY_DEFAULT_SCOPE` 以及插件发送的每个 Session Scope 上授予 `scope.contributor`(包含 `scope.read`),
否则 `scope.viewer` 足以完成 gateway 的只读调用。
任何能调用 gateway 的客户端,都能选择 gateway 的 Core 凭据可访问的任何 Scope。
见[网关认证边界](../operate/deploy-server.md#网关认证边界)。

OpenCode 在每个模型请求的 `x-opencode-session-id` 头中发送会话 ID。因此,通过 UDS 连接 Core 的 gateway 默认为
OpenCode 的每一轮准备并注入上下文;独立运行的 gateway 需要设置 `PC_GATEWAY_INJECTION=on`。见
Expand Down
9 changes: 6 additions & 3 deletions integrations/opencode/plugins/powercontext/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ remain in the separate Server plugin entrypoint.

Each Session resolves an explicit Scope, its durable Session or workspace binding, or the Server default. Set
`POWERCONTEXT_OPENCODE_SCOPE_ID` only to force an existing Scope. Other configuration uses the same prefix with `BASE_URL`,
`AUTHORIZATION`, `PROMPT_RECALL`, `CAPTURE_PROMPTS`, `FLUSH_ON_CAPTURE`, `REQUEST_TIMEOUT_MS`, `HTTP_BUDGET_MS`, `MAX_BYTES`, and
`FLUSH_MAX_CALLS`.
`AUTHORIZATION`, `PROMPT_RECALL`, `GATEWAY_PROVIDER`, `CAPTURE_PROMPTS`, `FLUSH_ON_CAPTURE`, `REQUEST_TIMEOUT_MS`,
`HTTP_BUDGET_MS`, `MAX_BYTES`, and `FLUSH_MAX_CALLS`.

Remote HTTP is rejected by default. Explicitly allow it with `POWERCONTEXT_OPENCODE_ALLOW_INSECURE_HTTP=true`,
or use `POWERCONTEXT_CLIENT_ALLOW_INSECURE_HTTP=true` as the common fallback. A host flag of `false` overrides
Expand All @@ -46,6 +46,9 @@ reuse saved HTTP consent.

Prompt-time recall is enabled by default. Set `POWERCONTEXT_OPENCODE_PROMPT_RECALL=false` when OpenCode's model
traffic goes through the PowerContext gateway, which prepares and injects context for each turn; the plugin then sends
no preparation request, adds no context, and does not offer the `pc_prepare_context` tool.
no preparation request, adds no context, and does not offer the `pc_prepare_context` tool. Also set
`POWERCONTEXT_OPENCODE_GATEWAY_PROVIDER` to the OpenCode provider that points at the gateway; while recall is off, its
model requests carry the Session's Scope as `X-PowerContext-Scope-ID`, and requests to other providers carry none. A
Scope whose ID the header cannot carry is left out with a warning, so the gateway uses its default Scope.

OpenCode 1.18.21 or newer in the 1.x line is required. Server failures are fail-open and never block normal work.
38 changes: 36 additions & 2 deletions integrations/opencode/plugins/powercontext/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2135,6 +2135,7 @@ const DEFAULTS = {
scopeId: void 0,
authorization: void 0,
promptRecall: true,
gatewayProvider: void 0,
capturePrompts: true,
requestTimeoutMs: 3e3,
httpBudgetMs: 6e3,
Expand Down Expand Up @@ -2192,6 +2193,7 @@ function resolveConfig(env = process.env) {
scopeId: envString(env, "POWERCONTEXT_OPENCODE_SCOPE_ID"),
authorization: envString(env, "POWERCONTEXT_OPENCODE_AUTHORIZATION"),
promptRecall: envBoolean(env, "POWERCONTEXT_OPENCODE_PROMPT_RECALL") ?? DEFAULTS.promptRecall,
gatewayProvider: envString(env, "POWERCONTEXT_OPENCODE_GATEWAY_PROVIDER"),
capturePrompts: envBoolean(env, "POWERCONTEXT_OPENCODE_CAPTURE_PROMPTS") ?? DEFAULTS.capturePrompts,
requestTimeoutMs,
httpBudgetMs,
Expand Down Expand Up @@ -2615,6 +2617,9 @@ Use pc_review_list / pc_review_get for requested candidate inspection. Generatio
Memory correction requires the requested change, exact current Atomic Memory artifact and real content ETag from pc_memory_get. pc_memory_retire sets recoverable forgotten state using the exact artifact and state_version from search, list or pc_memory_state. Follow next_cursor for later inventory pages. Empty retrieval is normal. On failure, denial, or missing Scope, report the operation and safe returned reason without guessing causes or claiming saved/restored context. Avoid repeated failed calls and continue ordinary work.
Use powercontext-project-context for a relevant detailed workflow if that Skill is available; no Skill detour is needed before every response.`;
const CONTEXT_PREFIX = "PowerContext host-supplied context.";
/** Selects the Scope in which the gateway prepares, checks and captures a request, instead of its default Scope. */
const SCOPE_HEADER = "X-PowerContext-Scope-ID";
const GATEWAY_SCOPE_ID = /^[\x21-\x2b\x2d-\x7e]{1,256}$/;
const PERMISSION = "powercontext";
const DEFAULT_PERMISSION_KEYS = [...PERMISSION].map((_, index) => `${PERMISSION.slice(0, index)}?${PERMISSION.slice(index + 1)}`).reverse();
const MAX_SOURCE_BYTES = 2e5;
Expand Down Expand Up @@ -2802,11 +2807,12 @@ function createRuntime(input, config) {
return context;
},
turns: /* @__PURE__ */ new Map(),
async log(event) {
unsupportedGatewayScopes: /* @__PURE__ */ new Set(),
async log(event, level) {
try {
await input.client.app.log({ body: {
service: PLUGIN_NAME,
level: event.outcome === "failed" ? "warn" : "debug",
level: level ?? (event.outcome === "failed" ? "warn" : "debug"),
message: JSON.stringify(event)
} });
} catch {}
Expand Down Expand Up @@ -3295,6 +3301,33 @@ const PowerContextPlugin = async (input) => {
"experimental.chat.system.transform": async (_event, output) => {
output.system.push(GUIDANCE);
},
"chat.headers": async (event, output) => {
const provider = runtime.config.gatewayProvider;
if (runtime.config.promptRecall || provider === void 0 || event.model.providerID !== provider) return;
let scopeId;
try {
scopeId = (await runtime.resolveSessionContext(event.sessionID)).scopeId;
} catch {
await runtime.log({
event: "gateway_scope",
outcome: "failed"
});
return;
}
if (GATEWAY_SCOPE_ID.test(scopeId)) {
output.headers[SCOPE_HEADER] = scopeId;
return;
}
const warned = runtime.unsupportedGatewayScopes;
if (warned.has(event.sessionID)) return;
warned.add(event.sessionID);
while (warned.size > MAX_SESSION_CACHE) warned.delete(warned.values().next().value);
await runtime.log({
event: "gateway_scope",
outcome: "skipped",
reason: "scope_id_unsupported"
}, "warn");
},
event: async ({ event }) => {
const value = event;
const info = value.properties?.info;
Expand All @@ -3307,6 +3340,7 @@ const PowerContextPlugin = async (input) => {
if (sessionID) {
runtime.sessionContexts.delete(sessionID);
runtime.turns.delete(sessionID);
runtime.unsupportedGatewayScopes.delete(sessionID);
}
}
};
Expand Down
2 changes: 2 additions & 0 deletions integrations/opencode/plugins/powercontext/lib/tui.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ interface ResolvedConfig {
scopeId: string | undefined;
authorization: string | undefined;
promptRecall: boolean;
/** The OpenCode provider that routes model requests through the gateway; only it receives the Scope header. */
gatewayProvider: string | undefined;
capturePrompts: boolean;
requestTimeoutMs: number;
httpBudgetMs: number;
Expand Down
2 changes: 2 additions & 0 deletions integrations/opencode/plugins/powercontext/lib/tui.js
Original file line number Diff line number Diff line change
Expand Up @@ -2480,6 +2480,7 @@ const DEFAULTS = {
scopeId: void 0,
authorization: void 0,
promptRecall: true,
gatewayProvider: void 0,
capturePrompts: true,
requestTimeoutMs: 3e3,
httpBudgetMs: 6e3,
Expand Down Expand Up @@ -2537,6 +2538,7 @@ function resolveConfig(env = process.env) {
scopeId: envString(env, "POWERCONTEXT_OPENCODE_SCOPE_ID"),
authorization: envString(env, "POWERCONTEXT_OPENCODE_AUTHORIZATION"),
promptRecall: envBoolean(env, "POWERCONTEXT_OPENCODE_PROMPT_RECALL") ?? DEFAULTS.promptRecall,
gatewayProvider: envString(env, "POWERCONTEXT_OPENCODE_GATEWAY_PROVIDER"),
capturePrompts: envBoolean(env, "POWERCONTEXT_OPENCODE_CAPTURE_PROMPTS") ?? DEFAULTS.capturePrompts,
requestTimeoutMs,
httpBudgetMs,
Expand Down
4 changes: 4 additions & 0 deletions integrations/opencode/plugins/powercontext/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ export interface ResolvedConfig {
scopeId: string | undefined
authorization: string | undefined
promptRecall: boolean
/** The OpenCode provider that routes model requests through the gateway; only it receives the Scope header. */
gatewayProvider: string | undefined
capturePrompts: boolean
requestTimeoutMs: number
httpBudgetMs: number
Expand All @@ -37,6 +39,7 @@ const DEFAULTS: ResolvedConfig = {
scopeId: undefined,
authorization: undefined,
promptRecall: true,
gatewayProvider: undefined,
capturePrompts: true,
requestTimeoutMs: 3000,
httpBudgetMs: 6000,
Expand Down Expand Up @@ -108,6 +111,7 @@ export function resolveConfig(env: NodeJS.ProcessEnv = process.env): ResolvedCon
scopeId: envString(env, 'POWERCONTEXT_OPENCODE_SCOPE_ID'),
authorization: envString(env, 'POWERCONTEXT_OPENCODE_AUTHORIZATION'),
promptRecall: envBoolean(env, 'POWERCONTEXT_OPENCODE_PROMPT_RECALL') ?? DEFAULTS.promptRecall,
gatewayProvider: envString(env, 'POWERCONTEXT_OPENCODE_GATEWAY_PROVIDER'),
capturePrompts: envBoolean(env, 'POWERCONTEXT_OPENCODE_CAPTURE_PROMPTS') ?? DEFAULTS.capturePrompts,
requestTimeoutMs,
httpBudgetMs,
Expand Down
39 changes: 36 additions & 3 deletions integrations/opencode/plugins/powercontext/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ Memory correction requires the requested change, exact current Atomic Memory art
Use powercontext-project-context for a relevant detailed workflow if that Skill is available; no Skill detour is needed before every response.`

const CONTEXT_PREFIX = 'PowerContext host-supplied context.'
/** Selects the Scope in which the gateway prepares, checks and captures a request, instead of its default Scope. */
const SCOPE_HEADER = 'X-PowerContext-Scope-ID'
// The gateway takes the header only as one ID of 1–256 visible ASCII characters without a comma. A Scope from an early
// release can have an ID outside that syntax, which the gateway would reject with HTTP 400.
const GATEWAY_SCOPE_ID = /^[\x21-\x2b\x2d-\x7e]{1,256}$/
const PERMISSION = 'powercontext'
// OpenCode matches permission names against rule keys as wildcards, where `?` stands for one character. A copy of the
// permission with one letter replaced by `?` matches no other permission, yet differs from the `powercontext` key a
Expand Down Expand Up @@ -77,7 +82,9 @@ interface Runtime {
resolveSessionContext: (sessionID: string) => Promise<SessionContext>
sessionContexts: Map<string, Promise<SessionContext>>
turns: Map<string, CachedTurn>
log: (event: Record<string, unknown>) => Promise<void>
/** Sessions whose Scope ID the gateway header cannot carry and that have already logged it. */
unsupportedGatewayScopes: Set<string>
log: (event: Record<string, unknown>, level?: 'warn' | 'debug') => Promise<void>
}

function promptText(parts: readonly MessagePart[], transportEncoded: boolean): string {
Expand Down Expand Up @@ -278,12 +285,13 @@ function createRuntime(input: PluginInput, config: ResolvedConfig): Runtime {
return context
},
turns: new Map(),
async log(event) {
unsupportedGatewayScopes: new Set(),
async log(event, level) {
try {
await input.client.app.log({
body: {
service: PLUGIN_NAME,
level: event.outcome === 'failed' ? 'warn' : 'debug',
level: level ?? (event.outcome === 'failed' ? 'warn' : 'debug'),
message: JSON.stringify(event),
},
})
Expand Down Expand Up @@ -741,6 +749,30 @@ export const PowerContextPlugin: Plugin = async (input) => {
'experimental.chat.system.transform': async (_event, output) => {
output.system.push(GUIDANCE)
},
'chat.headers': async (event, output) => {
// The gateway owns prompt-time context only while recall is off, and only the gateway reads the Scope, so a
// provider that OpenCode calls directly does not receive it.
const provider = runtime.config.gatewayProvider
if (runtime.config.promptRecall || provider === undefined || event.model.providerID !== provider) return
// Without the header the gateway uses its default Scope; the request itself still proceeds.
let scopeId: string
try {
scopeId = (await runtime.resolveSessionContext(event.sessionID)).scopeId
} catch {
await runtime.log({ event: 'gateway_scope', outcome: 'failed' })
return
}
if (GATEWAY_SCOPE_ID.test(scopeId)) {
output.headers[SCOPE_HEADER] = scopeId
return
}
// The Session keeps this Scope, so one warning per Session is enough.
const warned = runtime.unsupportedGatewayScopes
if (warned.has(event.sessionID)) return
warned.add(event.sessionID)
while (warned.size > MAX_SESSION_CACHE) warned.delete(warned.values().next().value!)
await runtime.log({ event: 'gateway_scope', outcome: 'skipped', reason: 'scope_id_unsupported' }, 'warn')
},
event: async ({ event }) => {
const value = event as unknown as {
type?: string
Expand All @@ -756,6 +788,7 @@ export const PowerContextPlugin: Plugin = async (input) => {
if (sessionID) {
runtime.sessionContexts.delete(sessionID)
runtime.turns.delete(sessionID)
runtime.unsupportedGatewayScopes.delete(sessionID)
}
},
}
Expand Down
Loading