From 504179c2cbb974fe8e7379e2d5f4ed38197ba301 Mon Sep 17 00:00:00 2001 From: Fengzdadi <453788063@qq.com> Date: Mon, 30 Nov 2026 20:08:09 -0500 Subject: [PATCH 1/3] feat(dsh): send the prompt's Scope to the gateway provider --- docs/en/docs/integrations/dsh.md | 52 +++++--- docs/zh/docs/integrations/dsh.md | 31 ++++- .../dsh/plugins/powercontext/README.md | 9 +- .../dsh/plugins/powercontext/lib/index.d.ts | 2 + .../dsh/plugins/powercontext/lib/index.js | 42 +++++- .../dsh/plugins/powercontext/src/config.ts | 8 ++ .../dsh/plugins/powercontext/src/index.ts | 52 +++++++- .../powercontext/tests/automatic-path.spec.ts | 121 +++++++++++++++++- 8 files changed, 281 insertions(+), 36 deletions(-) diff --git a/docs/en/docs/integrations/dsh.md b/docs/en/docs/integrations/dsh.md index df36931830..67c9cfb485 100644 --- a/docs/en/docs/integrations/dsh.md +++ b/docs/en/docs/integrations/dsh.md @@ -689,23 +689,24 @@ terminal stream and captures the completed turn. ### Turn the plugin's prompt recall and capture off -Turn the plugin's prompt-time recall and prompt capture off before starting DSH: +Turn the plugin's prompt-time recall and prompt capture off, and name the gateway provider, before starting DSH: ```bash export POWERCONTEXT_DSH_PROMPT_RECALL=false export POWERCONTEXT_DSH_CAPTURE_PROMPTS=false +export POWERCONTEXT_DSH_GATEWAY_PROVIDER=powercontext-gateway dsh web ``` -The plugin patch settings `promptRecall` and `capturePrompts` do the same. With recall off, the plugin sends no -preparation request and adds no message to the step. The gateway takes the latest user message that is not a -standalone host reminder as the turn's message, so any other message added after the prompt would replace the prompt -as the gateway's recall query and captured user text. The plugin therefore adds the Scope routing to DSH's runtime -context instead, which DSH sends as a `` user message after the step's messages. DSH sends the runtime -context on a session's first request and again only when any part of it changes, such as the Scope, the approval -policy, or a compaction that replaced it, so a later prompt stays the last user message while the context is -unchanged. The plugin does not provide the [companion memory service](#read-only-companion-memory-service) either, -because that service returns a prepared-context block. +The plugin patch settings `promptRecall`, `capturePrompts`, and `gatewayProvider` do the same. With recall off, the +plugin sends no preparation request and adds no message to the step. The gateway takes the latest user message that is +not a standalone host reminder as the turn's message, so any other message added after the prompt would replace the +prompt as the gateway's recall query and captured user text. The plugin therefore adds the Scope routing to DSH's +runtime context instead, which DSH sends as a `` user message after the step's messages. DSH sends the +runtime context on a session's first request and again only when any part of it changes, such as the Scope, the approval +policy, or a compaction that replaced it, so a later prompt stays the last user message while the context is unchanged. +The plugin does not provide the [companion memory service](#read-only-companion-memory-service) either, because that +service returns a prepared-context block. The plugin still resolves the Scope for each prompt and still captures prompts while `POWERCONTEXT_DSH_CAPTURE_PROMPTS` is `true`; with both off, it sends only Scope resolution for a prompt. The MCP @@ -732,6 +733,19 @@ DSH sends these headers to whichever provider serves the request, including one not forward them upstream. DSH's Responses requests already carry the session ID as `prompt_cache_key` unless the provider sets `cacheRetention: "none"`. +`POWERCONTEXT_DSH_GATEWAY_PROVIDER` names the `llm-pi-ai` provider that points at the gateway, by its key under +`providers`. While recall is off, the plugin sends the Scope it resolves for the session's workspace, the one `/pc` +prints, as `X-PowerContext-Scope-ID` on every request to that provider, compaction, session-title, and auto-review +requests included. The gateway then prepares and captures turns in that Scope instead of `PC_GATEWAY_DEFAULT_SCOPE`, +and Core checks each request in it. Requests to any other provider carry no Scope header. The plugin resolves the +Scope once per prompt, so a changed binding applies from the next prompt. The request carries no Scope header, and +the gateway uses `PC_GATEWAY_DEFAULT_SCOPE`, when the variable is unset, when the session's latest prompt resolved no +Scope, or when the header cannot carry the Scope's ID, which can happen with a Scope from an early release. In the +last two cases the plugin logs one `gateway_scope` diagnostic for that prompt, with `reason: scope_unresolved` or +`reason: scope_id_unsupported`. For a Scope whose ID the header cannot carry, the plugin's own prompt capture and MCP +tools still use that Scope. See [Gateway request Scope](../operate/deploy-server.md#gateway-request-scope) for the IDs +the header can carry. + Restart DSH after changing these settings, then start a new session. A session in which the plugin recalled context keeps that context in its history, and DSH resends it with later requests, so Core rejects them. The gateway removes a plugin block only from a tool result, and on the Responses route also from a developer message; the plugin's @@ -748,16 +762,19 @@ default. Set: - When Core enforces authentication, `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 `scope.contributor` (which includes `scope.read`) on `PC_GATEWAY_DEFAULT_SCOPE` and on every Scope that requests - select with `X-PowerContext-Scope-ID`. Because the gateway captures turns, use `scope.contributor` rather than - `scope.viewer`. See + select with `X-PowerContext-Scope-ID`. With `POWERCONTEXT_DSH_GATEWAY_PROVIDER` set, those are the workspace Scopes + that the plugin sends. Because the gateway captures turns, use `scope.contributor` rather than `scope.viewer`. See [Gateway authentication boundaries](../operate/deploy-server.md#gateway-authentication-boundaries). - `PC_GATEWAY_SEDIMENT=on`, so that the gateway captures each completed turn as a Source. -- `PC_GATEWAY_DEFAULT_SCOPE` to the Scope this plugin resolves for the workspace, which `/pc` prints. +- `PC_GATEWAY_DEFAULT_SCOPE` to the Scope for requests that carry no Scope header. With + `POWERCONTEXT_DSH_GATEWAY_PROVIDER` unset, set it to the Scope this plugin resolves for the workspace, which `/pc` + prints. -The plugin does not send `X-PowerContext-Scope-ID`, so the gateway prepares and captures every conversation in the one -Scope set by `PC_GATEWAY_DEFAULT_SCOPE`, not in the Scope this plugin resolves for each workspace. For the gateway's -authentication settings and request size limit, see -[Deploy the Server](../operate/deploy-server.md#gateway-authentication-boundaries). +The gateway key does not limit which Scope a request selects: any client that can call the gateway can select any +Scope that the gateway's Core credential can access; see +[Gateway request Scope](../operate/deploy-server.md#gateway-request-scope). When Core enforces authentication, grant +these roles on a new workspace's Scope before DSH works there. For the gateway's authentication settings and request +size limit, see [Deploy the Server](../operate/deploy-server.md#gateway-authentication-boundaries). ## Connect to an authenticated local Server @@ -794,6 +811,7 @@ powercontext doctor dsh | `POWERCONTEXT_DSH_SCOPE_ID` | unset | Explicit existing Scope before workspace binding and Server default | | `POWERCONTEXT_DSH_AUTHORIZATION` | unset | Complete `Bearer ` header for MCP and lifecycle HTTP requests | | `POWERCONTEXT_DSH_PROMPT_RECALL` | `true` | Prepare and add context before each model step and provide the companion memory service; `false` leaves prompt-time context to the gateway and sends the gateway conversation and internal-turn headers | +| `POWERCONTEXT_DSH_GATEWAY_PROVIDER` | unset | `llm-pi-ai` provider that routes through the gateway; while prompt recall is off, only its requests carry the session's Scope as `X-PowerContext-Scope-ID` | | `POWERCONTEXT_DSH_CAPTURE_PROMPTS` | `true` | Capture user prompts as Source evidence | | `POWERCONTEXT_DSH_FLUSH_ON_CAPTURE` | `false` | Wait for Source processing after capture | diff --git a/docs/zh/docs/integrations/dsh.md b/docs/zh/docs/integrations/dsh.md index f37781a221..9165bc666a 100644 --- a/docs/zh/docs/integrations/dsh.md +++ b/docs/zh/docs/integrations/dsh.md @@ -591,15 +591,16 @@ enforcing 模式的 Core 会扣留流式响应,gateway 返回 HTTP 400。 ### 关闭插件的提示词召回和采集 -启动 DSH 前,关闭插件的提示词时召回和提示词采集: +启动 DSH 前,关闭插件的提示词时召回和提示词采集,并指定 gateway provider: ```bash export POWERCONTEXT_DSH_PROMPT_RECALL=false export POWERCONTEXT_DSH_CAPTURE_PROMPTS=false +export POWERCONTEXT_DSH_GATEWAY_PROVIDER=powercontext-gateway dsh web ``` -插件 patch 配置 `promptRecall` 和 `capturePrompts` 的作用相同。关闭召回后,插件不发送准备请求, +插件 patch 配置 `promptRecall`、`capturePrompts` 和 `gatewayProvider` 的作用相同。关闭召回后,插件不发送准备请求, 也不向这一步添加任何消息。gateway 把最近一条不是独立宿主提醒的用户消息当作这一轮的消息, 因此加在提示词之后的其他消息,都会取代提示词成为 gateway 的召回查询和采集的用户文本。 所以插件把 Scope 路由加到 DSH 的运行时上下文中,DSH 会把它作为 `` 用户消息, @@ -628,6 +629,19 @@ gateway 仍会让 Core 检查这类请求,但不为它准备或注入上下文 DSH 会把这些请求头发给处理该请求的任何 provider,包括它直接调用的 provider;gateway 不会把它们转发给上游。 除非 provider 设置了 `cacheRetention: "none"`,DSH 的 Responses 请求本来就以 `prompt_cache_key` 携带会话 ID。 +`POWERCONTEXT_DSH_GATEWAY_PROVIDER` 以 `providers` 下的键指定指向 gateway 的 `llm-pi-ai` provider。 +关闭召回后,插件会把它为会话 workspace 解析的 Scope(即 `/pc` 打印的 Scope)作为 `X-PowerContext-Scope-ID`, +发送到这个 provider 的每个请求上,压缩、会话标题和 auto review 请求也包括在内。 +gateway 随后在这个 Scope 而不是 `PC_GATEWAY_DEFAULT_SCOPE` 中准备和采集各轮,Core 也在这个 Scope 中检查每个请求。 +发给其他 provider 的请求不带 Scope 请求头。插件每条提示词解析一次 Scope,因此 binding 改变后,从下一条提示词起生效。 +未设置这个变量、会话最近一条提示词没有解析出 Scope, +或请求头无法携带该 Scope 的 ID(早期版本的 Scope 可能如此)时, +请求不带 Scope 请求头,gateway 使用 `PC_GATEWAY_DEFAULT_SCOPE`。 +在后两种情况下,插件为这条提示词记录一条 `gateway_scope` 诊断, +`reason` 为 `scope_unresolved` 或 `scope_id_unsupported`。 +对于请求头无法携带其 ID 的 Scope,插件自己的提示词采集和 MCP 工具仍使用该 Scope。 +请求头能携带哪些 ID,见[Gateway 请求 Scope](../operate/deploy-server.md#gateway-请求-scope)。 + 修改这些设置后请重启 DSH,然后新建会话。插件召回过上下文的会话会在历史中保留这些上下文, DSH 之后的请求会再次发送它们,因此 Core 会拒绝这些请求。gateway 只从工具结果中移除插件块, 在 Responses 路由上还会从 developer 消息中移除;插件的快照是用户消息。 @@ -642,15 +656,17 @@ DSH 之后的请求会再次发送它们,因此 Core 会拒绝这些请求。g - Core 启用鉴权时,把 `PC_GATEWAY_CORE_TOKEN` 设为经过认证的服务身份。 请在 `POWERCONTEXT_SERVER_ACCESS_DEPLOYMENT_ID`(默认 `powercontext`)对应的 Server 资源上授予它 `server.observer`, 并在 `PC_GATEWAY_DEFAULT_SCOPE` 以及每个通过 `X-PowerContext-Scope-ID` 选择的 Scope 上授予 `scope.contributor`(包含 `scope.read`)。 + 设置 `POWERCONTEXT_DSH_GATEWAY_PROVIDER` 后,这些 Scope 就是插件发送的各个 workspace Scope。 gateway 会采集各轮,因此请使用 `scope.contributor` 而不是 `scope.viewer`。 见[网关认证边界](../operate/deploy-server.md#网关认证边界)。 - `PC_GATEWAY_SEDIMENT=on`,让 gateway 把每个完成的轮次采集为 Source。 -- `PC_GATEWAY_DEFAULT_SCOPE` 设为插件为该 workspace 解析的 Scope,`/pc` 会打印这个 Scope。 +- `PC_GATEWAY_DEFAULT_SCOPE` 设为不带 Scope 请求头的请求所用的 Scope。 + 未设置 `POWERCONTEXT_DSH_GATEWAY_PROVIDER` 时,把它设为插件为该 workspace 解析的 Scope,`/pc` 会打印这个 Scope。 -插件不发送 `X-PowerContext-Scope-ID`, -因此 gateway 把所有会话都放在 `PC_GATEWAY_DEFAULT_SCOPE` 指定的同一个 Scope 中准备和采集, -而不是插件为每个 workspace 解析的 Scope。gateway 的鉴权设置和请求大小上限, -见[部署 Server](../operate/deploy-server.md#网关认证边界)。 +gateway 密钥不限制请求选择哪个 Scope:任何能调用 gateway 的客户端, +都能选择 gateway 的 Core 凭据可访问的任何 Scope。见[Gateway 请求 Scope](../operate/deploy-server.md#gateway-请求-scope)。 +Core 启用鉴权时,DSH 在新的 workspace 中工作之前,请先在它的 Scope 上授予这些角色。 +gateway 的鉴权设置和请求大小上限,见[部署 Server](../operate/deploy-server.md#网关认证边界)。 ## 连接启用鉴权的本地 Server @@ -687,6 +703,7 @@ powercontext doctor dsh | `POWERCONTEXT_DSH_SCOPE_ID` | 未设置 | 在 workspace binding 和 Server 默认值之前显式选择已有 Scope | | `POWERCONTEXT_DSH_AUTHORIZATION` | 未设置 | MCP 与生命周期 HTTP 请求使用的完整 `Bearer ` header | | `POWERCONTEXT_DSH_PROMPT_RECALL` | `true` | 每次模型调用前准备并添加上下文,并提供桌宠记忆服务;`false` 把提示词时上下文交给 gateway,并发送 gateway 会话请求头和 internal 轮次请求头 | +| `POWERCONTEXT_DSH_GATEWAY_PROVIDER` | 未设置 | 经由 gateway 的 `llm-pi-ai` provider;关闭提示词召回时,只有它的请求以 `X-PowerContext-Scope-ID` 携带会话的 Scope | | `POWERCONTEXT_DSH_CAPTURE_PROMPTS` | `true` | 把用户提示词采集为 Source 证据 | | `POWERCONTEXT_DSH_FLUSH_ON_CAPTURE` | `false` | 采集后等待 Source 处理 | diff --git a/integrations/dsh/plugins/powercontext/README.md b/integrations/dsh/plugins/powercontext/README.md index 63ba3f93ee..ba48189070 100644 --- a/integrations/dsh/plugins/powercontext/README.md +++ b/integrations/dsh/plugins/powercontext/README.md @@ -129,9 +129,12 @@ make js-api-generate-check ``` The plugin resolves an explicit Scope, a durable workspace binding, or the Server default. Environment overrides use -the `POWERCONTEXT_DSH_` prefix for `BASE_URL`, `AUTHORIZATION`, `SCOPE_ID`, `PROMPT_RECALL`, `CAPTURE_PROMPTS`, and -`FLUSH_ON_CAPTURE`. Set `POWERCONTEXT_DSH_PROMPT_RECALL=false` when DeepSeek Harness reaches its model through the -PowerContext gateway, which then prepares context for each turn. +the `POWERCONTEXT_DSH_` prefix for `BASE_URL`, `AUTHORIZATION`, `SCOPE_ID`, `PROMPT_RECALL`, `GATEWAY_PROVIDER`, +`CAPTURE_PROMPTS`, and `FLUSH_ON_CAPTURE`. Set `POWERCONTEXT_DSH_PROMPT_RECALL=false` when DeepSeek Harness reaches its +model through the PowerContext gateway, which then prepares context for each turn, and set +`POWERCONTEXT_DSH_GATEWAY_PROVIDER` to the gateway's `llm-pi-ai` provider so that the gateway works in the workspace's +Scope. A Scope whose ID the gateway's Scope header cannot carry, which can happen with a Scope from an early release, +is not sent; the gateway then uses its default Scope, and the plugin logs a `gateway_scope` diagnostic. `timeoutMs`, `requestTimeoutMs`, `maxBytes`, `flushMaxCalls`, and `ownerLocal` are plugin patch settings. Context returned by recall is labelled as untrusted history. An unavailable Server never blocks normal Harness work. diff --git a/integrations/dsh/plugins/powercontext/lib/index.d.ts b/integrations/dsh/plugins/powercontext/lib/index.d.ts index 489b623de2..0fc6068eda 100644 --- a/integrations/dsh/plugins/powercontext/lib/index.d.ts +++ b/integrations/dsh/plugins/powercontext/lib/index.d.ts @@ -28,6 +28,8 @@ interface PluginConfig { maxBytes?: number; /** Prepare and inject context before each model step; turn off when a gateway does this. */ promptRecall?: boolean; + /** The `llm-pi-ai` provider that routes model requests through the gateway; only it receives the Scope header. */ + gatewayProvider?: string; capturePrompts?: boolean; flushOnCapture?: boolean; flushMaxCalls?: number; diff --git a/integrations/dsh/plugins/powercontext/lib/index.js b/integrations/dsh/plugins/powercontext/lib/index.js index 6927129b09..0db2d8fbe0 100644 --- a/integrations/dsh/plugins/powercontext/lib/index.js +++ b/integrations/dsh/plugins/powercontext/lib/index.js @@ -3853,6 +3853,7 @@ function resolveConfig(config = {}, env = process.env) { const transport = resolveTransport("dsh", env, config.baseUrl, config.allowInsecureHttp, DEFAULTS.baseUrl); if (config.updateChannel !== void 0 && config.updateChannel !== "stable" && config.updateChannel !== "preview") throw new Error("updateChannel must be stable or preview"); if (config.updateHold !== void 0 && typeof config.updateHold !== "boolean") throw new Error("updateHold must be a boolean"); + if (config.gatewayProvider !== void 0 && typeof config.gatewayProvider !== "string") throw new Error("gatewayProvider must be a string"); const maxBytes = config.maxBytes ?? DEFAULTS.maxBytes; if (maxBytes < 512 || maxBytes > 32768) throw new Error("maxBytes must be between 512 and 32768"); return { @@ -3870,6 +3871,7 @@ function resolveConfig(config = {}, env = process.env) { requestTimeoutMs: config.requestTimeoutMs ?? DEFAULTS.requestTimeoutMs, maxBytes, promptRecall: envBoolean(env, "POWERCONTEXT_DSH_PROMPT_RECALL") ?? config.promptRecall ?? DEFAULTS.promptRecall, + gatewayProvider: envString(env, "POWERCONTEXT_DSH_GATEWAY_PROVIDER") ?? optionalText(config.gatewayProvider), capturePrompts: envBoolean(env, "POWERCONTEXT_DSH_CAPTURE_PROMPTS") ?? config.capturePrompts ?? DEFAULTS.capturePrompts, flushOnCapture: envBoolean(env, "POWERCONTEXT_DSH_FLUSH_ON_CAPTURE") ?? config.flushOnCapture ?? DEFAULTS.flushOnCapture, flushMaxCalls: config.flushMaxCalls ?? DEFAULTS.flushMaxCalls, @@ -5782,11 +5784,13 @@ function createRuntime(ctx, config) { } function createSessionScopeResolver(runtime) { const cache = /* @__PURE__ */ new Map(); + const attempts = /* @__PURE__ */ new Map(); const keyFor = (sessionId, cwd) => sessionId ? `session:${sessionId}` : `cwd:${cwd ?? ""}`; const resolve$1 = async (request$2, refresh) => { const key$1 = keyFor(request$2.sessionId, request$2.cwd); const cached = cache.get(key$1); if (!refresh && cached && cached.cwd === request$2.cwd) return cached.scopeId; + if (refresh) attempts.set(key$1, (attempts.get(key$1) ?? 0) + 1); cache.delete(key$1); const scopeId = await runtime.resolveScope(request$2.cwd, request$2.signal); if (scopeId) cache.set(key$1, { @@ -5798,6 +5802,17 @@ function createSessionScopeResolver(runtime) { return { forPreStep: (request$2) => resolve$1(request$2, true), forTool: (request$2) => resolve$1(request$2, false), + forGateway: (sessionId) => { + if (!sessionId) return { + scopeId: void 0, + attempt: 0 + }; + const key$1 = keyFor(sessionId, void 0); + return { + scopeId: cache.get(key$1)?.scopeId, + attempt: attempts.get(key$1) ?? 0 + }; + }, current: (sessionId, cwd) => { const cached = cache.get(keyFor(sessionId, cwd)); return cached && cached.cwd === cwd ? cached.scopeId : void 0; @@ -5880,15 +5895,36 @@ const CONVERSATION_HEADER = "X-PowerContext-Conversation-ID"; const CONVERSATION_ID = /^[\x21-\x7e]{1,256}$/; /** With the value `internal`, the gateway neither prepares, injects nor captures the request as a turn. */ const TURN_HEADER = "X-PowerContext-Turn"; +/** 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}$/; /** * Name the gateway conversation on each model request of a session's agent loop. DSH marks its other model * requests, such as compaction, session titles and auto review, with a `purpose`; they are not turns of the -* conversation, so they are marked internal instead. The hook is synchronous and must not throw. +* conversation, so they are marked internal instead. Requests to the configured gateway provider, internal ones +* included, also carry the Scope that the session's latest prompt resolved, when the gateway accepts its ID. The hook +* is synchronous and must not throw. */ -function registerGatewayHeaders(ctx) { +function registerGatewayHeaders(ctx, runtime, sessionScope) { + const reported = /* @__PURE__ */ new Map(); ctx.on("llm-pi-ai/request-headers", ((request$2, _headers, next) => { const result = next(); const conversation = request$2.sessionId; + const provider = runtime.config.gatewayProvider; + if (provider !== void 0 && request$2.provider === provider) { + const sessionId = typeof conversation === "string" ? conversation : ""; + const resolved = sessionScope(sessionId); + if (resolved.scopeId !== void 0 && GATEWAY_SCOPE_ID.test(resolved.scopeId)) result.set(SCOPE_HEADER, resolved.scopeId); + else if (reported.get(sessionId) !== resolved.attempt) { + reported.set(sessionId, resolved.attempt); + const reason = resolved.scopeId === void 0 ? "scope_unresolved" : "scope_id_unsupported"; + logSafely(runtime.log, { + event: "gateway_scope", + outcome: "skipped", + reason + }); + } + } if (request$2.purpose !== void 0) result.set(TURN_HEADER, "internal"); else if (typeof conversation === "string" && CONVERSATION_ID.test(conversation)) result.set(CONVERSATION_HEADER, conversation); return result; @@ -5919,7 +5955,7 @@ async function apply(ctx, config) { registerGuidance(ctx); registerRecall(ctx, runtime, llmMod.createUserMessage, sessionScope.forPreStep); if (!runtime.config.promptRecall) { - registerGatewayHeaders(ctx); + registerGatewayHeaders(ctx, runtime, sessionScope.forGateway); registerScopeRoutingContext(ctx, sessionScope.current); } registerCommands(ctx, runtime); diff --git a/integrations/dsh/plugins/powercontext/src/config.ts b/integrations/dsh/plugins/powercontext/src/config.ts index ff78f70a22..3b07738a12 100644 --- a/integrations/dsh/plugins/powercontext/src/config.ts +++ b/integrations/dsh/plugins/powercontext/src/config.ts @@ -30,6 +30,8 @@ export interface PluginConfig { maxBytes?: number /** Prepare and inject context before each model step; turn off when a gateway does this. */ promptRecall?: boolean + /** The `llm-pi-ai` provider that routes model requests through the gateway; only it receives the Scope header. */ + gatewayProvider?: string capturePrompts?: boolean flushOnCapture?: boolean flushMaxCalls?: number @@ -50,6 +52,8 @@ export interface ResolvedConfig { requestTimeoutMs: number maxBytes: number promptRecall: boolean + /** The `llm-pi-ai` provider that routes model requests through the gateway; only it receives the Scope header. */ + gatewayProvider?: string capturePrompts: boolean flushOnCapture: boolean flushMaxCalls: number @@ -147,6 +151,9 @@ export function resolveConfig( if (config.updateHold !== undefined && typeof config.updateHold !== 'boolean') { throw new Error('updateHold must be a boolean') } + if (config.gatewayProvider !== undefined && typeof config.gatewayProvider !== 'string') { + throw new Error('gatewayProvider must be a string') + } const maxBytes = config.maxBytes ?? DEFAULTS.maxBytes if (maxBytes < 512 || maxBytes > 32768) { throw new Error('maxBytes must be between 512 and 32768') @@ -169,6 +176,7 @@ export function resolveConfig( requestTimeoutMs: config.requestTimeoutMs ?? DEFAULTS.requestTimeoutMs, maxBytes, promptRecall: envBoolean(env, 'POWERCONTEXT_DSH_PROMPT_RECALL') ?? config.promptRecall ?? DEFAULTS.promptRecall, + gatewayProvider: envString(env, 'POWERCONTEXT_DSH_GATEWAY_PROVIDER') ?? optionalText(config.gatewayProvider), capturePrompts: envBoolean(env, 'POWERCONTEXT_DSH_CAPTURE_PROMPTS') ?? config.capturePrompts ?? DEFAULTS.capturePrompts, flushOnCapture: envBoolean(env, 'POWERCONTEXT_DSH_FLUSH_ON_CAPTURE') ?? config.flushOnCapture ?? DEFAULTS.flushOnCapture, flushMaxCalls: config.flushMaxCalls ?? DEFAULTS.flushMaxCalls, diff --git a/integrations/dsh/plugins/powercontext/src/index.ts b/integrations/dsh/plugins/powercontext/src/index.ts index 8866b84bfd..fb5a518d32 100644 --- a/integrations/dsh/plugins/powercontext/src/index.ts +++ b/integrations/dsh/plugins/powercontext/src/index.ts @@ -20,7 +20,7 @@ import { fileURLToPath } from 'node:url' import { PowerContextClient } from './client.ts' import { registerCommands } from './commands.ts' import { resolveConfig, type PluginConfig } from './config.ts' -import { createDiagnosticEmitter } from './diagnostics.ts' +import { createDiagnosticEmitter, logSafely } from './diagnostics.ts' import { PLUGIN_NAME } from './errors.ts' import type { PluginRuntime } from './invoke.ts' import { registerMcp, registerMcpPolicy, type McpScopeResolutionRequest } from './mcp.ts' @@ -91,12 +91,21 @@ function createRuntime(ctx: Context, config: PluginConfig): PluginRuntime { type SessionScopeResolver = (request: McpScopeResolutionRequest) => Promise +/** The Scope a session's latest prompt resolved, and which resolution produced it. */ +interface ResolvedSessionScope { + scopeId: string | undefined + attempt: number +} + function createSessionScopeResolver(runtime: PluginRuntime): { forPreStep: SessionScopeResolver forTool: SessionScopeResolver current: (sessionId: string, cwd: string | undefined) => string | undefined + forGateway: (sessionId: string) => ResolvedSessionScope } { const cache = new Map() + // Counts each prompt's resolution, so a missing Scope is reported once per prompt, not once per request. + const attempts = new Map() const keyFor = (sessionId: string | undefined, cwd: string | undefined) => ( sessionId ? `session:${sessionId}` : `cwd:${cwd ?? ''}` ) @@ -104,6 +113,7 @@ function createSessionScopeResolver(runtime: PluginRuntime): { const key = keyFor(request.sessionId, request.cwd) const cached = cache.get(key) if (!refresh && cached && cached.cwd === request.cwd) return cached.scopeId + if (refresh) attempts.set(key, (attempts.get(key) ?? 0) + 1) // A failed refresh must not leave a previous turn's Scope available to MCP calls. cache.delete(key) const scopeId = await runtime.resolveScope(request.cwd, request.signal) @@ -113,6 +123,12 @@ function createSessionScopeResolver(runtime: PluginRuntime): { return { forPreStep: request => resolve(request, true), forTool: request => resolve(request, false), + forGateway: (sessionId) => { + // A request without a session ID cannot be matched to a prompt's resolution. + if (!sessionId) return { scopeId: undefined, attempt: 0 } + const key = keyFor(sessionId, undefined) + return { scopeId: cache.get(key)?.scopeId, attempt: attempts.get(key) ?? 0 } + }, // Reads what the session's latest resolution left, without contacting the Server. current: (sessionId, cwd) => { const cached = cache.get(keyFor(sessionId, cwd)) @@ -210,20 +226,46 @@ const CONVERSATION_HEADER = 'X-PowerContext-Conversation-ID' const CONVERSATION_ID = /^[\x21-\x7e]{1,256}$/ /** With the value `internal`, the gateway neither prepares, injects nor captures the request as a turn. */ const TURN_HEADER = 'X-PowerContext-Turn' +/** 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 accepts one ID of 1-256 visible ASCII characters other than `,`. Scopes from early releases can have +// IDs outside this syntax; sending one would fail the request, and `Headers.set` throws on non-Latin-1 text. +const GATEWAY_SCOPE_ID = /^[\x21-\x2b\x2d-\x7e]{1,256}$/ /** * Name the gateway conversation on each model request of a session's agent loop. DSH marks its other model * requests, such as compaction, session titles and auto review, with a `purpose`; they are not turns of the - * conversation, so they are marked internal instead. The hook is synchronous and must not throw. + * conversation, so they are marked internal instead. Requests to the configured gateway provider, internal ones + * included, also carry the Scope that the session's latest prompt resolved, when the gateway accepts its ID. The hook + * is synchronous and must not throw. */ -function registerGatewayHeaders(ctx: Context): void { +function registerGatewayHeaders( + ctx: Context, + runtime: PluginRuntime, + sessionScope: (sessionId: string) => ResolvedSessionScope, +): void { + const reported = new Map() ctx.on('llm-pi-ai/request-headers', (( - request: { sessionId?: unknown; purpose?: unknown }, + request: { provider?: unknown; sessionId?: unknown; purpose?: unknown }, _headers: Headers, next: () => Headers, ) => { const result = next() const conversation = request.sessionId + // Only the gateway reads the Scope, so a provider that DSH calls directly does not receive it. + const provider = runtime.config.gatewayProvider + if (provider !== undefined && request.provider === provider) { + const sessionId = typeof conversation === 'string' ? conversation : '' + const resolved = sessionScope(sessionId) + if (resolved.scopeId !== undefined && GATEWAY_SCOPE_ID.test(resolved.scopeId)) { + result.set(SCOPE_HEADER, resolved.scopeId) + } else if (reported.get(sessionId) !== resolved.attempt) { + // Without the header the gateway uses its default Scope; the request itself still proceeds. + reported.set(sessionId, resolved.attempt) + const reason = resolved.scopeId === undefined ? 'scope_unresolved' : 'scope_id_unsupported' + logSafely(runtime.log, { event: 'gateway_scope', outcome: 'skipped', reason }) + } + } if (request.purpose !== undefined) { result.set(TURN_HEADER, 'internal') } else if (typeof conversation === 'string' && CONVERSATION_ID.test(conversation)) { @@ -259,7 +301,7 @@ export async function apply(ctx: Context, config: Config): Promise { // provider that DSH calls directly while recall is on does not receive them, and only then does the Scope // routing move from the step's messages to the runtime context. if (!runtime.config.promptRecall) { - registerGatewayHeaders(ctx) + registerGatewayHeaders(ctx, runtime, sessionScope.forGateway) registerScopeRoutingContext(ctx, sessionScope.current) } registerCommands(ctx, runtime) diff --git a/integrations/dsh/plugins/powercontext/tests/automatic-path.spec.ts b/integrations/dsh/plugins/powercontext/tests/automatic-path.spec.ts index 02f2c5631a..ad30954ab3 100644 --- a/integrations/dsh/plugins/powercontext/tests/automatic-path.spec.ts +++ b/integrations/dsh/plugins/powercontext/tests/automatic-path.spec.ts @@ -17,7 +17,7 @@ import type { Context } from '@deepseek-ai/cordis' import { existsSync } from 'node:fs' import { afterEach, describe, expect, it, vi } from 'vitest' -import { apply, COMPANION_MEMORY_SERVICE } from '../src/index.ts' +import { apply, COMPANION_MEMORY_SERVICE, Config } from '../src/index.ts' import type { PluginConfig } from '../src/config.ts' import type { PreStepDecision, PromptMessage } from '../src/recall.ts' import { formatScopeRouting } from '../src/scope.ts' @@ -590,6 +590,125 @@ describe('registered automatic path', () => { } }) + describe('gateway Scope header', () => { + const GATEWAY = 'powercontext-gateway' + const route = { provider: GATEWAY, model: 'approved-model', baseURL: 'http://127.0.0.1:8787/gateway/v1' } + const gatewayDiagnostics = (h: Awaited>) => ( + h.diagnostics().filter(({ event }) => event === 'gateway_scope') + ) + + it.each([ + ['plugin config', { gatewayProvider: GATEWAY }, {}], + ['environment', { gatewayProvider: 'other-provider' }, { POWERCONTEXT_DSH_GATEWAY_PROVIDER: GATEWAY }], + ] as const)('sends the prompt\'s Scope only to the gateway provider named through %s', async (_, config, env) => { + for (const [name, value] of Object.entries(env)) vi.stubEnv(name, value) + const h = await fixture(successfulRequest, { promptRecall: false, ...config }) + await h.run() + expect(h.providerHeaders!({ ...route, sessionId: 'test-session' })).toEqual({ + 'x-route': 'configured', + 'x-powercontext-conversation-id': 'test-session', + 'x-powercontext-scope-id': 'scope-test', + }) + // Internal requests are checked by Core in the same Scope as the session's turns. + for (const purpose of ['compaction', 'session-title', 'auto-review']) { + expect(h.providerHeaders!({ ...route, sessionId: 'test-session', purpose })).toEqual({ + 'x-route': 'configured', 'x-powercontext-turn': 'internal', 'x-powercontext-scope-id': 'scope-test', + }) + } + expect(h.providerHeaders!({ ...route, provider: 'direct-provider', sessionId: 'test-session' })).toEqual({ + 'x-route': 'configured', 'x-powercontext-conversation-id': 'test-session', + }) + // Every request of a prompt reuses the prompt's resolution. + expect(h.requests.map(({ path }) => path)).toEqual([SCOPE, CAPTURE]) + expect(h.diagnostics()).toEqual([]) + }) + + it('sends no Scope header without a named gateway provider, or while recall is on', async () => { + const unnamed = await fixture(successfulRequest, { promptRecall: false }) + await unnamed.run() + expect(unnamed.providerHeaders!({ ...route, sessionId: 'test-session' })).toEqual({ + 'x-route': 'configured', 'x-powercontext-conversation-id': 'test-session', + }) + expect(unnamed.diagnostics()).toEqual([]) + const recalling = await fixture(successfulRequest, { gatewayProvider: GATEWAY }) + await recalling.run() + expect(recalling.providerHeaders).toBeUndefined() + }) + + it('sends no Scope header and reports once per prompt when the prompt resolved no Scope', async () => { + const h = await fixture(path => path === SCOPE ? failure(503) : successfulRequest(path), + { promptRecall: false, gatewayProvider: GATEWAY }) + await h.run() + for (const purpose of [undefined, undefined, 'session-title']) { + expect(h.providerHeaders!({ ...route, sessionId: 'test-session', purpose })).not.toHaveProperty( + 'x-powercontext-scope-id') + } + expect(gatewayDiagnostics(h)).toEqual([{ + component: 'powercontext.dsh', event: 'gateway_scope', outcome: 'skipped', reason: 'scope_unresolved', + }]) + await h.run() + h.providerHeaders!({ ...route, sessionId: 'test-session' }) + expect(gatewayDiagnostics(h)).toHaveLength(2) + expect(JSON.stringify(h.diagnostics())).not.toContain(PRIVATE) + }) + + it('drops the previous prompt\'s Scope when the next prompt resolves none', async () => { + let unavailable = false + const h = await fixture(path => unavailable && path === SCOPE ? failure(503) : successfulRequest(path), + { promptRecall: false, gatewayProvider: GATEWAY }) + await h.run() + expect(h.providerHeaders!({ ...route, sessionId: 'test-session' })).toHaveProperty( + 'x-powercontext-scope-id', 'scope-test') + unavailable = true + await h.run() + expect(h.providerHeaders!({ ...route, sessionId: 'test-session' })).not.toHaveProperty('x-powercontext-scope-id') + expect(h.providerHeaders!({ ...route })).not.toHaveProperty('x-powercontext-scope-id') + expect(gatewayDiagnostics(h)).toHaveLength(2) + }) + + it.each([ + ['a comma', 'team,alpha'], + ['a space', 'team alpha'], + ['non-ASCII Latin-1 text', 'café'], + ['non-Latin-1 text', '团队'], + ['more than 256 characters', 'x'.repeat(257)], + ])('sends no Scope header for a Scope ID with %s and reports it once per prompt', async (_, scopeId) => { + const h = await fixture(path => path === SCOPE ? response({ scope_id: scopeId }) : successfulRequest(path), + { promptRecall: false, gatewayProvider: GATEWAY }) + await h.run() + expect(h.providerHeaders!({ ...route, sessionId: 'test-session' })).toEqual({ + 'x-route': 'configured', 'x-powercontext-conversation-id': 'test-session', + }) + expect(h.providerHeaders!({ ...route, sessionId: 'test-session', purpose: 'session-title' })).toEqual({ + 'x-route': 'configured', 'x-powercontext-turn': 'internal', + }) + expect(gatewayDiagnostics(h)).toEqual([{ + component: 'powercontext.dsh', event: 'gateway_scope', outcome: 'skipped', reason: 'scope_id_unsupported', + }]) + expect(JSON.stringify(h.diagnostics())).not.toContain(scopeId) + // Only the gateway header is skipped; capture still uses the resolved Scope. + expect(h.requests.find(({ path }) => path === CAPTURE)?.body).toMatchObject({ scope_id: scopeId }) + await h.run() + h.providerHeaders!({ ...route, sessionId: 'test-session' }) + expect(gatewayDiagnostics(h)).toHaveLength(2) + }) + + it.each(['!', '~', 'a+b-c', 'x'.repeat(256)])('sends the gateway-valid Scope ID %s', async (scopeId) => { + const h = await fixture(path => path === SCOPE ? response({ scope_id: scopeId }) : successfulRequest(path), + { promptRecall: false, gatewayProvider: GATEWAY }) + await h.run() + expect(h.providerHeaders!({ ...route, sessionId: 'test-session' })).toHaveProperty( + 'x-powercontext-scope-id', scopeId) + expect(gatewayDiagnostics(h)).toEqual([]) + }) + + it('rejects a gateway provider that is not a string', () => { + expect(Config['~standard'].validate({ gatewayProvider: 1 }).issues).toEqual([ + { message: 'gatewayProvider must be a string' }, + ]) + }) + }) + it('sends only Scope resolution for a prompt when recall and capture are both off', async () => { const h = await fixture(successfulRequest, { promptRecall: false, capturePrompts: false }) await h.run() From 5f7e68b534a70764d45a9afb305e14ac1db5c8a8 Mon Sep 17 00:00:00 2001 From: Fengzdadi <453788063@qq.com> Date: Thu, 3 Dec 2026 21:50:52 -0500 Subject: [PATCH 2/3] fix(dsh): keep each prompt's gateway Scope from its pre-step The gateway Scope header read the session's resolution cache, which MCP tool calls also write. After a failed pre-step, a later successful tool resolution moved the rest of the prompt's model requests from the gateway's default Scope to the workspace Scope, splitting recall replay, Core's checks and capture across Scopes within one tool loop. A tool resolution for another cwd, or a failed tool refresh, could likewise change or drop the prompt's Scope. Gateway routing now keeps its own snapshot per session. The pre-step's Scope resolution, which runs on the step that brings the prompt's messages, starts it as unresolved and fills it; later steps of the prompt and tool resolutions leave it unchanged. --- .../dsh/plugins/powercontext/lib/index.js | 29 ++++++--- .../dsh/plugins/powercontext/src/index.ts | 37 ++++++++---- .../powercontext/tests/automatic-path.spec.ts | 59 ++++++++++++++++++- 3 files changed, 101 insertions(+), 24 deletions(-) diff --git a/integrations/dsh/plugins/powercontext/lib/index.js b/integrations/dsh/plugins/powercontext/lib/index.js index 456fcec364..66a1a2e719 100644 --- a/integrations/dsh/plugins/powercontext/lib/index.js +++ b/integrations/dsh/plugins/powercontext/lib/index.js @@ -5801,13 +5801,12 @@ function createRuntime(ctx, config) { } function createSessionScopeResolver(runtime) { const cache = /* @__PURE__ */ new Map(); - const attempts = /* @__PURE__ */ new Map(); + const promptScopes = /* @__PURE__ */ new Map(); const keyFor = (sessionId, cwd) => sessionId ? `session:${sessionId}` : `cwd:${cwd ?? ""}`; const resolve$1 = async (request$2, refresh) => { const key$1 = keyFor(request$2.sessionId, request$2.cwd); const cached = cache.get(key$1); if (!refresh && cached && cached.cwd === request$2.cwd) return cached.scopeId; - if (refresh) attempts.set(key$1, (attempts.get(key$1) ?? 0) + 1); cache.delete(key$1); const scopeId = await runtime.resolveScope(request$2.cwd, request$2.signal); if (scopeId) cache.set(key$1, { @@ -5817,17 +5816,28 @@ function createSessionScopeResolver(runtime) { return scopeId; }; return { - forPreStep: (request$2) => resolve$1(request$2, true), + forPrompt: (sessionId) => async (request$2) => { + const attempt = (promptScopes.get(sessionId)?.attempt ?? 0) + 1; + promptScopes.set(sessionId, { + scopeId: void 0, + attempt + }); + const scopeId = await resolve$1(request$2, true); + if (promptScopes.get(sessionId)?.attempt === attempt) promptScopes.set(sessionId, { + scopeId, + attempt + }); + return scopeId; + }, forTool: (request$2) => resolve$1(request$2, false), forGateway: (sessionId) => { if (!sessionId) return { scopeId: void 0, attempt: 0 }; - const key$1 = keyFor(sessionId, void 0); - return { - scopeId: cache.get(key$1)?.scopeId, - attempt: attempts.get(key$1) ?? 0 + return promptScopes.get(sessionId) ?? { + scopeId: void 0, + attempt: 0 }; }, current: (sessionId, cwd) => { @@ -5858,8 +5868,9 @@ function registerScopeRoutingContext(ctx, currentScope) { } }); } -function registerRecall(ctx, runtime, createUserMessage, resolveSessionScope) { +function registerRecall(ctx, runtime, createUserMessage, resolvePromptScope) { ctx.on("agent/pre-step", (async (payload, next) => { + const resolveSessionScope = resolvePromptScope(payload.agent.session.header.id); return runRecallPreStep({ messages: payload.messages, next, @@ -5970,7 +5981,7 @@ async function apply(ctx, config) { registerMcpPolicy(ctx, sessionScope.forTool, runtime.config.authorization); registerSkill(ctx); registerGuidance(ctx); - registerRecall(ctx, runtime, llmMod.createUserMessage, sessionScope.forPreStep); + registerRecall(ctx, runtime, llmMod.createUserMessage, sessionScope.forPrompt); if (!runtime.config.promptRecall) { registerGatewayHeaders(ctx, runtime, sessionScope.forGateway); registerScopeRoutingContext(ctx, sessionScope.current); diff --git a/integrations/dsh/plugins/powercontext/src/index.ts b/integrations/dsh/plugins/powercontext/src/index.ts index fb5a518d32..330ae47382 100644 --- a/integrations/dsh/plugins/powercontext/src/index.ts +++ b/integrations/dsh/plugins/powercontext/src/index.ts @@ -91,21 +91,23 @@ function createRuntime(ctx: Context, config: PluginConfig): PluginRuntime { type SessionScopeResolver = (request: McpScopeResolutionRequest) => Promise -/** The Scope a session's latest prompt resolved, and which resolution produced it. */ -interface ResolvedSessionScope { +/** The Scope a session's latest prompt resolved in its pre-step, and which prompt that was. */ +interface PromptScope { scopeId: string | undefined attempt: number } function createSessionScopeResolver(runtime: PluginRuntime): { - forPreStep: SessionScopeResolver + forPrompt: (sessionId: string) => SessionScopeResolver forTool: SessionScopeResolver current: (sessionId: string, cwd: string | undefined) => string | undefined - forGateway: (sessionId: string) => ResolvedSessionScope + forGateway: (sessionId: string) => PromptScope } { const cache = new Map() - // Counts each prompt's resolution, so a missing Scope is reported once per prompt, not once per request. - const attempts = new Map() + // Gateway routing reads only what each prompt's pre-step resolved, an unresolved result included. Recall replay, + // Core's checks and capture all follow the Scope header, so a tool resolution that succeeds after a failed + // pre-step, uses another cwd or fails must not move the prompt's remaining model requests to another Scope. + const promptScopes = new Map() const keyFor = (sessionId: string | undefined, cwd: string | undefined) => ( sessionId ? `session:${sessionId}` : `cwd:${cwd ?? ''}` ) @@ -113,7 +115,6 @@ function createSessionScopeResolver(runtime: PluginRuntime): { const key = keyFor(request.sessionId, request.cwd) const cached = cache.get(key) if (!refresh && cached && cached.cwd === request.cwd) return cached.scopeId - if (refresh) attempts.set(key, (attempts.get(key) ?? 0) + 1) // A failed refresh must not leave a previous turn's Scope available to MCP calls. cache.delete(key) const scopeId = await runtime.resolveScope(request.cwd, request.signal) @@ -121,13 +122,22 @@ function createSessionScopeResolver(runtime: PluginRuntime): { return scopeId } return { - forPreStep: request => resolve(request, true), + // DSH runs the pre-step before every step of the agent loop, but only a step that brings the prompt's messages + // resolves the Scope. That resolution starts the prompt's snapshot as unresolved and fills it; a later step of + // the same prompt, such as a tool continuation, leaves it as it is. + forPrompt: (sessionId) => async (request) => { + const attempt = (promptScopes.get(sessionId)?.attempt ?? 0) + 1 + promptScopes.set(sessionId, { scopeId: undefined, attempt }) + const scopeId = await resolve(request, true) + // A later prompt of the session owns the snapshot once its resolution has started. + if (promptScopes.get(sessionId)?.attempt === attempt) promptScopes.set(sessionId, { scopeId, attempt }) + return scopeId + }, forTool: request => resolve(request, false), forGateway: (sessionId) => { // A request without a session ID cannot be matched to a prompt's resolution. if (!sessionId) return { scopeId: undefined, attempt: 0 } - const key = keyFor(sessionId, undefined) - return { scopeId: cache.get(key)?.scopeId, attempt: attempts.get(key) ?? 0 } + return promptScopes.get(sessionId) ?? { scopeId: undefined, attempt: 0 } }, // Reads what the session's latest resolution left, without contacting the Server. current: (sessionId, cwd) => { @@ -178,7 +188,7 @@ function registerRecall( ctx: Context, runtime: PluginRuntime, createUserMessage: CreateUserMessage, - resolveSessionScope: SessionScopeResolver, + resolvePromptScope: (sessionId: string) => SessionScopeResolver, ): void { ctx.on('agent/pre-step', (async (payload: { agent: { session: { header: { id: string; cwd?: string } } } @@ -186,6 +196,7 @@ function registerRecall( turn: number signal: AbortSignal }, next: () => Promise<{ kind: string; messages?: unknown[] }>) => { + const resolveSessionScope = resolvePromptScope(payload.agent.session.header.id) return runRecallPreStep({ messages: payload.messages, next, @@ -242,7 +253,7 @@ const GATEWAY_SCOPE_ID = /^[\x21-\x2b\x2d-\x7e]{1,256}$/ function registerGatewayHeaders( ctx: Context, runtime: PluginRuntime, - sessionScope: (sessionId: string) => ResolvedSessionScope, + sessionScope: (sessionId: string) => PromptScope, ): void { const reported = new Map() ctx.on('llm-pi-ai/request-headers', (( @@ -296,7 +307,7 @@ export async function apply(ctx: Context, config: Config): Promise { registerMcpPolicy(ctx, sessionScope.forTool, runtime.config.authorization) registerSkill(ctx) registerGuidance(ctx) - registerRecall(ctx, runtime, llmMod.createUserMessage, sessionScope.forPreStep) + registerRecall(ctx, runtime, llmMod.createUserMessage, sessionScope.forPrompt) // Prompt recall is off when the gateway injects context. Only then are the gateway headers sent, so a // provider that DSH calls directly while recall is on does not receive them, and only then does the Scope // routing move from the step's messages to the runtime context. diff --git a/integrations/dsh/plugins/powercontext/tests/automatic-path.spec.ts b/integrations/dsh/plugins/powercontext/tests/automatic-path.spec.ts index ad30954ab3..979317da3b 100644 --- a/integrations/dsh/plugins/powercontext/tests/automatic-path.spec.ts +++ b/integrations/dsh/plugins/powercontext/tests/automatic-path.spec.ts @@ -112,11 +112,11 @@ async function fixture( }, options.next ?? (async () => ({ kind: 'enter', messages }))) } if (!toolHook) throw new Error('MCP policy hook was not registered') - const search = () => toolHook!({ + const search = (options: { cwd?: string } = {}) => toolHook!({ name: 'mcp__powercontext__search_memory', arguments: { scope_id: 'scope-test', query: 'Aurora' }, signal: new AbortController().signal, - agent: { session: { header: { id: 'test-session' } } }, + agent: { session: { header: { id: 'test-session', cwd: options.cwd } } }, }, async () => ({ kind: 'allow' })) // Mirrors how llm-pi-ai runs the waterfall: the route's headers in, the final request headers out. const providerHeaders = headerHook && ((request: Record) => { @@ -666,6 +666,61 @@ describe('registered automatic path', () => { expect(gatewayDiagnostics(h)).toHaveLength(2) }) + describe('keeps the pre-step\'s result for the rest of the prompt', () => { + const scopeHeader = (h: Awaited>) => ( + h.providerHeaders!({ ...route, sessionId: 'test-session' })['x-powercontext-scope-id'] + ) + + it('when an MCP call resolves the Scope after the pre-step failed', async () => { + let resolutions = 0 + const h = await fixture(path => path === SCOPE && resolutions++ === 0 ? failure(503) : successfulRequest(path), + { promptRecall: false, gatewayProvider: GATEWAY }) + await h.run() + expect(scopeHeader(h)).toBeUndefined() + // The MCP policy resolves the session's Scope again, and this time it succeeds. + expect(await h.search()).toEqual({ kind: 'allow' }) + expect(h.requests.filter(({ path }) => path === SCOPE)).toHaveLength(2) + expect(scopeHeader(h)).toBeUndefined() + expect(h.providerHeaders!({ ...route, sessionId: 'test-session', purpose: 'compaction' })).not.toHaveProperty( + 'x-powercontext-scope-id') + // The next prompt's pre-step takes the Scope it resolves. + await h.run() + expect(scopeHeader(h)).toBe('scope-test') + }) + + it('across the agent loop\'s later steps, which bring no new messages', async () => { + const h = await fixture(successfulRequest, { promptRecall: false, gatewayProvider: GATEWAY }) + await h.run() + // DSH runs the pre-step again before the step that continues after a tool call. + await h.run({ messages: [] }) + expect(h.requests.filter(({ path }) => path === SCOPE)).toHaveLength(1) + expect(scopeHeader(h)).toBe('scope-test') + expect(gatewayDiagnostics(h)).toEqual([]) + }) + + it('when an MCP call from another cwd resolves another Scope', async () => { + let resolutions = 0 + const h = await fixture(path => path === SCOPE + ? response({ scope_id: resolutions++ === 0 ? 'scope-test' : 'scope-other' }) + : successfulRequest(path), { promptRecall: false, gatewayProvider: GATEWAY }) + await h.run({ cwd: '/work/api' }) + await h.search({ cwd: '/work/other' }) + expect(h.requests.filter(({ path }) => path === SCOPE)).toHaveLength(2) + expect(scopeHeader(h)).toBe('scope-test') + }) + + it('when an MCP call from another cwd fails to resolve', async () => { + let resolutions = 0 + const h = await fixture(path => path === SCOPE && resolutions++ > 0 ? failure(503) : successfulRequest(path), + { promptRecall: false, gatewayProvider: GATEWAY }) + await h.run({ cwd: '/work/api' }) + await h.search({ cwd: '/work/other' }) + expect(h.requests.filter(({ path }) => path === SCOPE)).toHaveLength(2) + expect(scopeHeader(h)).toBe('scope-test') + expect(gatewayDiagnostics(h)).toEqual([]) + }) + }) + it.each([ ['a comma', 'team,alpha'], ['a space', 'team alpha'], From dc990368ad12f51f8be9e3e841d755871353dad4 Mon Sep 17 00:00:00 2001 From: Fengzdadi <453788063@qq.com> Date: Thu, 3 Dec 2026 21:55:27 -0500 Subject: [PATCH 3/3] feat(dsh): mark gateway requests internal when the prompt has no usable Scope Without a Scope header the gateway prepares, injects and captures a turn in its default Scope, not the workspace's. A failed, timed-out or empty Scope resolution is not a resolution to that Scope, so a prompt that resolved no Scope, or one whose ID the header cannot carry, now sends its requests to the gateway provider with X-PowerContext-Turn: internal and no Scope or conversation header. A request that cannot be matched to a prompt is treated the same way. Every gateway request then either carries the prompt's Scope or is internal; Core still checks internal requests, in the gateway's default Scope. Requests to other providers are unchanged. The gateway_scope diagnostic keeps its event, outcome and reasons. The DSH guide (en and zh) and the plugin README describe the fallback. --- docs/en/docs/integrations/dsh.md | 18 ++++-- docs/zh/docs/integrations/dsh.md | 20 ++++--- .../dsh/plugins/powercontext/README.md | 5 +- .../dsh/plugins/powercontext/lib/index.js | 28 ++++++---- .../dsh/plugins/powercontext/src/index.ts | 23 +++++--- .../powercontext/tests/automatic-path.spec.ts | 56 +++++++++++++++---- 6 files changed, 106 insertions(+), 44 deletions(-) diff --git a/docs/en/docs/integrations/dsh.md b/docs/en/docs/integrations/dsh.md index 6762edd8c3..fd60308691 100644 --- a/docs/en/docs/integrations/dsh.md +++ b/docs/en/docs/integrations/dsh.md @@ -781,10 +781,18 @@ provider sets `cacheRetention: "none"`. prints, as `X-PowerContext-Scope-ID` on every request to that provider, compaction, session-title, and auto-review requests included. The gateway then prepares and captures turns in that Scope instead of `PC_GATEWAY_DEFAULT_SCOPE`, and Core checks each request in it. Requests to any other provider carry no Scope header. The plugin resolves the -Scope once per prompt, so a changed binding applies from the next prompt. The request carries no Scope header, and -the gateway uses `PC_GATEWAY_DEFAULT_SCOPE`, when the variable is unset, when the session's latest prompt resolved no -Scope, or when the header cannot carry the Scope's ID, which can happen with a Scope from an early release. In the -last two cases the plugin logs one `gateway_scope` diagnostic for that prompt, with `reason: scope_unresolved` or +Scope once per prompt, before the prompt's first model request, so a changed binding applies from the next prompt. +Every request of the prompt uses that result, even when an MCP tool call resolves the Scope again later in the prompt. +While the variable is unset, requests carry no Scope header, and the gateway uses `PC_GATEWAY_DEFAULT_SCOPE`. + +The plugin sends a request to the gateway provider with `X-PowerContext-Turn: internal` and no Scope or conversation +header when the session's latest prompt resolved no Scope, when it resolved a Scope whose ID the header cannot carry, +which can happen with a Scope from an early release, or when the request cannot be matched to a resolved prompt: it +has no session ID, or no prompt of its session has resolved the Scope yet. +The gateway neither prepares, injects nor captures an internal request, so it gives such a turn no recall and does +not capture it, instead of preparing and capturing it in `PC_GATEWAY_DEFAULT_SCOPE`. Core still checks the request +before the gateway sends it and before the gateway releases the response, in `PC_GATEWAY_DEFAULT_SCOPE`. The plugin +logs one `gateway_scope` diagnostic for such a prompt, with `reason: scope_unresolved` or `reason: scope_id_unsupported`. For a Scope whose ID the header cannot carry, the plugin's own prompt capture and MCP tools still use that Scope. See [Gateway request Scope](../operate/deploy-server.md#gateway-request-scope) for the IDs the header can carry. @@ -877,7 +885,7 @@ with `--dsh-command /path/to/Desktop/resources/runtime/cli/bin/dsh` (`dsh.cmd` o | `POWERCONTEXT_DSH_SCOPE_ID` | unset | Explicit existing Scope before workspace binding and Server default | | `POWERCONTEXT_DSH_AUTHORIZATION` | unset | Complete `Bearer ` header for MCP and lifecycle HTTP requests | | `POWERCONTEXT_DSH_PROMPT_RECALL` | `true` | Prepare and add context before each model step and provide the companion memory service; `false` leaves prompt-time context to the gateway and sends the gateway conversation and internal-turn headers | -| `POWERCONTEXT_DSH_GATEWAY_PROVIDER` | unset | `llm-pi-ai` provider that routes through the gateway; while prompt recall is off, only its requests carry the session's Scope as `X-PowerContext-Scope-ID` | +| `POWERCONTEXT_DSH_GATEWAY_PROVIDER` | unset | `llm-pi-ai` provider that routes through the gateway; while prompt recall is off, only its requests carry the prompt's Scope as `X-PowerContext-Scope-ID`, or `X-PowerContext-Turn: internal` when the prompt has no usable Scope | | `POWERCONTEXT_DSH_CAPTURE_PROMPTS` | `true` | Capture user prompts as Source evidence | | `POWERCONTEXT_DSH_FLUSH_ON_CAPTURE` | `false` | Wait for Source processing after capture | diff --git a/docs/zh/docs/integrations/dsh.md b/docs/zh/docs/integrations/dsh.md index db5706e4de..4eacbe716f 100644 --- a/docs/zh/docs/integrations/dsh.md +++ b/docs/zh/docs/integrations/dsh.md @@ -675,12 +675,18 @@ DSH 会把这些请求头发给处理该请求的任何 provider,包括它直 关闭召回后,插件会把它为会话 workspace 解析的 Scope(即 `/pc` 打印的 Scope)作为 `X-PowerContext-Scope-ID`, 发送到这个 provider 的每个请求上,压缩、会话标题和 auto review 请求也包括在内。 gateway 随后在这个 Scope 而不是 `PC_GATEWAY_DEFAULT_SCOPE` 中准备和采集各轮,Core 也在这个 Scope 中检查每个请求。 -发给其他 provider 的请求不带 Scope 请求头。插件每条提示词解析一次 Scope,因此 binding 改变后,从下一条提示词起生效。 -未设置这个变量、会话最近一条提示词没有解析出 Scope, -或请求头无法携带该 Scope 的 ID(早期版本的 Scope 可能如此)时, -请求不带 Scope 请求头,gateway 使用 `PC_GATEWAY_DEFAULT_SCOPE`。 -在后两种情况下,插件为这条提示词记录一条 `gateway_scope` 诊断, -`reason` 为 `scope_unresolved` 或 `scope_id_unsupported`。 +发给其他 provider 的请求不带 Scope 请求头。插件在每条提示词的第一个模型请求之前解析一次 Scope, +因此 binding 改变后,从下一条提示词起生效。 +这条提示词的每个请求都使用这次的结果,即使 MCP 工具调用在这条提示词中再次解析了 Scope。 +未设置这个变量时,请求不带 Scope 请求头,gateway 使用 `PC_GATEWAY_DEFAULT_SCOPE`。 + +会话最近一条提示词没有解析出 Scope、解析出的 Scope 的 ID 无法由请求头携带(早期版本的 Scope 可能如此), +或请求无法与已解析的提示词对应(请求没有会话 ID,或它所在会话还没有提示词解析过 Scope)时, +插件发给 gateway provider 的请求带 `X-PowerContext-Turn: internal`,不带 Scope 请求头和会话请求头。 +gateway 不为 internal 请求准备或注入上下文,也不采集它。 +这样的一轮因此既没有召回,也不会被采集;gateway 不会改在 `PC_GATEWAY_DEFAULT_SCOPE` 中准备和采集它。 +gateway 发送请求之前和放行响应之前,Core 仍会在 `PC_GATEWAY_DEFAULT_SCOPE` 中检查这个请求。 +插件为这样的提示词记录一条 `gateway_scope` 诊断,`reason` 为 `scope_unresolved` 或 `scope_id_unsupported`。 对于请求头无法携带其 ID 的 Scope,插件自己的提示词采集和 MCP 工具仍使用该 Scope。 请求头能携带哪些 ID,见[Gateway 请求 Scope](../operate/deploy-server.md#gateway-请求-scope)。 @@ -769,7 +775,7 @@ powercontext setup dsh --remove --profile desktop | `POWERCONTEXT_DSH_SCOPE_ID` | 未设置 | 在 workspace binding 和 Server 默认值之前显式选择已有 Scope | | `POWERCONTEXT_DSH_AUTHORIZATION` | 未设置 | MCP 与生命周期 HTTP 请求使用的完整 `Bearer ` header | | `POWERCONTEXT_DSH_PROMPT_RECALL` | `true` | 每次模型调用前准备并添加上下文,并提供桌宠记忆服务;`false` 把提示词时上下文交给 gateway,并发送 gateway 会话请求头和 internal 轮次请求头 | -| `POWERCONTEXT_DSH_GATEWAY_PROVIDER` | 未设置 | 经由 gateway 的 `llm-pi-ai` provider;关闭提示词召回时,只有它的请求以 `X-PowerContext-Scope-ID` 携带会话的 Scope | +| `POWERCONTEXT_DSH_GATEWAY_PROVIDER` | 未设置 | 经由 gateway 的 `llm-pi-ai` provider;关闭提示词召回时,只有它的请求以 `X-PowerContext-Scope-ID` 携带提示词的 Scope,提示词没有可用的 Scope 时带 `X-PowerContext-Turn: internal` | | `POWERCONTEXT_DSH_CAPTURE_PROMPTS` | `true` | 把用户提示词采集为 Source 证据 | | `POWERCONTEXT_DSH_FLUSH_ON_CAPTURE` | `false` | 采集后等待 Source 处理 | diff --git a/integrations/dsh/plugins/powercontext/README.md b/integrations/dsh/plugins/powercontext/README.md index ba48189070..3639dc42f8 100644 --- a/integrations/dsh/plugins/powercontext/README.md +++ b/integrations/dsh/plugins/powercontext/README.md @@ -133,8 +133,9 @@ the `POWERCONTEXT_DSH_` prefix for `BASE_URL`, `AUTHORIZATION`, `SCOPE_ID`, `PRO `CAPTURE_PROMPTS`, and `FLUSH_ON_CAPTURE`. Set `POWERCONTEXT_DSH_PROMPT_RECALL=false` when DeepSeek Harness reaches its model through the PowerContext gateway, which then prepares context for each turn, and set `POWERCONTEXT_DSH_GATEWAY_PROVIDER` to the gateway's `llm-pi-ai` provider so that the gateway works in the workspace's -Scope. A Scope whose ID the gateway's Scope header cannot carry, which can happen with a Scope from an early release, -is not sent; the gateway then uses its default Scope, and the plugin logs a `gateway_scope` diagnostic. +Scope. When a prompt resolves no Scope, or one whose ID the gateway's Scope header cannot carry, which can happen with +a Scope from an early release, its gateway requests are marked `X-PowerContext-Turn: internal`, so the gateway neither +prepares nor captures them in its default Scope, and the plugin logs a `gateway_scope` diagnostic. `timeoutMs`, `requestTimeoutMs`, `maxBytes`, `flushMaxCalls`, and `ownerLocal` are plugin patch settings. Context returned by recall is labelled as untrusted history. An unavailable Server never blocks normal Harness work. diff --git a/integrations/dsh/plugins/powercontext/lib/index.js b/integrations/dsh/plugins/powercontext/lib/index.js index 66a1a2e719..f48661d78b 100644 --- a/integrations/dsh/plugins/powercontext/lib/index.js +++ b/integrations/dsh/plugins/powercontext/lib/index.js @@ -5930,30 +5930,36 @@ const GATEWAY_SCOPE_ID = /^[\x21-\x2b\x2d-\x7e]{1,256}$/; * Name the gateway conversation on each model request of a session's agent loop. DSH marks its other model * requests, such as compaction, session titles and auto review, with a `purpose`; they are not turns of the * conversation, so they are marked internal instead. Requests to the configured gateway provider, internal ones -* included, also carry the Scope that the session's latest prompt resolved, when the gateway accepts its ID. The hook -* is synchronous and must not throw. +* included, also carry the Scope that the session's latest prompt resolved in its pre-step. When that prompt resolved +* no Scope, resolved one whose ID the gateway does not accept, or cannot be identified, the request is marked internal +* instead, so the gateway neither prepares nor captures it in its default Scope. The hook is synchronous and must not +* throw. */ function registerGatewayHeaders(ctx, runtime, sessionScope) { const reported = /* @__PURE__ */ new Map(); ctx.on("llm-pi-ai/request-headers", ((request$2, _headers, next) => { const result = next(); const conversation = request$2.sessionId; + let internal = request$2.purpose !== void 0; const provider = runtime.config.gatewayProvider; if (provider !== void 0 && request$2.provider === provider) { const sessionId = typeof conversation === "string" ? conversation : ""; const resolved = sessionScope(sessionId); if (resolved.scopeId !== void 0 && GATEWAY_SCOPE_ID.test(resolved.scopeId)) result.set(SCOPE_HEADER, resolved.scopeId); - else if (reported.get(sessionId) !== resolved.attempt) { - reported.set(sessionId, resolved.attempt); - const reason = resolved.scopeId === void 0 ? "scope_unresolved" : "scope_id_unsupported"; - logSafely(runtime.log, { - event: "gateway_scope", - outcome: "skipped", - reason - }); + else { + internal = true; + if (reported.get(sessionId) !== resolved.attempt) { + reported.set(sessionId, resolved.attempt); + const reason = resolved.scopeId === void 0 ? "scope_unresolved" : "scope_id_unsupported"; + logSafely(runtime.log, { + event: "gateway_scope", + outcome: "skipped", + reason + }); + } } } - if (request$2.purpose !== void 0) result.set(TURN_HEADER, "internal"); + if (internal) result.set(TURN_HEADER, "internal"); else if (typeof conversation === "string" && CONVERSATION_ID.test(conversation)) result.set(CONVERSATION_HEADER, conversation); return result; })); diff --git a/integrations/dsh/plugins/powercontext/src/index.ts b/integrations/dsh/plugins/powercontext/src/index.ts index 330ae47382..2ec571c5fe 100644 --- a/integrations/dsh/plugins/powercontext/src/index.ts +++ b/integrations/dsh/plugins/powercontext/src/index.ts @@ -247,8 +247,10 @@ const GATEWAY_SCOPE_ID = /^[\x21-\x2b\x2d-\x7e]{1,256}$/ * Name the gateway conversation on each model request of a session's agent loop. DSH marks its other model * requests, such as compaction, session titles and auto review, with a `purpose`; they are not turns of the * conversation, so they are marked internal instead. Requests to the configured gateway provider, internal ones - * included, also carry the Scope that the session's latest prompt resolved, when the gateway accepts its ID. The hook - * is synchronous and must not throw. + * included, also carry the Scope that the session's latest prompt resolved in its pre-step. When that prompt resolved + * no Scope, resolved one whose ID the gateway does not accept, or cannot be identified, the request is marked internal + * instead, so the gateway neither prepares nor captures it in its default Scope. The hook is synchronous and must not + * throw. */ function registerGatewayHeaders( ctx: Context, @@ -263,6 +265,7 @@ function registerGatewayHeaders( ) => { const result = next() const conversation = request.sessionId + let internal = request.purpose !== undefined // Only the gateway reads the Scope, so a provider that DSH calls directly does not receive it. const provider = runtime.config.gatewayProvider if (provider !== undefined && request.provider === provider) { @@ -270,14 +273,18 @@ function registerGatewayHeaders( const resolved = sessionScope(sessionId) if (resolved.scopeId !== undefined && GATEWAY_SCOPE_ID.test(resolved.scopeId)) { result.set(SCOPE_HEADER, resolved.scopeId) - } else if (reported.get(sessionId) !== resolved.attempt) { - // Without the header the gateway uses its default Scope; the request itself still proceeds. - reported.set(sessionId, resolved.attempt) - const reason = resolved.scopeId === undefined ? 'scope_unresolved' : 'scope_id_unsupported' - logSafely(runtime.log, { event: 'gateway_scope', outcome: 'skipped', reason }) + } else { + // Without the header the gateway would prepare and capture the turn in its default Scope, not the + // workspace's. An internal request is still checked by Core, but is neither prepared nor captured. + internal = true + if (reported.get(sessionId) !== resolved.attempt) { + reported.set(sessionId, resolved.attempt) + const reason = resolved.scopeId === undefined ? 'scope_unresolved' : 'scope_id_unsupported' + logSafely(runtime.log, { event: 'gateway_scope', outcome: 'skipped', reason }) + } } } - if (request.purpose !== undefined) { + if (internal) { result.set(TURN_HEADER, 'internal') } else if (typeof conversation === 'string' && CONVERSATION_ID.test(conversation)) { result.set(CONVERSATION_HEADER, conversation) diff --git a/integrations/dsh/plugins/powercontext/tests/automatic-path.spec.ts b/integrations/dsh/plugins/powercontext/tests/automatic-path.spec.ts index 979317da3b..ba8630987f 100644 --- a/integrations/dsh/plugins/powercontext/tests/automatic-path.spec.ts +++ b/integrations/dsh/plugins/powercontext/tests/automatic-path.spec.ts @@ -635,14 +635,20 @@ describe('registered automatic path', () => { expect(recalling.providerHeaders).toBeUndefined() }) - it('sends no Scope header and reports once per prompt when the prompt resolved no Scope', async () => { + it('marks the gateway requests internal and reports once per prompt when the prompt resolved no Scope', async () => { const h = await fixture(path => path === SCOPE ? failure(503) : successfulRequest(path), { promptRecall: false, gatewayProvider: GATEWAY }) await h.run() + // Without the workspace's Scope, the gateway must neither prepare nor capture the turn in its default Scope. for (const purpose of [undefined, undefined, 'session-title']) { - expect(h.providerHeaders!({ ...route, sessionId: 'test-session', purpose })).not.toHaveProperty( - 'x-powercontext-scope-id') + expect(h.providerHeaders!({ ...route, sessionId: 'test-session', purpose })).toEqual({ + 'x-route': 'configured', 'x-powercontext-turn': 'internal', + }) } + // A provider that DSH calls directly still gets the conversation header and no internal marker. + expect(h.providerHeaders!({ ...route, provider: 'direct-provider', sessionId: 'test-session' })).toEqual({ + 'x-route': 'configured', 'x-powercontext-conversation-id': 'test-session', + }) expect(gatewayDiagnostics(h)).toEqual([{ component: 'powercontext.dsh', event: 'gateway_scope', outcome: 'skipped', reason: 'scope_unresolved', }]) @@ -661,9 +667,36 @@ describe('registered automatic path', () => { 'x-powercontext-scope-id', 'scope-test') unavailable = true await h.run() - expect(h.providerHeaders!({ ...route, sessionId: 'test-session' })).not.toHaveProperty('x-powercontext-scope-id') - expect(h.providerHeaders!({ ...route })).not.toHaveProperty('x-powercontext-scope-id') - expect(gatewayDiagnostics(h)).toHaveLength(2) + expect(h.providerHeaders!({ ...route, sessionId: 'test-session' })).toEqual({ + 'x-route': 'configured', 'x-powercontext-turn': 'internal', + }) + expect(gatewayDiagnostics(h)).toEqual([ + { component: 'powercontext.dsh', event: 'gateway_scope', outcome: 'skipped', reason: 'scope_unresolved' }, + ]) + }) + + it('marks a gateway request internal when it cannot be matched to a prompt', async () => { + const h = await fixture(successfulRequest, { promptRecall: false, gatewayProvider: GATEWAY }) + // No prompt of the session has started its pre-step yet. + expect(h.providerHeaders!({ ...route, sessionId: 'test-session' })).toEqual({ + 'x-route': 'configured', 'x-powercontext-turn': 'internal', + }) + await h.run() + // A request without a session ID cannot be matched to the prompt that resolved the Scope. + for (const sessionId of [undefined, '']) { + expect(h.providerHeaders!({ ...route, sessionId })).toEqual({ + 'x-route': 'configured', 'x-powercontext-turn': 'internal', + }) + } + expect(h.providerHeaders!({ ...route, sessionId: 'test-session' })).toEqual({ + 'x-route': 'configured', + 'x-powercontext-conversation-id': 'test-session', + 'x-powercontext-scope-id': 'scope-test', + }) + expect(gatewayDiagnostics(h)).toEqual([ + { component: 'powercontext.dsh', event: 'gateway_scope', outcome: 'skipped', reason: 'scope_unresolved' }, + { component: 'powercontext.dsh', event: 'gateway_scope', outcome: 'skipped', reason: 'scope_unresolved' }, + ]) }) describe('keeps the pre-step\'s result for the rest of the prompt', () => { @@ -676,11 +709,12 @@ describe('registered automatic path', () => { const h = await fixture(path => path === SCOPE && resolutions++ === 0 ? failure(503) : successfulRequest(path), { promptRecall: false, gatewayProvider: GATEWAY }) await h.run() - expect(scopeHeader(h)).toBeUndefined() + const unresolved = h.providerHeaders!({ ...route, sessionId: 'test-session' }) + expect(unresolved['x-powercontext-scope-id']).toBeUndefined() // The MCP policy resolves the session's Scope again, and this time it succeeds. expect(await h.search()).toEqual({ kind: 'allow' }) expect(h.requests.filter(({ path }) => path === SCOPE)).toHaveLength(2) - expect(scopeHeader(h)).toBeUndefined() + expect(h.providerHeaders!({ ...route, sessionId: 'test-session' })).toEqual(unresolved) expect(h.providerHeaders!({ ...route, sessionId: 'test-session', purpose: 'compaction' })).not.toHaveProperty( 'x-powercontext-scope-id') // The next prompt's pre-step takes the Scope it resolves. @@ -727,12 +761,12 @@ describe('registered automatic path', () => { ['non-ASCII Latin-1 text', 'café'], ['non-Latin-1 text', '团队'], ['more than 256 characters', 'x'.repeat(257)], - ])('sends no Scope header for a Scope ID with %s and reports it once per prompt', async (_, scopeId) => { + ])('marks the gateway requests internal for a Scope ID with %s and reports it once per prompt', async (_, scopeId) => { const h = await fixture(path => path === SCOPE ? response({ scope_id: scopeId }) : successfulRequest(path), { promptRecall: false, gatewayProvider: GATEWAY }) await h.run() expect(h.providerHeaders!({ ...route, sessionId: 'test-session' })).toEqual({ - 'x-route': 'configured', 'x-powercontext-conversation-id': 'test-session', + 'x-route': 'configured', 'x-powercontext-turn': 'internal', }) expect(h.providerHeaders!({ ...route, sessionId: 'test-session', purpose: 'session-title' })).toEqual({ 'x-route': 'configured', 'x-powercontext-turn': 'internal', @@ -741,7 +775,7 @@ describe('registered automatic path', () => { component: 'powercontext.dsh', event: 'gateway_scope', outcome: 'skipped', reason: 'scope_id_unsupported', }]) expect(JSON.stringify(h.diagnostics())).not.toContain(scopeId) - // Only the gateway header is skipped; capture still uses the resolved Scope. + // Only the gateway request changes; the plugin's own capture still uses the resolved Scope. expect(h.requests.find(({ path }) => path === CAPTURE)?.body).toMatchObject({ scope_id: scopeId }) await h.run() h.providerHeaders!({ ...route, sessionId: 'test-session' })