diff --git a/README.md b/README.md index c54605fccf..acd092a1b1 100644 --- a/README.md +++ b/README.md @@ -233,7 +233,7 @@ Codex is officially maintained; other Agent and Python framework integrations ar ## Learn more - [Core concepts](https://powercontext.oceanbase.io/en/docs/get-started/core-concepts/) · [Architecture and responsibilities](https://powercontext.oceanbase.io/en/docs/workflows/architecture/) · [Plugins](https://powercontext.oceanbase.io/en/docs/develop/plugins/) -- [Python / HTTP / MCP interfaces](https://powercontext.oceanbase.io/en/docs/develop/interfaces/) · [Deploy the Server](https://powercontext.oceanbase.io/en/docs/operate/deploy-server/) +- [Python / HTTP / MCP interfaces](https://powercontext.oceanbase.io/en/docs/develop/interfaces/) · [Deploy the Server](https://powercontext.oceanbase.io/en/docs/operate/deploy-server/) · [Select a Scope per Gateway request](docs/en/docs/operate/deploy-server.md#gateway-request-scope) - [Token benchmark report](docs/benchmarks/token-savings/README.md) · [Blog](https://powercontext.oceanbase.io/en/blog/) ## Community diff --git a/README_CN.md b/README_CN.md index d211072f9c..e7078dd068 100644 --- a/README_CN.md +++ b/README_CN.md @@ -233,7 +233,7 @@ Codex 为官方维护;其余 Agent 和 Python 框架集成为社区维护;Bu ## 了解更多 - [核心概念](https://powercontext.oceanbase.io/zh/docs/get-started/core-concepts/) · [架构与职责边界](https://powercontext.oceanbase.io/zh/docs/workflows/architecture/) · [插件开发](https://powercontext.oceanbase.io/zh/docs/develop/plugins/) -- [Python / HTTP / MCP 接口](https://powercontext.oceanbase.io/zh/docs/develop/interfaces/) · [部署 Server](https://powercontext.oceanbase.io/zh/docs/operate/deploy-server/) +- [Python / HTTP / MCP 接口](https://powercontext.oceanbase.io/zh/docs/develop/interfaces/) · [部署 Server](https://powercontext.oceanbase.io/zh/docs/operate/deploy-server/) · [为每个 Gateway 请求选择 Scope](docs/zh/docs/operate/deploy-server.md#gateway-请求-scope) - [Token 评测报告](docs/benchmarks/token-savings/README_CN.md) · [博客](https://powercontext.oceanbase.io/zh/blog/) ## 社区 diff --git a/README_JP.md b/README_JP.md index f9a64fe984..48e0895878 100644 --- a/README_JP.md +++ b/README_JP.md @@ -233,7 +233,7 @@ Codex 連携は公式メンテナンス、その他の Agent と Python フレ ## さらに詳しく - [基本概念](https://powercontext.oceanbase.io/en/docs/get-started/core-concepts/) · [アーキテクチャと責任範囲](https://powercontext.oceanbase.io/en/docs/workflows/architecture/) · [プラグイン](https://powercontext.oceanbase.io/en/docs/develop/plugins/) -- [Python / HTTP / MCP インターフェース](https://powercontext.oceanbase.io/en/docs/develop/interfaces/) · [Server のデプロイ](https://powercontext.oceanbase.io/en/docs/operate/deploy-server/) +- [Python / HTTP / MCP インターフェース](https://powercontext.oceanbase.io/en/docs/develop/interfaces/) · [Server のデプロイ](https://powercontext.oceanbase.io/en/docs/operate/deploy-server/) · [Gateway のリクエストごとに Scope を選択する](docs/en/docs/operate/deploy-server.md#gateway-request-scope) - [トークン削減のベンチマーク](docs/benchmarks/token-savings/README.md) · [ブログ](https://powercontext.oceanbase.io/en/blog/) ## コミュニティ diff --git a/docs/en/docs/integrations/codex.md b/docs/en/docs/integrations/codex.md index 74decbd125..654d5a7c0d 100644 --- a/docs/en/docs/integrations/codex.md +++ b/docs/en/docs/integrations/codex.md @@ -412,9 +412,10 @@ default. Set: - `PC_GATEWAY_API_KEY` to the key that Codex sends as `PC_GATEWAY_KEY`. A non-loopback listener requires it. - `PC_GATEWAY_CORE_TOKEN` when Core enforces authentication. - `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. Running `scope_binding.py` without +- `PC_GATEWAY_DEFAULT_SCOPE` to the fallback Scope. To use the Scope this plugin resolves for the workspace, + run `scope_binding.py` without `--bind-scope`, as described in [Hand off the current work in one turn](#hand-off-the-current-work-in-one-turn), - prints that Scope. + to print that Scope. The gateway reads these settings at startup. For its authentication and injection settings, see [Deploy the Server](../operate/deploy-server.md#gateway-authentication-boundaries). A model request body through the @@ -423,8 +424,9 @@ gateway is limited to at most 1 MiB, so a long thread can be refused before it i With recall off, prompt-time context comes only from the gateway, with two differences: -- 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 Session or workspace. +- The gateway prepares and captures in the Scope selected by `X-PowerContext-Scope-ID` and uses the fallback Scope + when the header is absent. The plugin's Session and workspace bindings are independent. See + [Gateway request Scope](../operate/deploy-server.md#gateway-request-scope). - The gateway does not send the bootstrap receipt, so Memory already injected by [Session bootstrap context](#opt-in-to-session-bootstrap-context) can appear again in the gateway's context. diff --git a/docs/en/docs/integrations/opencode.md b/docs/en/docs/integrations/opencode.md index 7f94f86396..adbb53f768 100644 --- a/docs/en/docs/integrations/opencode.md +++ b/docs/en/docs/integrations/opencode.md @@ -99,9 +99,10 @@ 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 set -by `PC_GATEWAY_DEFAULT_SCOPE`, not in the Scope this plugin resolves for the Session or workspace. Set it to the same -Scope. +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). 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 diff --git a/docs/en/docs/operate/deploy-server.md b/docs/en/docs/operate/deploy-server.md index b13c8804ff..d1b8edf19f 100644 --- a/docs/en/docs/operate/deploy-server.md +++ b/docs/en/docs/operate/deploy-server.md @@ -183,6 +183,12 @@ Gemini disables Gateway context injection. Claude CLI accepts fresh text-only tu Do not route Core's own generation through automatic Gateway recall or capture without a separate recursion boundary. +### Gateway request Scope + +Send `X-PowerContext-Scope-ID` on `/gateway/v1/chat/completions` or `/gateway/v1/responses` to select the Scope for recall, both Core checks, and turn capture. Send one Scope ID of 1–256 visible ASCII characters, excluding commas. An invalid or repeated value returns HTTP 400 with `invalid_scope_id`. When the header is absent, the Gateway uses `PC_GATEWAY_DEFAULT_SCOPE` (defaults to `gateway:default`). Clients should send the same Scope on every request in a conversation. The Gateway partitions prepared context replay by Scope and conversation ID. + +Use a Gateway with clients trusted to select the Scopes available to its Core credential. Core checks access under that credential according to its configured access mode. A client or a trusted proxy can set the header on each request. + ### Gateway context injection When the gateway connects to the Core over UDS (`PC_GATEWAY_CORE_UDS`, the combined deployment), it injects prepared context by default into Chat and Responses requests that belong to a conversation. Within a conversation it prepares once per new user message and replays the exact result for the rest of that turn, such as an agent's tool loop. diff --git a/docs/zh/docs/integrations/codex.md b/docs/zh/docs/integrations/codex.md index c2d2ecbd1f..ec9a1af3e4 100644 --- a/docs/zh/docs/integrations/codex.md +++ b/docs/zh/docs/integrations/codex.md @@ -357,8 +357,8 @@ codex - `PC_GATEWAY_API_KEY` 设为 Codex 以 `PC_GATEWAY_KEY` 发送的密钥。监听非回环地址时必须设置。 - Core 启用鉴权时,设置 `PC_GATEWAY_CORE_TOKEN`。 - `PC_GATEWAY_SEDIMENT=on`,让 gateway 把每个完成的轮次采集为 Source。 -- `PC_GATEWAY_DEFAULT_SCOPE` 设为插件为该 workspace 解析的 Scope。按[一句话交接当前工作](#一句话交接当前工作)中的 - 说明,不带 `--bind-scope` 运行 `scope_binding.py`,即可打印这个 Scope。 +- `PC_GATEWAY_DEFAULT_SCOPE` 设为回退 Scope。若要使用插件为该 workspace 解析的 Scope,按 + [一句话交接当前工作](#一句话交接当前工作)中的说明,不带 `--bind-scope` 运行 `scope_binding.py`,即可打印这个 Scope。 gateway 在启动时读取这些设置。gateway 的鉴权和注入设置见[部署 Server](../operate/deploy-server.md#网关认证边界)。 经过 gateway 的模型请求正文最多 1 MiB,过长的 thread 可能在发送前被拒绝,见 @@ -366,8 +366,8 @@ gateway 在启动时读取这些设置。gateway 的鉴权和注入设置见[部 关闭召回后,提示词时上下文只来自 gateway,有两点不同: -- gateway 把所有对话都放在 `PC_GATEWAY_DEFAULT_SCOPE` 指定的同一个 Scope 中准备和采集,而不是插件为每个 Session - 或 workspace 解析的 Scope。 +- gateway 在 `X-PowerContext-Scope-ID` 选择的 Scope 中准备和采集,未发送该请求头时使用回退 Scope。插件的 + Session 和 workspace binding 独立生效。见 [Gateway 请求 Scope](../operate/deploy-server.md#gateway-请求-scope)。 - gateway 不发送启动上下文的 receipt,因此[启动上下文](#选择启用-session-启动上下文)已经注入的 Memory 可能再次出现在 gateway 的上下文中。 diff --git a/docs/zh/docs/integrations/opencode.md b/docs/zh/docs/integrations/opencode.md index 13392b7efc..7df6321de7 100644 --- a/docs/zh/docs/integrations/opencode.md +++ b/docs/zh/docs/integrations/opencode.md @@ -90,8 +90,9 @@ opencode gateway 会将该结果的文本替换为 `PowerContext plugin prepared context omitted by the gateway.`,并保留工具调用 ID。 请求和响应仍会经过 Core 的常规检查。 -关闭召回后,提示词时上下文只来自 gateway。gateway 在 `PC_GATEWAY_DEFAULT_SCOPE` 指定的 Scope 中准备和采集, -而不是插件为 Session 或 workspace 解析的 Scope。请把它设为同一个 Scope。 +关闭召回后,提示词时上下文只来自 gateway。gateway 在 `X-PowerContext-Scope-ID` 选择的 Scope 中准备和采集, +未发送该请求头时使用 `PC_GATEWAY_DEFAULT_SCOPE`。若要使用插件为 Session 或 workspace 解析的 Scope,请在请求头 +中指定该 Scope,或将其设为默认值。见 [Gateway 请求 Scope](../operate/deploy-server.md#gateway-请求-scope)。 OpenCode 在每个模型请求的 `x-opencode-session-id` 头中发送会话 ID。因此,通过 UDS 连接 Core 的 gateway 默认为 OpenCode 的每一轮准备并注入上下文;独立运行的 gateway 需要设置 `PC_GATEWAY_INJECTION=on`。见 diff --git a/docs/zh/docs/operate/deploy-server.md b/docs/zh/docs/operate/deploy-server.md index 1b1a2d7a3f..64f70c8ed8 100644 --- a/docs/zh/docs/operate/deploy-server.md +++ b/docs/zh/docs/operate/deploy-server.md @@ -185,6 +185,12 @@ Gemini 关闭 Gateway 上下文注入。Claude CLI 只接受新的单轮文本 不要在缺少独立递归边界时,让 Core 内部生成回经自动召回或捕获对话的 Gateway。 +### Gateway 请求 Scope + +向 `/gateway/v1/chat/completions` 或 `/gateway/v1/responses` 发送 `X-PowerContext-Scope-ID` 请求头,可选择召回、Core 两阶段检查和轮次采集使用的 Scope。请发送一个 Scope ID,由 1–256 个可见 ASCII 字符组成,不含逗号。请求头无效或重复时,返回 HTTP 400 和 `invalid_scope_id`。未发送该请求头时,Gateway 使用 `PC_GATEWAY_DEFAULT_SCOPE`(默认值为 `gateway:default`)。同一对话的每个请求应使用相同的 Scope。Gateway 按 Scope 和对话 ID 隔离已准备上下文的重放。 + +请只让受信任的客户端使用 Gateway,这些客户端可以选择其 Core 凭据可访问的 Scope。Core 按配置的访问模式检查该凭据的权限。客户端或受信任的代理可以在每个请求中设置此请求头。 + ### 网关上下文注入 网关通过 UDS 连接 Core(`PC_GATEWAY_CORE_UDS`,即同机组合部署)时,默认向属于某个会话的 Chat 和 Responses 请求注入准备好的上下文。在同一会话内,每条新的用户消息只准备一次,该回合的后续请求(例如 Agent 的工具循环)精确重放同一结果。 diff --git a/gateway/README.md b/gateway/README.md index 4fced48dd6..28b7bb9c66 100644 --- a/gateway/README.md +++ b/gateway/README.md @@ -22,6 +22,8 @@ Use `X-PowerContext-Conversation-ID` to identify a conversation. The Gateway als The Gateway classifies each request tail as `user_turn`, `tool_continuation`, `assistant_only` or `empty`, and records it in call evidence and debug logs. Responses items are classified by their own role and type rather than the verbatim carrier. Every kind other than `user_turn` reuses the turn's prepared block when a replay entry exists and otherwise skips preparation and replay. +Send `X-PowerContext-Scope-ID` on Chat or Responses requests to select the Scope for recall, both Core checks, and capture. Requests without the header use `PC_GATEWAY_DEFAULT_SCOPE`. Core applies its access rules using the Gateway's Core credentials. See [request Scope settings](../docs/en/docs/operate/deploy-server.md#gateway-request-scope). + Set `PC_GATEWAY_SEDIMENT=on` to capture completed user turns as Sources for later extraction. Capture excludes injected context and provider reasoning ciphertext. Tool continuations remain open until the final response. Long turns are split into Sources, and Core stores all parts in one batch. With a trusted conversation ID, captures share a turn digest and include a digest of the ordered normalized Source parts in their Source IDs. Distinct terminal records are stored independently; identical normalized parts are idempotent even when provider response IDs or usage change. Existing Sources remain unchanged, and a repeated capture under the former turn-only ID creates a new Source. Capture requires a Core that supports batch capture. Capture failure does not prevent response delivery. Blocked and degraded turns are not captured. Prefix extraction is enabled by default for supported upstreams on both model routes. Chat extraction requires a captured non-streaming turn with a single completed text reply and a conversation ID. `PC_GATEWAY_PREFIX_EXTRACTION=off` disables prefix extraction. With a subscription this applies to `codex` only, on a Core confirmed as non-enforcing; the extraction requests use the subscription account. Traffic of the other subscriptions uses normal extraction. Capture remains opt-in. Core also needs its gateway callback URL and generation model configured. With that URL configured, the Server defaults to `one_pass` unless a processing mode was explicitly supplied; `POWERCONTEXT_SERVER_RUNTIME_ATOMIC_MEMORY_PROCESSING_MODE=per_candidate` retains the previous mode. Both processing modes can reuse an eligible agent prefix when estimated cheaper, with normal extraction as the fallback. See [prefix extraction settings](../docs/en/docs/operate/deploy-server.md#memory-extraction-over-the-cached-prefix). diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index 1f8b62f261..a1b121774c 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -225,6 +225,10 @@ pub async fn extract( if let Some(rejected) = unauthorized(&state, &headers) { return rejected; } + let scope_id = match request_scope(&headers, &state.default_scope) { + Ok(scope_id) => scope_id, + Err(error) => return error.into_response(), + }; if request.instruction.trim().is_empty() || request.instruction.len() > MAX_EXTRACT_INSTRUCTION_BYTES { @@ -240,7 +244,7 @@ pub async fn extract( if !valid_continuation(&request.continuation) { return error(StatusCode::BAD_REQUEST, "invalid_continuation"); } - let Some(prefix) = state.executor.prefix(&request.handle, &state.default_scope) else { + let Some(prefix) = state.executor.prefix(&request.handle, scope_id) else { return error(StatusCode::NOT_FOUND, "prefix_unavailable"); }; if prefix.target_profile != state.upstream_profile { @@ -262,7 +266,7 @@ pub async fn extract( return subscription_auth_failed(); }; let call = ManagedCall { - scope_id: state.default_scope.clone(), + scope_id: scope_id.to_owned(), target_profile: state.upstream_profile.clone(), request: canonical, target_url: channel.target_url, @@ -511,6 +515,10 @@ async fn ingress_model( if let Some(rejected) = unauthorized(&state, &headers) { return rejected; } + let scope_id = match request_scope(&headers, &state.default_scope) { + Ok(scope_id) => scope_id, + Err(error) => return error.into_response(), + }; if state.max_body_bytes == 0 { return respond( @@ -704,7 +712,7 @@ async fn ingress_model( tracing::warn!("context injection skipped: no conversation identity"); } let call = ManagedCall { - scope_id: state.default_scope.clone(), + scope_id: scope_id.to_owned(), target_profile: state.upstream_profile.clone(), request: canonical, target_url, @@ -1110,6 +1118,26 @@ fn valid_id(value: &str) -> bool { !value.is_empty() && value.len() <= 256 && value.bytes().all(|b| b.is_ascii_graphic()) } +/// Select the Scope once for the request. Reject ambiguous or invalid explicit selections. +fn request_scope<'a>( + headers: &'a HeaderMap, + default_scope: &'a str, +) -> Result<&'a str, (StatusCode, Json)> { + let mut values = headers.get_all(SCOPE_ID_HEADER).into_iter(); + let Some(value) = values.next() else { + return Ok(default_scope); + }; + if let Ok(scope_id) = value.to_str() { + if valid_id(scope_id) && !scope_id.contains(',') && values.next().is_none() { + return Ok(scope_id); + } + } + Err(( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ "error": "invalid_scope_id" })), + )) +} + /// 请求带给上游的会话标识:请求的 `session-id` 头;没有时取请求体的 `prompt_cache_key`。Codex 给两者填同一个值, /// 不发这个头的 agent 往往仍带后者。值的规则与会话头相同,不合规则时按没有处理。 fn upstream_session(headers: &HeaderMap, body: &[u8]) -> Option { @@ -1126,6 +1154,7 @@ fn upstream_session(headers: &HeaderMap, body: &[u8]) -> Option { .filter(|key| valid_id(key)) } +const SCOPE_ID_HEADER: &str = "x-powercontext-scope-id"; const CONVERSATION_ID_HEADER: &str = "x-powercontext-conversation-id"; const CLAUDE_CODE_SESSION_HEADER: &str = "x-claude-code-session-id"; const CLAUDE_CODE_AGENT_HEADER: &str = "x-claude-code-agent-id"; diff --git a/gateway/crates/pc-gateway-app/tests/gateway_behaviors.rs b/gateway/crates/pc-gateway-app/tests/gateway_behaviors.rs index a4cf6b900c..e3d2db0ee4 100644 --- a/gateway/crates/pc-gateway-app/tests/gateway_behaviors.rs +++ b/gateway/crates/pc-gateway-app/tests/gateway_behaviors.rs @@ -1395,6 +1395,154 @@ async fn default_steering_and_overrides_reach_both_routes() { std::fs::remove_file(custom).unwrap(); } +#[tokio::test] +async fn request_scope_binds_recall_checks_and_capture() { + let requests = [ + ( + "responses", + "responses", + Some("project:alpha"), + "project:alpha", + ), + ( + "responses", + "responses", + Some("project:beta"), + "project:beta", + ), + ( + "chat/completions", + "chat", + Some("project:chat"), + "project:chat", + ), + ("responses", "responses", None, "gateway:fallback"), + ]; + let replies = requests + .iter() + .map(|(_, format, _, _)| Reply::fixture(&format!("fantasy_{format}_simple"), 0)) + .chain(std::iter::once(Reply::fixture( + "fantasy_responses_simple", + 0, + ))) + .collect(); + let gateway = Gateway::start_with_env( + replies, + None, + &[ + ("PC_GATEWAY_DEFAULT_SCOPE", "gateway:fallback"), + ("PC_GATEWAY_INJECTION", "on"), + ("PC_GATEWAY_SEDIMENT", "on"), + ("PC_GATEWAY_STEERING", "off"), + ], + true, + ) + .await; + + for (route, format, header, _) in requests { + let mut call = gateway + .client + .post(format!("{}/{route}", gateway.base)) + .bearer_auth("gateway-test-key") + .header("X-PowerContext-Conversation-ID", "shared-conversation") + .json(&request(format, "simple", false)); + if let Some(scope) = header { + call = call.header("X-PowerContext-Scope-ID", scope); + } + assert_eq!(call.send().await.unwrap().status(), 200); + } + + let expected = requests.map(|(_, _, _, scope)| scope); + let handle = { + let prepares = gateway.peers.prepares.lock().unwrap(); + let actual: Vec<_> = prepares + .iter() + .map(|value| value["scope_id"].as_str().unwrap()) + .collect(); + assert_eq!( + actual, expected, + "Core preparation must use the selected Scope" + ); + + let checks = gateway.peers.checks.lock().unwrap(); + let captures = gateway.peers.captures.lock().unwrap(); + let sent = gateway.peers.sent.lock().unwrap(); + assert_eq!(checks.len(), expected.len() * 2); + assert_eq!(captures.len(), expected.len()); + assert_eq!(sent.len(), expected.len()); + for (index, scope) in expected.into_iter().enumerate() { + let send = &checks[index * 2]; + let release = &checks[index * 2 + 1]; + assert_eq!(send["phase"], "before_send"); + assert_eq!(send["scope_id"], scope); + assert_eq!(release["phase"], "before_release"); + assert_eq!(release["scope_id"], scope); + assert_eq!(release["request_binding"], "test-before_send"); + assert_eq!(captures[index]["scope_id"], scope); + let (headers, body) = &sent[index]; + assert!(!headers.contains_key("X-PowerContext-Scope-ID")); + assert!(std::str::from_utf8(body) + .unwrap() + .contains(&format!("Prepared context {}", index + 1))); + assert!(!captures[index]["sources"][0]["content"] + .to_string() + .contains("Prepared context ")); + } + captures[0]["sources"][0]["metadata"]["prefix_handle"] + .as_str() + .unwrap() + .to_owned() + }; + + let model = || { + gateway + .client + .post(format!("{}/responses", gateway.base)) + .bearer_auth("gateway-test-key") + .json(&request("responses", "simple", false)) + }; + for invalid in [ + "", + "project alpha", + "project:alpha,project:beta", + &"a".repeat(257), + ] { + let rejected = model() + .header("X-PowerContext-Scope-ID", invalid) + .send() + .await + .unwrap(); + assert_eq!(rejected.status(), 400); + } + let duplicate = model() + .header("X-PowerContext-Scope-ID", "project:alpha") + .header("X-PowerContext-Scope-ID", "project:beta") + .send() + .await + .unwrap(); + assert_eq!(duplicate.status(), 400); + + let extract = json!({"handle": handle, "instruction": "Extract memory."}); + assert_eq!(gateway.post("extract", &extract).await.status(), 404); + for (scope, status) in [("project:beta", 404), ("project:alpha", 200)] { + let response = gateway + .client + .post(format!("{}/extract", gateway.base)) + .bearer_auth("gateway-test-key") + .header("X-PowerContext-Scope-ID", scope) + .json(&extract) + .send() + .await + .unwrap(); + assert_eq!(response.status(), status); + } + let checks = gateway.peers.checks.lock().unwrap(); + assert_eq!(checks.len(), expected.len() * 2 + 2); + assert_eq!(checks[checks.len() - 2]["scope_id"], "project:alpha"); + assert_eq!(checks[checks.len() - 1]["scope_id"], "project:alpha"); + assert_eq!(gateway.peers.sent.lock().unwrap().len(), expected.len() + 1); +} + #[tokio::test] async fn codex_omits_unsupported_options_before_send_check() { let credentials = diff --git a/src/powercontext/builtin/artifacts/atomic_memory/extraction.py b/src/powercontext/builtin/artifacts/atomic_memory/extraction.py index 1683be92a1..01d91cde59 100644 --- a/src/powercontext/builtin/artifacts/atomic_memory/extraction.py +++ b/src/powercontext/builtin/artifacts/atomic_memory/extraction.py @@ -22,6 +22,7 @@ from typing import TYPE_CHECKING, Any, Literal from pydantic import BaseModel, ConfigDict, Field, JsonValue, TypeAdapter, ValidationError +from pydantic.json_schema import SkipJsonSchema from powercontext._logging import log_safely from powercontext.artifacts import ArtifactRef @@ -143,6 +144,8 @@ class AtomicMemoryEvidence(BaseModel): class AtomicMemoryExtractionInput(BaseModel): model_config = ConfigDict(extra="forbid", frozen=True) evidence: tuple[AtomicMemoryEvidence, ...] + # Routing metadata for the Gateway callback, excluded from model input and its schema. + scope_id: SkipJsonSchema[str | None] = Field(default=None, exclude=True) class AtomicMemoryCandidate(BaseModel): diff --git a/src/powercontext/builtin/artifacts/atomic_memory/prefixed_extraction.py b/src/powercontext/builtin/artifacts/atomic_memory/prefixed_extraction.py index cf474322a9..f924ea289e 100644 --- a/src/powercontext/builtin/artifacts/atomic_memory/prefixed_extraction.py +++ b/src/powercontext/builtin/artifacts/atomic_memory/prefixed_extraction.py @@ -46,6 +46,7 @@ InferenceUsage, combine_inference_usage, ) +from powercontext.limits import MAX_SCOPE_ID_LENGTH if TYPE_CHECKING: from powercontext.builtin.artifacts.atomic_memory.extraction import ( @@ -128,6 +129,13 @@ def _count(value: object) -> TypeGuard[int]: return isinstance(value, int) and not isinstance(value, bool) and value >= 0 +def _scope_headers(scope_id: str | None) -> dict[str, str]: + # Legacy Scope IDs outside the header syntax can only have prefixes under the Gateway default. + if scope_id and len(scope_id) <= MAX_SCOPE_ID_LENGTH and all("!" <= ch <= "~" and ch != "," for ch in scope_id): + return {"X-PowerContext-Scope-ID": scope_id} + return {} + + @dataclass(frozen=True) class GatewayPrefixedExtractor: """Generate extraction output through the gateway's prefixed extraction route.""" @@ -160,7 +168,7 @@ async def generate(self, value: AtomicMemoryExtractionInput, /) -> GenerationRes if self.max_output_tokens is not None: body["max_output_tokens"] = self.max_output_tokens try: - response = await self.client.post(EXTRACT_PATH, json=body) + response = await self.client.post(EXTRACT_PATH, json=body, headers=_scope_headers(value.scope_id)) except httpx.HTTPError as error: raise PrefixedExtractionUnavailable("gateway_unavailable") from error payload = _json_object(response) @@ -237,6 +245,7 @@ class PrefixStart: cached_tokens: int uncached_tokens: int normal_input_tokens: int + scope_id: str | None = None def prefix_start(value: AtomicMemoryExtractionInput, normal_input_tokens: int) -> PrefixStart: @@ -248,7 +257,7 @@ def prefix_start(value: AtomicMemoryExtractionInput, normal_input_tokens: int) - tokens = _prefix_tokens(value.evidence[-1]) if tokens is None: raise PrefixedExtractionUnavailable("prefix_size_unknown") - return PrefixStart(handle, tokens[0], tokens[1], normal_input_tokens) + return PrefixStart(handle, tokens[0], tokens[1], normal_input_tokens, scope_id=value.scope_id) @dataclass(frozen=True) @@ -278,7 +287,7 @@ async def generate(self, value: ConversationTurn[Any], /) -> GenerationResult[Co detail = "the reply does not satisfy the turn" for _ in range(self.max_requests): try: - text, spent = await self._send(start.handle, instruction, messages[1:]) + text, spent = await self._send(start, instruction, messages[1:]) except PrefixedExtractionUnavailable as error: # The requests this turn already made stay accounted for. error.usage = usage @@ -317,15 +326,15 @@ def _require_cheaper(self, start: PrefixStart, instruction: str) -> None: raise PrefixedExtractionUnavailable("not_cheaper") async def _send( - self, handle: str, instruction: str, continuation: list[tuple[str, str]] + self, start: PrefixStart, instruction: str, continuation: list[tuple[str, str]] ) -> tuple[str, InferenceUsage]: - body: dict[str, Any] = {"handle": handle, "instruction": instruction} + body: dict[str, Any] = {"handle": start.handle, "instruction": instruction} if continuation: body["continuation"] = [{"role": role, "text": text} for role, text in continuation] if self.max_output_tokens is not None: body["max_output_tokens"] = self.max_output_tokens try: - response = await self.client.post(EXTRACT_PATH, json=body) + response = await self.client.post(EXTRACT_PATH, json=body, headers=_scope_headers(start.scope_id)) except httpx.HTTPError as error: raise PrefixedExtractionUnavailable("gateway_unavailable") from error payload = _json_object(response) diff --git a/src/powercontext/builtin/runtime/atomic_memory_processing.py b/src/powercontext/builtin/runtime/atomic_memory_processing.py index 1df1c72fd8..faebb3b1f4 100644 --- a/src/powercontext/builtin/runtime/atomic_memory_processing.py +++ b/src/powercontext/builtin/runtime/atomic_memory_processing.py @@ -511,7 +511,7 @@ async def _prepare(self, scope_id, eligible, pipeline, context): # noqa: C901 - await project_atomic_memory_evidence(item, self.sources, evidence_id=f"source:{item.journal_position}") for item in eligible ]) - extraction_input = AtomicMemoryExtractionInput(evidence=evidence) + extraction_input = AtomicMemoryExtractionInput(evidence=evidence, scope_id=scope_id) self._require_budget(pipeline, extraction_input, "atomic_memory.extract") extraction_prompt = current_prompt("atomic_memory.extract") prompt_refs = ( diff --git a/tests/builtin/artifacts/atomic_memory/test_prefixed_extraction.py b/tests/builtin/artifacts/atomic_memory/test_prefixed_extraction.py index c9c72ffc49..58a5a1a82f 100644 --- a/tests/builtin/artifacts/atomic_memory/test_prefixed_extraction.py +++ b/tests/builtin/artifacts/atomic_memory/test_prefixed_extraction.py @@ -67,6 +67,15 @@ } +def test_scope_routing_metadata_is_not_part_of_the_extraction_contract() -> None: + value = AtomicMemoryExtractionInput(evidence=(), scope_id="project") + + assert value.scope_id == "project" + assert value.model_dump(mode="json") == {"evidence": []} + assert set(AtomicMemoryExtractionInput.model_json_schema()["properties"]) == {"evidence"} + assert set(AtomicMemoryExtractionInput.model_json_schema(mode="serialization")["properties"]) == {"evidence"} + + class _Extractor: def __init__(self) -> None: self.calls = 0 @@ -100,12 +109,15 @@ def __init__(self, status: int, payload: object) -> None: self.status = status self.payload = payload self.requests: list[dict[str, object]] = [] + self.request_scopes: list[str | None] = [] + self.source_scope: str | None = None # Atomic Memory text in the Scope after the flush. self.memories: list[str] = [] def __call__(self, request: httpx.Request) -> httpx.Response: assert request.url.path == "/gateway/v1/extract" assert request.headers["authorization"] == "Bearer gateway-key" + self.request_scopes.append(request.headers.get("x-powercontext-scope-id")) self.requests.append(json.loads(request.content)) return httpx.Response(self.status, json=self.payload) @@ -133,7 +145,7 @@ def _flush(tmp_path, gateway: _Gateway, sources: list[dict[str, object]]) -> _Ex ), ) with TestClient(app) as test_client: - scope_id = test_client.get("/v1/scopes/default").json()["scope_id"] + scope_id = gateway.source_scope = _create_source_scope(test_client) for source in sources: captured = test_client.post("/v1/sources/content", json={"scope_id": scope_id, **source}) assert captured.status_code == 202, captured.text @@ -145,6 +157,14 @@ def _flush(tmp_path, gateway: _Gateway, sources: list[dict[str, object]]) -> _Ex return extractor +def _create_source_scope(client: TestClient) -> str: + response = client.post( + "/v1/scopes", json={"title": "Project", "summary": "Memory for this project", "idempotency_key": "project"} + ) + assert response.status_code == 201, response.text + return cast("str", response.json()["scope_id"]) + + def _turn( source_id: str, handle: str | None = "a" * 32, prefix_tokens: tuple[int, int] | None = (30_000, 50) ) -> dict[str, object]: @@ -164,6 +184,7 @@ def test_a_gateway_turn_is_extracted_over_its_prefix_without_resending_the_trans assert extractor.calls == 0 assert gateway.memories == [CANDIDATE["text"]] + assert gateway.request_scopes == [gateway.source_scope] (request,) = gateway.requests assert request["handle"] == "a" * 32 instruction = request["instruction"] @@ -339,7 +360,7 @@ def _flush_one_pass(tmp_path, gateway: _Gateway, source: dict[str, object], *fal ), ) with TestClient(app) as test_client: - scope_id = test_client.get("/v1/scopes/default").json()["scope_id"] + scope_id = gateway.source_scope = _create_source_scope(test_client) captured = test_client.post("/v1/sources/content", json={"scope_id": scope_id, **source}) assert captured.status_code == 202, captured.text flushed = test_client.post("/v1/memory/flush", json={"scope_id": scope_id}) @@ -366,6 +387,7 @@ def test_a_one_pass_window_continues_the_prefix_through_every_step(tmp_path, cap assert conversation.turns == [] assert gateway.memories == [CANDIDATE["text"]] + assert gateway.request_scopes == [gateway.source_scope, gateway.source_scope] first, second = gateway.requests instruction = first["instruction"] assert isinstance(instruction, str)