From da38ec86048da65f60f077706dfe059030bad9d5 Mon Sep 17 00:00:00 2001 From: jasper-yl Date: Sun, 22 Nov 2026 08:35:23 -0800 Subject: [PATCH 1/5] feat(gateway): extract over the cached prefix on a Codex subscription The extraction entry sent with the static upstream key and the plain Responses renderer, so prefix extraction was turned off for every OAuth subscription. It now uses the same upstream address, subscription rendering and credentials as the model entry. A Codex subscription request carries no max_output_tokens, which that endpoint rejects. Other subscriptions keep normal extraction. Co-Authored-By: Claude --- docs/en/docs/operate/deploy-server.md | 2 +- docs/zh/docs/operate/deploy-server.md | 2 +- gateway/crates/pc-gateway-app/src/ingress.rs | 200 +++++++++++++------ gateway/crates/pc-gateway-app/src/main.rs | 13 +- 4 files changed, 146 insertions(+), 71 deletions(-) diff --git a/docs/en/docs/operate/deploy-server.md b/docs/en/docs/operate/deploy-server.md index ae2658788e..1c1a2eceaa 100644 --- a/docs/en/docs/operate/deploy-server.md +++ b/docs/en/docs/operate/deploy-server.md @@ -221,7 +221,7 @@ These are per-body and per-class concurrency limits. They do not measure retaine ### Memory extraction over the cached prefix When the gateway runs on the same host as the Server, Atomic Memory extraction for a captured turn can reuse the -provider's prompt cache for the agent's conversation instead of sending the transcript again. OAuth subscription traffic uses normal extraction. Prefix extraction is off by default and needs both sides: +provider's prompt cache for the agent's conversation instead of sending the transcript again. With an OAuth subscription, only `codex` supports it: the extraction request goes to the subscription account like the agent's own requests and carries no output limit, which that endpoint rejects; traffic of the other subscriptions uses normal extraction. Prefix extraction is off by default and needs both sides: - **Gateway:** `PC_GATEWAY_PREFIX_EXTRACTION=on` together with capture (`PC_GATEWAY_SEDIMENT=on`). For a Responses conversation, the gateway keeps the exact request it sent and the response output of each turn's final response in diff --git a/docs/zh/docs/operate/deploy-server.md b/docs/zh/docs/operate/deploy-server.md index 82d150c086..13b0e7c35f 100644 --- a/docs/zh/docs/operate/deploy-server.md +++ b/docs/zh/docs/operate/deploy-server.md @@ -223,7 +223,7 @@ Rust Gateway 在启动时通过 `/v1/capabilities` 查询一次 `context_protect ### 复用缓存前缀抽取记忆 网关与 Server 部署在同一主机时,为一个已沉淀回合抽取 Atomic Memory 可以复用服务商为 Agent 会话写下的提示缓存, -而不必再次发送对话记录。OAuth 订阅流量使用普通抽取。前缀抽取默认关闭,需要两端同时开启: +而不必再次发送对话记录。使用 OAuth 订阅时,只有 `codex` 支持前缀抽取:抽取请求和 agent 自己的请求一样发往订阅账号,并且不带输出上限(该端点拒绝这个参数);其他订阅的流量使用普通抽取。前缀抽取默认关闭,需要两端同时开启: - **网关:** 设置 `PC_GATEWAY_PREFIX_EXTRACTION=on`,并开启沉淀(`PC_GATEWAY_SEDIMENT=on`)。对 Responses 会话,网关 在内存中保留每个回合终止响应对应的、实际发出的请求及其响应输出,最多 30 分钟、最多 64 个回合、总计最多 64 MiB, diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index d2bdc772e8..37b7e4127c 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -196,18 +196,26 @@ pub async fn extract( if prefix.target_profile != state.upstream_profile { return error(StatusCode::CONFLICT, "target_mismatch"); } - let canonical = prefixed_request(&prefix, &request) + // Codex 订阅端点拒绝 `max_output_tokens`,抽取请求不带输出上限。 + let output_limit = state.subscription.as_ref().map(|auth| auth.kind()) + != Some(pc_gateway_auth::Subscription::Codex); + let canonical = prefixed_request(&prefix, &request, output_limit) .and_then(|body| serde_json::from_value::(body).ok()) .and_then(|parsed| to_canonical_responses(parsed).ok()); let Some(canonical) = canonical else { return error(StatusCode::INTERNAL_SERVER_ERROR, "prefix_invalid"); }; + let Some((target_url, renderer, upstream_headers)) = + upstream_channel(&state, &Format::Responses).await + else { + return error(StatusCode::BAD_GATEWAY, "subscription_auth_failed"); + }; let call = ManagedCall { scope_id: state.default_scope.clone(), target_profile: state.upstream_profile.clone(), request: canonical, - target_url: state.upstream_responses.clone(), - headers: bearer_headers(&state.upstream_responses_api_key), + target_url, + headers: upstream_headers, degrade_policy: pc_gateway_core::DegradePolicy::Pause, inject_context: false, include_code: false, @@ -216,7 +224,6 @@ pub async fn extract( sediment: false, prepared_contexts: prefix.prepared_contexts.clone(), }; - let renderer = pc_gateway_protocol::GatewayRenderer::Responses(Default::default()); // 期限从连接开始接收请求时起算,读取请求体的时间也在其中。 let control = match owner { Some(axum::Extension(owner)) => owner.take_control(), @@ -247,10 +254,11 @@ pub async fn extract( /// 前缀请求:原始请求的 input 依次接上终止响应的输出(去掉 `id`/`status`,与客户端重放的形式一致)和 Core 的 /// 指令。其余字段(工具、`prompt_cache_key`、推理设置等)不变,只把 `tool_choice` 设为 `none`、改为非流式, -/// 并在 Core 给出时设置输出上限:这些字段不影响前缀缓存。 +/// 并在 Core 给出且上游接受(`output_limit`)时设置输出上限:这些字段不影响前缀缓存。 fn prefixed_request( prefix: &pc_gateway_core::PrefixEntry, request: &ExtractRequest, + output_limit: bool, ) -> Option { let mut body: serde_json::Value = serde_json::from_slice(&prefix.request_body).ok()?; let input = body.get_mut("input")?.as_array_mut()?; @@ -269,7 +277,7 @@ fn prefixed_request( })); body["tool_choice"] = "none".into(); body["stream"] = false.into(); - if let Some(limit) = request.max_output_tokens { + if let Some(limit) = request.max_output_tokens.filter(|_| output_limit) { body["max_output_tokens"] = limit.into(); } Some(body) @@ -472,10 +480,6 @@ async fn ingress_model( ) .into_response(); } - let inner_renderer = match format { - Format::Chat => pc_gateway_protocol::GatewayRenderer::Chat(Default::default()), - Format::Responses => pc_gateway_protocol::GatewayRenderer::Responses(Default::default()), - }; let subscription_kind = state.subscription.as_ref().map(|auth| auth.kind()); if subscription_kind == Some(pc_gateway_auth::Subscription::Codex) && matches!(format, Format::Chat) @@ -501,59 +505,13 @@ async fn ingress_model( ) .into_response(); } - let mut renderer = pc_gateway_protocol::SubscriptionRenderer { - inner: inner_renderer, - subscription: match subscription_kind { - Some(pc_gateway_auth::Subscription::Grok) => { - Some(pc_gateway_protocol::SubscriptionProtocol::Grok) - } - Some(pc_gateway_auth::Subscription::Codex) => { - Some(pc_gateway_protocol::SubscriptionProtocol::Codex) - } - Some(pc_gateway_auth::Subscription::Kimi) => { - Some(pc_gateway_protocol::SubscriptionProtocol::Kimi) - } - Some(pc_gateway_auth::Subscription::Claude) => { - Some(pc_gateway_protocol::SubscriptionProtocol::Claude) - } - _ => None, - }, - }; - let target_url = match format { - Format::Chat => state.upstream_chat.clone(), - Format::Responses => state.upstream_responses.clone(), - }; - let upstream_headers = if let Some(auth) = state.subscription.as_ref() { - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|v| v.as_secs() as i64) - .unwrap_or(0); - let result = if auth.kind() == pc_gateway_auth::Subscription::Gemini { - auth.gemini_context(&target_url, now) - .await - .map(|(headers, project)| { - renderer.subscription = - Some(pc_gateway_protocol::SubscriptionProtocol::Gemini { project }); - headers - }) - } else { - auth.headers(&target_url, now).await - }; - match result { - Ok(headers) => headers, - Err(_) => { - return ( - StatusCode::BAD_GATEWAY, - Json(serde_json::json!({"error":"subscription_auth_failed"})), - ) - .into_response() - } - } - } else { - bearer_headers(match format { - Format::Chat => &state.upstream_chat_api_key, - Format::Responses => &state.upstream_responses_api_key, - }) + let Some((target_url, renderer, upstream_headers)) = upstream_channel(&state, &format).await + else { + return ( + StatusCode::BAD_GATEWAY, + Json(serde_json::json!({"error":"subscription_auth_failed"})), + ) + .into_response(); }; let conversation = conversation_id(&headers, &format); @@ -917,6 +875,66 @@ const CLAUDE_CODE_AGENT_HEADER: &str = "x-claude-code-agent-id"; const OPENCODE_SESSION_HEADER: &str = "x-opencode-session-id"; const CODEX_THREAD_ID_HEADER: &str = "thread-id"; +/// 路由的上游地址、订阅改写和凭据。模型入口与前缀抽取共用,抽取请求因此以原请求的形式发往同一账号。 +/// 订阅凭据不可用时返回 `None`。 +async fn upstream_channel( + state: &AppState, + format: &Format, +) -> Option<( + String, + pc_gateway_protocol::SubscriptionRenderer, + Vec<(String, String)>, +)> { + let subscription_kind = state.subscription.as_ref().map(|auth| auth.kind()); + let mut renderer = pc_gateway_protocol::SubscriptionRenderer { + inner: match format { + Format::Chat => pc_gateway_protocol::GatewayRenderer::Chat(Default::default()), + Format::Responses => { + pc_gateway_protocol::GatewayRenderer::Responses(Default::default()) + } + }, + subscription: match subscription_kind { + Some(pc_gateway_auth::Subscription::Grok) => { + Some(pc_gateway_protocol::SubscriptionProtocol::Grok) + } + Some(pc_gateway_auth::Subscription::Codex) => { + Some(pc_gateway_protocol::SubscriptionProtocol::Codex) + } + Some(pc_gateway_auth::Subscription::Kimi) => { + Some(pc_gateway_protocol::SubscriptionProtocol::Kimi) + } + Some(pc_gateway_auth::Subscription::Claude) => { + Some(pc_gateway_protocol::SubscriptionProtocol::Claude) + } + _ => None, + }, + }; + let target_url = match format { + Format::Chat => state.upstream_chat.clone(), + Format::Responses => state.upstream_responses.clone(), + }; + let headers = if let Some(auth) = state.subscription.as_ref() { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|v| v.as_secs() as i64) + .unwrap_or(0); + if auth.kind() == pc_gateway_auth::Subscription::Gemini { + let (headers, project) = auth.gemini_context(&target_url, now).await.ok()?; + renderer.subscription = + Some(pc_gateway_protocol::SubscriptionProtocol::Gemini { project }); + headers + } else { + auth.headers(&target_url, now).await.ok()? + } + } else { + bearer_headers(match format { + Format::Chat => &state.upstream_chat_api_key, + Format::Responses => &state.upstream_responses_api_key, + }) + }; + Some((target_url, renderer, headers)) +} + fn bearer_headers(key: &str) -> Vec<(String, String)> { if key.is_empty() { Vec::new() @@ -1654,7 +1672,7 @@ pub(crate) mod tests { instruction: "Extract memories.".into(), max_output_tokens: Some(2000), }; - let extract = render_responses(&prefixed_request(&prefix, &request).unwrap()); + let extract = render_responses(&prefixed_request(&prefix, &request, true).unwrap()); let before = sent["input"].as_array().unwrap(); let after = extract["input"].as_array().unwrap(); @@ -1689,6 +1707,60 @@ pub(crate) mod tests { assert_eq!(rest(&extract), rest(&sent)); } + #[test] + fn a_codex_subscription_extraction_request_keeps_the_subscription_form() { + use pc_gateway_protocol::WireRenderer; + let renderer = pc_gateway_protocol::SubscriptionRenderer { + inner: pc_gateway_protocol::GatewayRenderer::Responses(Default::default()), + subscription: Some(pc_gateway_protocol::SubscriptionProtocol::Codex), + }; + let render = |body: &serde_json::Value| -> serde_json::Value { + let parsed: OpenAiResponsesRequest = serde_json::from_value(body.clone()).unwrap(); + let payload = renderer + .render(&to_canonical_responses(parsed).unwrap(), None) + .unwrap(); + serde_json::from_slice(&payload.bytes).unwrap() + }; + let sent = render(&codex_request(true)); + let prefix = pc_gateway_core::PrefixEntry { + scope_id: "s".into(), + target_profile: "codex".into(), + conversation_id: "codex-thread:a".into(), + request_body: serde_json::to_vec(&sent).unwrap().into(), + response_output: Vec::new(), + prepared_contexts: Vec::new(), + }; + let request = ExtractRequest { + handle: "h".into(), + instruction: "Extract memories.".into(), + max_output_tokens: Some(2000), + }; + // 订阅端点拒绝输出上限;带着它时请求在发送前就被渲染器拒绝。 + let parsed: OpenAiResponsesRequest = + serde_json::from_value(prefixed_request(&prefix, &request, true).unwrap()).unwrap(); + assert!(renderer + .render(&to_canonical_responses(parsed).unwrap(), None) + .is_err()); + + let extract = render(&prefixed_request(&prefix, &request, false).unwrap()); + assert!(extract.get("max_output_tokens").is_none()); + assert_eq!(extract["stream"], true); + assert_eq!(extract["tool_choice"], "none"); + let rest = |body: &serde_json::Value| { + let mut fields = body.as_object().unwrap().clone(); + for key in ["input", "tool_choice"] { + fields.remove(key); + } + fields + }; + assert_eq!(rest(&extract), rest(&sent)); + let before = sent["input"].as_array().unwrap(); + assert_eq!( + extract["input"].as_array().unwrap()[..before.len()], + before[..] + ); + } + #[test] fn steering_is_rendered_after_the_base_prompt_and_nothing_else_changes() { let client = codex_request(false); diff --git a/gateway/crates/pc-gateway-app/src/main.rs b/gateway/crates/pc-gateway-app/src/main.rs index 39744eb87d..53662106f0 100644 --- a/gateway/crates/pc-gateway-app/src/main.rs +++ b/gateway/crates/pc-gateway-app/src/main.rs @@ -292,11 +292,14 @@ async fn main() { ), sediment, steering, - prefix_extraction: subscription_kind.is_none() - && matches!( - std::env::var("PC_GATEWAY_PREFIX_EXTRACTION").as_deref(), - Ok("on") - ), + // 订阅通道里只有 Codex 支持前缀抽取。 + prefix_extraction: matches!( + subscription_kind, + None | Some(pc_gateway_auth::Subscription::Codex) + ) && matches!( + std::env::var("PC_GATEWAY_PREFIX_EXTRACTION").as_deref(), + Ok("on") + ), default_scope: std::env::var("PC_GATEWAY_DEFAULT_SCOPE") .unwrap_or_else(|_| "gateway:default".into()), max_body_bytes: model_body_bytes, From 2d79a54cc526cbaa1bd41d05361a85849b60121a Mon Sep 17 00:00:00 2001 From: jasper-yl Date: Sun, 22 Nov 2026 11:36:26 -0800 Subject: [PATCH 2/5] fix(gateway): tighten prefix extraction on a Codex subscription - A failed or cancelled terminal response arrives as HTTP 200 once the subscription stream is collapsed; the extraction entry now returns the provider error instead of an empty reply. - A requested output limit is refused with output_limit_unsupported instead of being dropped, since the Codex endpoint cannot enforce it. - Prefix extraction on Codex is enabled only when Core is confirmed as non-enforcing, because an enforcing Core withholds every request that replays encrypted reasoning; the gateway logs when the setting is not in effect. - Core maps the two new gateway refusals to output_limit_unsupported and credentials_unavailable. - The channel returns a named type and the auth error; tests cover the credentials and form of the extraction channel. - gateway/README.md and SUBSCRIPTIONS.md describe the Codex case. Co-Authored-By: Claude --- docs/en/docs/operate/deploy-server.md | 2 +- docs/en/docs/operate/observability.md | 2 +- docs/zh/docs/operate/deploy-server.md | 2 +- docs/zh/docs/operate/observability.md | 2 +- gateway/README.md | 2 +- gateway/SUBSCRIPTIONS.md | 2 + gateway/crates/pc-gateway-app/src/ingress.rs | 269 ++++++++++++++---- gateway/crates/pc-gateway-app/src/main.rs | 26 +- .../atomic_memory/prefixed_extraction.py | 2 + .../atomic_memory/test_prefixed_extraction.py | 3 + 10 files changed, 243 insertions(+), 69 deletions(-) diff --git a/docs/en/docs/operate/deploy-server.md b/docs/en/docs/operate/deploy-server.md index 1c1a2eceaa..a7cf7da497 100644 --- a/docs/en/docs/operate/deploy-server.md +++ b/docs/en/docs/operate/deploy-server.md @@ -221,7 +221,7 @@ These are per-body and per-class concurrency limits. They do not measure retaine ### Memory extraction over the cached prefix When the gateway runs on the same host as the Server, Atomic Memory extraction for a captured turn can reuse the -provider's prompt cache for the agent's conversation instead of sending the transcript again. With an OAuth subscription, only `codex` supports it: the extraction request goes to the subscription account like the agent's own requests and carries no output limit, which that endpoint rejects; traffic of the other subscriptions uses normal extraction. Prefix extraction is off by default and needs both sides: +provider's prompt cache for the agent's conversation instead of sending the transcript again. With an OAuth subscription, only `codex` supports it, and only when the Server is not enforcing: the extraction request goes out with the subscription's credentials like the agent's own requests, counts against that account's usage limits, and cannot carry an output limit, which that endpoint rejects. Traffic of the other subscriptions uses normal extraction. Prefix extraction is off by default and needs both sides: - **Gateway:** `PC_GATEWAY_PREFIX_EXTRACTION=on` together with capture (`PC_GATEWAY_SEDIMENT=on`). For a Responses conversation, the gateway keeps the exact request it sent and the response output of each turn's final response in diff --git a/docs/en/docs/operate/observability.md b/docs/en/docs/operate/observability.md index 84eb99df41..c14d55c05e 100644 --- a/docs/en/docs/operate/observability.md +++ b/docs/en/docs/operate/observability.md @@ -153,7 +153,7 @@ With prefixed extraction configured (`POWERCONTEXT_SERVER_INFERENCE_PREFIX_EXTRA `atomic_memory.prefixed_extraction` event with `operation` `atomic_memory.extract` and `unit` `inference` reports each attempt for a window that holds one gateway turn with a prefix handle. `outcome` is `success` when the reply over the cached prefix was used, or `fallback` when normal extraction ran instead; `fallback_reason` is then one of -`not_cheaper`, `prefix_size_unknown`, `prefix_unavailable`, `target_mismatch`, `disabled`, `invalid_instruction`, `check_rejected`, `gateway_unavailable`, +`not_cheaper`, `prefix_size_unknown`, `prefix_unavailable`, `target_mismatch`, `disabled`, `invalid_instruction`, `output_limit_unsupported`, `credentials_unavailable`, `check_rejected`, `gateway_unavailable`, `provider_error`, `gateway_error`, or `invalid_output`. Windows without such a turn emit no event. The event carries no handle, prompt, or response content. With the `one_pass` processing mode (`POWERCONTEXT_SERVER_RUNTIME_ATOMIC_MEMORY_PROCESSING_MODE`), an INFO diff --git a/docs/zh/docs/operate/deploy-server.md b/docs/zh/docs/operate/deploy-server.md index 13b0e7c35f..8434118a8d 100644 --- a/docs/zh/docs/operate/deploy-server.md +++ b/docs/zh/docs/operate/deploy-server.md @@ -223,7 +223,7 @@ Rust Gateway 在启动时通过 `/v1/capabilities` 查询一次 `context_protect ### 复用缓存前缀抽取记忆 网关与 Server 部署在同一主机时,为一个已沉淀回合抽取 Atomic Memory 可以复用服务商为 Agent 会话写下的提示缓存, -而不必再次发送对话记录。使用 OAuth 订阅时,只有 `codex` 支持前缀抽取:抽取请求和 agent 自己的请求一样发往订阅账号,并且不带输出上限(该端点拒绝这个参数);其他订阅的流量使用普通抽取。前缀抽取默认关闭,需要两端同时开启: +而不必再次发送对话记录。使用 OAuth 订阅时,只有 `codex` 支持前缀抽取,并且 Server 不能是 enforcing:抽取请求和 agent 自己的请求一样用订阅的凭据发出,计入该账号的用量限额,并且不能带输出上限(该端点拒绝这个参数)。其他订阅的流量使用普通抽取。前缀抽取默认关闭,需要两端同时开启: - **网关:** 设置 `PC_GATEWAY_PREFIX_EXTRACTION=on`,并开启沉淀(`PC_GATEWAY_SEDIMENT=on`)。对 Responses 会话,网关 在内存中保留每个回合终止响应对应的、实际发出的请求及其响应输出,最多 30 分钟、最多 64 个回合、总计最多 64 MiB, diff --git a/docs/zh/docs/operate/observability.md b/docs/zh/docs/operate/observability.md index dafb443a24..102e209f0f 100644 --- a/docs/zh/docs/operate/observability.md +++ b/docs/zh/docs/operate/observability.md @@ -144,7 +144,7 @@ prompt 或响应内容,也不改变本次请求的结果。 配置了前缀抽取(`POWERCONTEXT_SERVER_INFERENCE_PREFIX_EXTRACTION_GATEWAY_URL`)时,对含一个带前缀句柄的网关回合的 窗口,每次尝试输出一条 INFO 级别的 `atomic_memory.prefixed_extraction` 事件,`operation` 为 `atomic_memory.extract`, `unit` 为 `inference`。使用了基于缓存前缀的回复时 `outcome` 为 `success`;改用普通抽取时为 `fallback`,此时 -`fallback_reason` 取 `not_cheaper`、`prefix_size_unknown`、`prefix_unavailable`、`target_mismatch`、`disabled`、`invalid_instruction`、`check_rejected`、 +`fallback_reason` 取 `not_cheaper`、`prefix_size_unknown`、`prefix_unavailable`、`target_mismatch`、`disabled`、`invalid_instruction`、`output_limit_unsupported`、`credentials_unavailable`、`check_rejected`、 `gateway_unavailable`、`provider_error`、`gateway_error` 或 `invalid_output` 之一。不含这种回合的窗口不输出该事件。该事件不携带句柄、 prompt 或响应内容。 处理模式为 `one_pass`(`POWERCONTEXT_SERVER_RUNTIME_ATOMIC_MEMORY_PROCESSING_MODE`)时,每个 Source 窗口输出一条 INFO 级别的 diff --git a/gateway/README.md b/gateway/README.md index 2d6d5d762b..e2a00e7d68 100644 --- a/gateway/README.md +++ b/gateway/README.md @@ -20,7 +20,7 @@ Use `X-PowerContext-Conversation-ID` to identify a conversation. The Gateway als 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. -For a Responses upstream configured without a subscription, `PC_GATEWAY_PREFIX_EXTRACTION=on` lets Core reuse the provider's cached prefix for memory extraction. Subscription traffic uses normal extraction. See [prefix extraction settings](../docs/en/docs/operate/deploy-server.md#memory-extraction-over-the-cached-prefix). +For a Responses upstream, `PC_GATEWAY_PREFIX_EXTRACTION=on` lets Core reuse the provider's cached prefix for memory 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. See [prefix extraction settings](../docs/en/docs/operate/deploy-server.md#memory-extraction-over-the-cached-prefix). ## Run diff --git a/gateway/SUBSCRIPTIONS.md b/gateway/SUBSCRIPTIONS.md index 78ad11ab6f..2651e3dfa8 100644 --- a/gateway/SUBSCRIPTIONS.md +++ b/gateway/SUBSCRIPTIONS.md @@ -62,6 +62,8 @@ Core must approve the final target, model and protocol through `PC_GATEWAY_UPSTR Codex's endpoint rejects `max_output_tokens`. A Core policy requiring that explicit output cap withholds the request with `output_limit_required`; a configured profile limit cannot make the upstream enforce an unsupported parameter. +With `PC_GATEWAY_PREFIX_EXTRACTION=on`, memory extraction over the cached prefix is available on `codex` when Core is confirmed as non-enforcing at startup. Each extraction request is sent with the credentials in the Codex login at that moment, counts against that account's usage limits, and has no output limit; a request that asks for one is refused with `output_limit_unsupported`, and Core uses normal extraction. See [prefix extraction settings](../docs/en/docs/operate/deploy-server.md#memory-extraction-over-the-cached-prefix). + Gemini maps Chat output limits to `request.generationConfig.maxOutputTokens`. Responses containing thought signatures are withheld; signed tool continuations are unsupported. Plain thought text is retained in the checked result. Claude checks cannot inspect the CLI's internal HTTP calls, retries or token budget, so enforcing Core always withholds this execution path, including after a runtime policy change. Do not route Core's own generation calls back through a Gateway with automatic recall or capture enabled without a separate recursion boundary. These global features cannot distinguish internal generation from ordinary clients. diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index 37b7e4127c..09cd96f791 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -190,32 +190,34 @@ pub async fn extract( { return error(StatusCode::BAD_REQUEST, "invalid_instruction"); } + // Codex 订阅端点拒绝 `max_output_tokens`:调用方要求的上限无法生效,明确拒绝而不是忽略它。 + if request.max_output_tokens.is_some() + && state.subscription.as_ref().map(|auth| auth.kind()) + == Some(pc_gateway_auth::Subscription::Codex) + { + return error(StatusCode::BAD_REQUEST, "output_limit_unsupported"); + } let Some(prefix) = state.executor.prefix(&request.handle, &state.default_scope) else { return error(StatusCode::NOT_FOUND, "prefix_unavailable"); }; if prefix.target_profile != state.upstream_profile { return error(StatusCode::CONFLICT, "target_mismatch"); } - // Codex 订阅端点拒绝 `max_output_tokens`,抽取请求不带输出上限。 - let output_limit = state.subscription.as_ref().map(|auth| auth.kind()) - != Some(pc_gateway_auth::Subscription::Codex); - let canonical = prefixed_request(&prefix, &request, output_limit) + let canonical = prefixed_request(&prefix, &request) .and_then(|body| serde_json::from_value::(body).ok()) .and_then(|parsed| to_canonical_responses(parsed).ok()); let Some(canonical) = canonical else { return error(StatusCode::INTERNAL_SERVER_ERROR, "prefix_invalid"); }; - let Some((target_url, renderer, upstream_headers)) = - upstream_channel(&state, &Format::Responses).await - else { - return error(StatusCode::BAD_GATEWAY, "subscription_auth_failed"); + let Ok(channel) = upstream_channel(&state, &Format::Responses).await else { + return subscription_auth_failed(); }; let call = ManagedCall { scope_id: state.default_scope.clone(), target_profile: state.upstream_profile.clone(), request: canonical, - target_url, - headers: upstream_headers, + target_url: channel.target_url, + headers: channel.headers, degrade_policy: pc_gateway_core::DegradePolicy::Pause, inject_context: false, include_code: false, @@ -234,17 +236,15 @@ pub async fn extract( }; match state .executor - .run(control, call, &renderer, state.evidence.as_ref()) + .run(control, call, &channel.renderer, state.evidence.as_ref()) .await { ManagedOutcome::Released { status, body, .. } if (200..300).contains(&status) => { match serde_json::from_slice::(&body) { - Ok(response) => Json(serde_json::json!({ - "text": responses_output_text(&response), - "usage": response.get("usage").cloned().unwrap_or(serde_json::Value::Null), - "model": response.get("model").cloned().unwrap_or(serde_json::Value::Null), - })) - .into_response(), + Ok(response) => match extraction_reply(&response) { + Ok(reply) => Json(reply).into_response(), + Err(failure) => (StatusCode::BAD_GATEWAY, Json(failure)).into_response(), + }, Err(_) => error(StatusCode::BAD_GATEWAY, "invalid_upstream_response"), } } @@ -252,13 +252,30 @@ pub async fn extract( } } +/// 抽取的回复。订阅通道把流折叠成终止响应,失败的响应因此也以 200 到达:按响应状态区分,失败时返回供应商的 +/// 错误对象,与上游直接以错误状态码返回时的形式一致。 +fn extraction_reply(response: &serde_json::Value) -> Result { + let error = response.get("error").filter(|error| !error.is_null()); + if error.is_some() || matches!(response["status"].as_str(), Some("failed" | "cancelled")) { + let error = error + .filter(|error| error.is_object()) + .cloned() + .unwrap_or_else(|| serde_json::json!({"code": "response_failed"})); + return Err(serde_json::json!({ "error": error })); + } + Ok(serde_json::json!({ + "text": responses_output_text(response), + "usage": response.get("usage").cloned().unwrap_or(serde_json::Value::Null), + "model": response.get("model").cloned().unwrap_or(serde_json::Value::Null), + })) +} + /// 前缀请求:原始请求的 input 依次接上终止响应的输出(去掉 `id`/`status`,与客户端重放的形式一致)和 Core 的 /// 指令。其余字段(工具、`prompt_cache_key`、推理设置等)不变,只把 `tool_choice` 设为 `none`、改为非流式, -/// 并在 Core 给出且上游接受(`output_limit`)时设置输出上限:这些字段不影响前缀缓存。 +/// 并在 Core 给出时设置输出上限:这些字段不影响前缀缓存。 fn prefixed_request( prefix: &pc_gateway_core::PrefixEntry, request: &ExtractRequest, - output_limit: bool, ) -> Option { let mut body: serde_json::Value = serde_json::from_slice(&prefix.request_body).ok()?; let input = body.get_mut("input")?.as_array_mut()?; @@ -277,7 +294,7 @@ fn prefixed_request( })); body["tool_choice"] = "none".into(); body["stream"] = false.into(); - if let Some(limit) = request.max_output_tokens.filter(|_| output_limit) { + if let Some(limit) = request.max_output_tokens { body["max_output_tokens"] = limit.into(); } Some(body) @@ -505,13 +522,13 @@ async fn ingress_model( ) .into_response(); } - let Some((target_url, renderer, upstream_headers)) = upstream_channel(&state, &format).await + let Ok(UpstreamChannel { + target_url, + renderer, + headers: upstream_headers, + }) = upstream_channel(&state, &format).await else { - return ( - StatusCode::BAD_GATEWAY, - Json(serde_json::json!({"error":"subscription_auth_failed"})), - ) - .into_response(); + return subscription_auth_failed(); }; let conversation = conversation_id(&headers, &format); @@ -875,16 +892,17 @@ const CLAUDE_CODE_AGENT_HEADER: &str = "x-claude-code-agent-id"; const OPENCODE_SESSION_HEADER: &str = "x-opencode-session-id"; const CODEX_THREAD_ID_HEADER: &str = "thread-id"; -/// 路由的上游地址、订阅改写和凭据。模型入口与前缀抽取共用,抽取请求因此以原请求的形式发往同一账号。 -/// 订阅凭据不可用时返回 `None`。 +/// 路由的上游地址、订阅改写和凭据。模型入口与前缀抽取共用,抽取请求因此以原请求的形式和凭据发出。 +struct UpstreamChannel { + target_url: String, + renderer: pc_gateway_protocol::SubscriptionRenderer, + headers: Vec<(String, String)>, +} + async fn upstream_channel( state: &AppState, format: &Format, -) -> Option<( - String, - pc_gateway_protocol::SubscriptionRenderer, - Vec<(String, String)>, -)> { +) -> Result { let subscription_kind = state.subscription.as_ref().map(|auth| auth.kind()); let mut renderer = pc_gateway_protocol::SubscriptionRenderer { inner: match format { @@ -919,12 +937,12 @@ async fn upstream_channel( .map(|v| v.as_secs() as i64) .unwrap_or(0); if auth.kind() == pc_gateway_auth::Subscription::Gemini { - let (headers, project) = auth.gemini_context(&target_url, now).await.ok()?; + let (headers, project) = auth.gemini_context(&target_url, now).await?; renderer.subscription = Some(pc_gateway_protocol::SubscriptionProtocol::Gemini { project }); headers } else { - auth.headers(&target_url, now).await.ok()? + auth.headers(&target_url, now).await? } } else { bearer_headers(match format { @@ -932,7 +950,19 @@ async fn upstream_channel( Format::Responses => &state.upstream_responses_api_key, }) }; - Some((target_url, renderer, headers)) + Ok(UpstreamChannel { + target_url, + renderer, + headers, + }) +} + +fn subscription_auth_failed() -> Response { + ( + StatusCode::BAD_GATEWAY, + Json(serde_json::json!({"error":"subscription_auth_failed"})), + ) + .into_response() } fn bearer_headers(key: &str) -> Vec<(String, String)> { @@ -1672,7 +1702,7 @@ pub(crate) mod tests { instruction: "Extract memories.".into(), max_output_tokens: Some(2000), }; - let extract = render_responses(&prefixed_request(&prefix, &request, true).unwrap()); + let extract = render_responses(&prefixed_request(&prefix, &request).unwrap()); let before = sent["input"].as_array().unwrap(); let after = extract["input"].as_array().unwrap(); @@ -1707,21 +1737,90 @@ pub(crate) mod tests { assert_eq!(rest(&extract), rest(&sent)); } - #[test] - fn a_codex_subscription_extraction_request_keeps_the_subscription_form() { + /// 使用 Codex 订阅的网关状态;凭据文件是合成的,测试不发出网络请求。 + fn codex_subscription_state(name: &str) -> (Arc, std::path::PathBuf) { + use pc_gateway_core::{Executor, HttpGateClient}; + let path = std::env::temp_dir().join(format!( + "pc-gateway-codex-auth-{}-{name}.json", + std::process::id() + )); + std::fs::write( + &path, + r#"{"auth_mode":"chatgpt","tokens":{"access_token":"SYNTHETIC_SUBSCRIPTION_TOKEN","account_id":"acct-1"}}"#, + ) + .unwrap(); + let state = Arc::new(AppState { + executor: Arc::new(Executor::new( + crate::link::CoreLink::Http(HttpGateClient::with_token("http://127.0.0.1:9", None)), + pc_gateway_transport::GatewayTransport::new( + pc_gateway_transport::ReqwestTransport::new(std::time::Duration::from_secs(1)), + ), + std::num::NonZeroU32::new(1).unwrap(), + )), + evidence: Arc::new(pc_gateway_evidence::NoopEvidenceSink), + upstream_profile: "test".into(), + upstream_chat: String::new(), + upstream_responses: "https://chatgpt.com/backend-api/codex/responses".into(), + upstream_chat_api_key: String::new(), + upstream_responses_api_key: "SYNTHETIC_STATIC_KEY".into(), + subscription: Some( + pc_gateway_auth::SubscriptionAuth::new( + pc_gateway_auth::Subscription::Codex, + path.clone(), + ) + .unwrap(), + ), + api_key: None, + degrade: pc_gateway_core::DegradePolicy::Pause, + injection: Injection::Off, + inject_responses: false, + inject_code: false, + sediment: false, + steering: None, + prefix_extraction: true, + default_scope: "test".into(), + max_body_bytes: 1024 * 1024, + degradation_allowed: true, + }); + (state, path) + } + + #[tokio::test] + async fn the_extraction_channel_of_a_codex_subscription_carries_its_credentials_and_form() { use pc_gateway_protocol::WireRenderer; - let renderer = pc_gateway_protocol::SubscriptionRenderer { - inner: pc_gateway_protocol::GatewayRenderer::Responses(Default::default()), - subscription: Some(pc_gateway_protocol::SubscriptionProtocol::Codex), + let (state, path) = codex_subscription_state("channel"); + let channel = upstream_channel(&state, &Format::Responses).await; + std::fs::remove_file(&path).unwrap(); + let channel = channel.unwrap(); + + assert_eq!( + channel.target_url, + "https://chatgpt.com/backend-api/codex/responses" + ); + let header = |name: &str| { + channel + .headers + .iter() + .find(|(key, _)| key.eq_ignore_ascii_case(name)) + .map(|(_, value)| value.as_str()) }; - let render = |body: &serde_json::Value| -> serde_json::Value { - let parsed: OpenAiResponsesRequest = serde_json::from_value(body.clone()).unwrap(); - let payload = renderer + // 订阅的令牌和账号,而不是静态的上游 key。 + assert_eq!( + header("authorization"), + Some("Bearer SYNTHETIC_SUBSCRIPTION_TOKEN") + ); + assert_eq!(header("chatgpt-account-id"), Some("acct-1")); + + // 抽取请求以订阅的形式发出,其余字段与保留的请求一致。 + let render = |body: serde_json::Value| -> serde_json::Value { + let parsed: OpenAiResponsesRequest = serde_json::from_value(body).unwrap(); + let payload = channel + .renderer .render(&to_canonical_responses(parsed).unwrap(), None) .unwrap(); serde_json::from_slice(&payload.bytes).unwrap() }; - let sent = render(&codex_request(true)); + let sent = render(codex_request(true)); let prefix = pc_gateway_core::PrefixEntry { scope_id: "s".into(), target_profile: "codex".into(), @@ -1733,18 +1832,11 @@ pub(crate) mod tests { let request = ExtractRequest { handle: "h".into(), instruction: "Extract memories.".into(), - max_output_tokens: Some(2000), + max_output_tokens: None, }; - // 订阅端点拒绝输出上限;带着它时请求在发送前就被渲染器拒绝。 - let parsed: OpenAiResponsesRequest = - serde_json::from_value(prefixed_request(&prefix, &request, true).unwrap()).unwrap(); - assert!(renderer - .render(&to_canonical_responses(parsed).unwrap(), None) - .is_err()); - - let extract = render(&prefixed_request(&prefix, &request, false).unwrap()); - assert!(extract.get("max_output_tokens").is_none()); + let extract = render(prefixed_request(&prefix, &request).unwrap()); assert_eq!(extract["stream"], true); + assert_eq!(extract["store"], false); assert_eq!(extract["tool_choice"], "none"); let rest = |body: &serde_json::Value| { let mut fields = body.as_object().unwrap().clone(); @@ -1761,6 +1853,71 @@ pub(crate) mod tests { ); } + #[tokio::test] + async fn unreadable_subscription_credentials_fail_the_extraction_channel() { + let (state, path) = codex_subscription_state("missing"); + std::fs::remove_file(&path).unwrap(); + assert!(upstream_channel(&state, &Format::Responses).await.is_err()); + } + + #[tokio::test] + async fn a_codex_subscription_rejects_an_extraction_output_limit() { + use tower::ServiceExt; + let (state, path) = codex_subscription_state("limit"); + std::fs::remove_file(&path).unwrap(); + let router = crate::router(state, crate::proxy::ProxyState::from_env()); + let response = router + .oneshot( + Request::builder() + .method("POST") + .uri("/gateway/v1/extract") + .header(header::CONTENT_TYPE, "application/json") + .body(axum::body::Body::from( + r#"{"handle":"h","instruction":"Extract memories.","max_output_tokens":2000}"#, + )) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + let body = axum::body::to_bytes(response.into_body(), 4096) + .await + .unwrap(); + let body: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(body["error"], "output_limit_unsupported"); + } + + #[test] + fn a_failed_terminal_response_is_an_extraction_error() { + let completed = serde_json::json!({ + "status": "completed", "model": "m", "usage": {"input_tokens": 3}, + "output": [{"type": "message", "role": "assistant", + "content": [{"type": "output_text", "text": "{}"}]}] + }); + assert_eq!( + extraction_reply(&completed), + Ok(serde_json::json!({"text": "{}", "usage": {"input_tokens": 3}, "model": "m"})) + ); + // 被截断的响应仍交给 Core 校验,与上游以 200 返回它时一致。 + let incomplete = serde_json::json!({"status": "incomplete", "output": [], + "incomplete_details": {"reason": "max_output_tokens"}}); + assert!(extraction_reply(&incomplete).is_ok()); + + let failed = serde_json::json!({"status": "failed", "output": [], + "error": {"code": "server_error", "message": "upstream failed"}}); + assert_eq!( + extraction_reply(&failed), + Err( + serde_json::json!({"error": {"code": "server_error", "message": "upstream failed"}}) + ) + ); + let cancelled = serde_json::json!({"status": "cancelled", "output": []}); + assert_eq!( + extraction_reply(&cancelled), + Err(serde_json::json!({"error": {"code": "response_failed"}})) + ); + } + #[test] fn steering_is_rendered_after_the_base_prompt_and_nothing_else_changes() { let client = codex_request(false); diff --git a/gateway/crates/pc-gateway-app/src/main.rs b/gateway/crates/pc-gateway-app/src/main.rs index 53662106f0..86a034ad43 100644 --- a/gateway/crates/pc-gateway-app/src/main.rs +++ b/gateway/crates/pc-gateway-app/src/main.rs @@ -234,6 +234,23 @@ async fn main() { eprintln!("Claude CLI requires confirmed non-enforcing Core; its internal HTTP sends are not observable"); std::process::exit(2); } + // 订阅通道里只有 Codex 支持前缀抽取。它的请求重放加密推理,enforcing 的 Core 会暂缓每个抽取请求, + // 所以只在 Core 确认为非 enforcing 时启用。 + let prefix_extraction_requested = matches!( + std::env::var("PC_GATEWAY_PREFIX_EXTRACTION").as_deref(), + Ok("on") + ); + let prefix_extraction = prefix_extraction_requested + && match subscription_kind { + None => true, + Some(pc_gateway_auth::Subscription::Codex) => degradation_allowed, + Some(_) => false, + }; + if prefix_extraction_requested && !prefix_extraction { + tracing::warn!( + "PC_GATEWAY_PREFIX_EXTRACTION=on is not in effect: with a subscription it needs codex and a Core confirmed as non-enforcing; turns use normal extraction" + ); + } let transport = GatewayTransport::new( ReqwestTransport::new(Duration::from_secs(120)) .with_subscription_responses_sse(matches!( @@ -292,14 +309,7 @@ async fn main() { ), sediment, steering, - // 订阅通道里只有 Codex 支持前缀抽取。 - prefix_extraction: matches!( - subscription_kind, - None | Some(pc_gateway_auth::Subscription::Codex) - ) && matches!( - std::env::var("PC_GATEWAY_PREFIX_EXTRACTION").as_deref(), - Ok("on") - ), + prefix_extraction, default_scope: std::env::var("PC_GATEWAY_DEFAULT_SCOPE") .unwrap_or_else(|_| "gateway:default".into()), max_body_bytes: model_body_bytes, diff --git a/src/powercontext/builtin/artifacts/atomic_memory/prefixed_extraction.py b/src/powercontext/builtin/artifacts/atomic_memory/prefixed_extraction.py index 329d3d7ab2..ea4bc3dfaf 100644 --- a/src/powercontext/builtin/artifacts/atomic_memory/prefixed_extraction.py +++ b/src/powercontext/builtin/artifacts/atomic_memory/prefixed_extraction.py @@ -60,6 +60,8 @@ "prefix_unavailable": "prefix_unavailable", "target_mismatch": "target_mismatch", "invalid_instruction": "invalid_instruction", + "output_limit_unsupported": "output_limit_unsupported", + "subscription_auth_failed": "credentials_unavailable", } diff --git a/tests/builtin/artifacts/atomic_memory/test_prefixed_extraction.py b/tests/builtin/artifacts/atomic_memory/test_prefixed_extraction.py index 72fe92345a..5a1dca4a56 100644 --- a/tests/builtin/artifacts/atomic_memory/test_prefixed_extraction.py +++ b/tests/builtin/artifacts/atomic_memory/test_prefixed_extraction.py @@ -180,6 +180,9 @@ def test_a_gateway_turn_is_extracted_over_its_prefix_without_resending_the_trans [ (404, {"error": "prefix_unavailable"}, "prefix_unavailable"), (409, {"error": "target_mismatch"}, "target_mismatch"), + (400, {"error": "output_limit_unsupported"}, "output_limit_unsupported"), + (502, {"error": "subscription_auth_failed"}, "credentials_unavailable"), + (502, {"error": {"code": "server_error", "message": "upstream failed"}}, "provider_error"), (409, {"decision": "withhold", "reason_codes": ["encrypted-origin-unverified"]}, "check_rejected"), (502, {"decision": "not_sent", "attempts": 2}, "gateway_error"), ( From 247f1ae2078119f7ba714e85bec4cfd6a6f9a98b Mon Sep 17 00:00:00 2001 From: jasper-yl Date: Sun, 22 Nov 2026 12:04:52 -0800 Subject: [PATCH 3/5] revert(gateway): keep the extraction reply as on master The check for a failed terminal response changed how the extraction entry treats every 2xx reply, including the API-key path that predates this branch. The reply handling is the same as on master again. Co-Authored-By: Claude --- gateway/crates/pc-gateway-app/src/ingress.rs | 59 ++----------------- .../atomic_memory/test_prefixed_extraction.py | 1 - 2 files changed, 6 insertions(+), 54 deletions(-) diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index 09cd96f791..fdc0c1ffb8 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -241,10 +241,12 @@ pub async fn extract( { ManagedOutcome::Released { status, body, .. } if (200..300).contains(&status) => { match serde_json::from_slice::(&body) { - Ok(response) => match extraction_reply(&response) { - Ok(reply) => Json(reply).into_response(), - Err(failure) => (StatusCode::BAD_GATEWAY, Json(failure)).into_response(), - }, + Ok(response) => Json(serde_json::json!({ + "text": responses_output_text(&response), + "usage": response.get("usage").cloned().unwrap_or(serde_json::Value::Null), + "model": response.get("model").cloned().unwrap_or(serde_json::Value::Null), + })) + .into_response(), Err(_) => error(StatusCode::BAD_GATEWAY, "invalid_upstream_response"), } } @@ -252,24 +254,6 @@ pub async fn extract( } } -/// 抽取的回复。订阅通道把流折叠成终止响应,失败的响应因此也以 200 到达:按响应状态区分,失败时返回供应商的 -/// 错误对象,与上游直接以错误状态码返回时的形式一致。 -fn extraction_reply(response: &serde_json::Value) -> Result { - let error = response.get("error").filter(|error| !error.is_null()); - if error.is_some() || matches!(response["status"].as_str(), Some("failed" | "cancelled")) { - let error = error - .filter(|error| error.is_object()) - .cloned() - .unwrap_or_else(|| serde_json::json!({"code": "response_failed"})); - return Err(serde_json::json!({ "error": error })); - } - Ok(serde_json::json!({ - "text": responses_output_text(response), - "usage": response.get("usage").cloned().unwrap_or(serde_json::Value::Null), - "model": response.get("model").cloned().unwrap_or(serde_json::Value::Null), - })) -} - /// 前缀请求:原始请求的 input 依次接上终止响应的输出(去掉 `id`/`status`,与客户端重放的形式一致)和 Core 的 /// 指令。其余字段(工具、`prompt_cache_key`、推理设置等)不变,只把 `tool_choice` 设为 `none`、改为非流式, /// 并在 Core 给出时设置输出上限:这些字段不影响前缀缓存。 @@ -1887,37 +1871,6 @@ pub(crate) mod tests { assert_eq!(body["error"], "output_limit_unsupported"); } - #[test] - fn a_failed_terminal_response_is_an_extraction_error() { - let completed = serde_json::json!({ - "status": "completed", "model": "m", "usage": {"input_tokens": 3}, - "output": [{"type": "message", "role": "assistant", - "content": [{"type": "output_text", "text": "{}"}]}] - }); - assert_eq!( - extraction_reply(&completed), - Ok(serde_json::json!({"text": "{}", "usage": {"input_tokens": 3}, "model": "m"})) - ); - // 被截断的响应仍交给 Core 校验,与上游以 200 返回它时一致。 - let incomplete = serde_json::json!({"status": "incomplete", "output": [], - "incomplete_details": {"reason": "max_output_tokens"}}); - assert!(extraction_reply(&incomplete).is_ok()); - - let failed = serde_json::json!({"status": "failed", "output": [], - "error": {"code": "server_error", "message": "upstream failed"}}); - assert_eq!( - extraction_reply(&failed), - Err( - serde_json::json!({"error": {"code": "server_error", "message": "upstream failed"}}) - ) - ); - let cancelled = serde_json::json!({"status": "cancelled", "output": []}); - assert_eq!( - extraction_reply(&cancelled), - Err(serde_json::json!({"error": {"code": "response_failed"}})) - ); - } - #[test] fn steering_is_rendered_after_the_base_prompt_and_nothing_else_changes() { let client = codex_request(false); diff --git a/tests/builtin/artifacts/atomic_memory/test_prefixed_extraction.py b/tests/builtin/artifacts/atomic_memory/test_prefixed_extraction.py index 5a1dca4a56..006027c775 100644 --- a/tests/builtin/artifacts/atomic_memory/test_prefixed_extraction.py +++ b/tests/builtin/artifacts/atomic_memory/test_prefixed_extraction.py @@ -182,7 +182,6 @@ def test_a_gateway_turn_is_extracted_over_its_prefix_without_resending_the_trans (409, {"error": "target_mismatch"}, "target_mismatch"), (400, {"error": "output_limit_unsupported"}, "output_limit_unsupported"), (502, {"error": "subscription_auth_failed"}, "credentials_unavailable"), - (502, {"error": {"code": "server_error", "message": "upstream failed"}}, "provider_error"), (409, {"decision": "withhold", "reason_codes": ["encrypted-origin-unverified"]}, "check_rejected"), (502, {"decision": "not_sent", "attempts": 2}, "gateway_error"), ( From e7a0ab80e91446398e8607bd7f4eb779ca2f7dc0 Mon Sep 17 00:00:00 2001 From: jasper-yl Date: Sun, 22 Nov 2026 19:56:37 -0800 Subject: [PATCH 4/5] fix(gateway): forward session-id to the Codex subscription endpoint The Codex subscription endpoint routes its prompt cache by the session-id request header, not by prompt_cache_key. The gateway sent only the authorization and account headers, so requests of one session mostly missed each other's cache. The model entry now forwards the client's session-id on a Codex subscription. The kept prefix records it, and the extraction request sends the same value. Other upstreams do not receive the header. Co-Authored-By: Claude --- gateway/SUBSCRIPTIONS.md | 2 + gateway/crates/pc-gateway-app/src/ingress.rs | 88 +++++++++++++++---- .../crates/pc-gateway-core/src/executor.rs | 7 ++ gateway/crates/pc-gateway-core/src/lib.rs | 2 +- .../pc-gateway-core/src/prefix_store.rs | 7 ++ .../tests/executor_semantics.rs | 4 + 6 files changed, 93 insertions(+), 17 deletions(-) diff --git a/gateway/SUBSCRIPTIONS.md b/gateway/SUBSCRIPTIONS.md index 2651e3dfa8..044bf29624 100644 --- a/gateway/SUBSCRIPTIONS.md +++ b/gateway/SUBSCRIPTIONS.md @@ -62,6 +62,8 @@ Core must approve the final target, model and protocol through `PC_GATEWAY_UPSTR Codex's endpoint rejects `max_output_tokens`. A Core policy requiring that explicit output cap withholds the request with `output_limit_required`; a configured profile limit cannot make the upstream enforce an unsupported parameter. +The Codex endpoint routes its prompt cache by the `session-id` request header; `prompt_cache_key` in the body does not do this there. The Gateway forwards the client's `session-id` to this endpoint and sends the same value on a prefix extraction request, so requests of one session reach the same cache. A client that sends no `session-id` gets few cache hits. The header is not forwarded to other upstreams. + With `PC_GATEWAY_PREFIX_EXTRACTION=on`, memory extraction over the cached prefix is available on `codex` when Core is confirmed as non-enforcing at startup. Each extraction request is sent with the credentials in the Codex login at that moment, counts against that account's usage limits, and has no output limit; a request that asks for one is refused with `output_limit_unsupported`, and Core uses normal extraction. See [prefix extraction settings](../docs/en/docs/operate/deploy-server.md#memory-extraction-over-the-cached-prefix). Gemini maps Chat output limits to `request.generationConfig.maxOutputTokens`. Responses containing thought signatures are withheld; signed tool continuations are unsupported. Plain thought text is retained in the checked result. Claude checks cannot inspect the CLI's internal HTTP calls, retries or token budget, so enforcing Core always withholds this execution path, including after a runtime policy change. diff --git a/gateway/crates/pc-gateway-app/src/ingress.rs b/gateway/crates/pc-gateway-app/src/ingress.rs index 53c4b149fe..1f143035d7 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -248,7 +248,9 @@ pub async fn extract( let Some(canonical) = canonical else { return error(StatusCode::INTERNAL_SERVER_ERROR, "prefix_invalid"); }; - let Ok(channel) = upstream_channel(&state, &Format::Responses).await else { + let Ok(channel) = + upstream_channel(&state, &Format::Responses, prefix.session_id.as_deref()).await + else { return subscription_auth_failed(); }; let call = ManagedCall { @@ -563,7 +565,12 @@ async fn ingress_model( target_url, renderer, headers: upstream_headers, - }) = upstream_channel(&state, &format).await + }) = upstream_channel( + &state, + &format, + header_id(&headers, pc_gateway_core::UPSTREAM_SESSION_HEADER), + ) + .await else { return subscription_auth_failed(); }; @@ -930,6 +937,9 @@ const OPENCODE_SESSION_HEADER: &str = "x-opencode-session-id"; const CODEX_THREAD_ID_HEADER: &str = "thread-id"; /// 路由的上游地址、订阅改写和凭据。模型入口与前缀抽取共用,抽取请求因此以原请求的形式和凭据发出。 +/// +/// `session` 是客户端请求的 `session-id`。Codex 订阅端点按这个请求头路由提示缓存,请求体里的 +/// `prompt_cache_key` 在那里不起这个作用;不带它时同一会话的请求大多落不到同一份缓存上。其他上游不转发它。 struct UpstreamChannel { target_url: String, renderer: pc_gateway_protocol::SubscriptionRenderer, @@ -939,6 +949,7 @@ struct UpstreamChannel { async fn upstream_channel( state: &AppState, format: &Format, + session: Option<&str>, ) -> Result { let subscription_kind = state.subscription.as_ref().map(|auth| auth.kind()); let mut renderer = pc_gateway_protocol::SubscriptionRenderer { @@ -968,7 +979,7 @@ async fn upstream_channel( Format::Chat => state.upstream_chat.clone(), Format::Responses => state.upstream_responses.clone(), }; - let headers = if let Some(auth) = state.subscription.as_ref() { + let mut headers = if let Some(auth) = state.subscription.as_ref() { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|v| v.as_secs() as i64) @@ -987,6 +998,14 @@ async fn upstream_channel( Format::Responses => &state.upstream_responses_api_key, }) }; + if let (Some(pc_gateway_auth::Subscription::Codex), Some(session)) = + (subscription_kind, session) + { + headers.push(( + pc_gateway_core::UPSTREAM_SESSION_HEADER.to_string(), + session.to_string(), + )); + } Ok(UpstreamChannel { target_url, renderer, @@ -1733,6 +1752,7 @@ pub(crate) mod tests { request_body: serde_json::to_vec(&sent).unwrap().into(), response_output: output, prepared_contexts: Vec::new(), + session_id: None, }; let request = ExtractRequest { handle: "h".into(), @@ -1797,6 +1817,7 @@ pub(crate) mod tests { "role": "assistant", "status": "completed", "content": [{"type": "output_text", "text": "done", "annotations": []}]})], prepared_contexts: Vec::new(), + session_id: None, }; let step = |messages: &[(&str, &str)]| { let request = ExtractRequest { @@ -1860,7 +1881,6 @@ pub(crate) mod tests { /// 使用 Codex 订阅的网关状态;凭据文件是合成的,测试不发出网络请求。 fn codex_subscription_state(name: &str) -> (Arc, std::path::PathBuf) { - use pc_gateway_core::{Executor, HttpGateClient}; let path = std::env::temp_dir().join(format!( "pc-gateway-codex-auth-{}-{name}.json", std::process::id() @@ -1870,7 +1890,18 @@ pub(crate) mod tests { r#"{"auth_mode":"chatgpt","tokens":{"access_token":"SYNTHETIC_SUBSCRIPTION_TOKEN","account_id":"acct-1"}}"#, ) .unwrap(); - let state = Arc::new(AppState { + let subscription = pc_gateway_auth::SubscriptionAuth::new( + pc_gateway_auth::Subscription::Codex, + path.clone(), + ) + .unwrap(); + (channel_state(Some(subscription)), path) + } + + /// 只用于取上游通道的网关状态,不连接 Core 或上游。 + fn channel_state(subscription: Option) -> Arc { + use pc_gateway_core::{Executor, HttpGateClient}; + Arc::new(AppState { executor: Arc::new(Executor::new( crate::link::CoreLink::Http(HttpGateClient::with_token("http://127.0.0.1:9", None)), pc_gateway_transport::GatewayTransport::new( @@ -1884,13 +1915,7 @@ pub(crate) mod tests { upstream_responses: "https://chatgpt.com/backend-api/codex/responses".into(), upstream_chat_api_key: String::new(), upstream_responses_api_key: "SYNTHETIC_STATIC_KEY".into(), - subscription: Some( - pc_gateway_auth::SubscriptionAuth::new( - pc_gateway_auth::Subscription::Codex, - path.clone(), - ) - .unwrap(), - ), + subscription, api_key: None, degrade: pc_gateway_core::DegradePolicy::Pause, injection: Injection::Off, @@ -1902,15 +1927,14 @@ pub(crate) mod tests { default_scope: "test".into(), max_body_bytes: 1024 * 1024, degradation_allowed: true, - }); - (state, path) + }) } #[tokio::test] async fn the_extraction_channel_of_a_codex_subscription_carries_its_credentials_and_form() { use pc_gateway_protocol::WireRenderer; let (state, path) = codex_subscription_state("channel"); - let channel = upstream_channel(&state, &Format::Responses).await; + let channel = upstream_channel(&state, &Format::Responses, Some("session-a")).await; std::fs::remove_file(&path).unwrap(); let channel = channel.unwrap(); @@ -1931,6 +1955,8 @@ pub(crate) mod tests { Some("Bearer SYNTHETIC_SUBSCRIPTION_TOKEN") ); assert_eq!(header("chatgpt-account-id"), Some("acct-1")); + // 会话标识随请求带给上游,上游据此路由提示缓存。 + assert_eq!(header("session-id"), Some("session-a")); // 抽取请求以订阅的形式发出,其余字段与保留的请求一致。 let render = |body: serde_json::Value| -> serde_json::Value { @@ -1949,6 +1975,7 @@ pub(crate) mod tests { request_body: serde_json::to_vec(&sent).unwrap().into(), response_output: Vec::new(), prepared_contexts: Vec::new(), + session_id: None, }; let request = ExtractRequest { handle: "h".into(), @@ -1975,11 +2002,40 @@ pub(crate) mod tests { ); } + #[tokio::test] + async fn the_session_header_goes_only_to_a_codex_subscription_upstream() { + let has_session = |channel: &UpstreamChannel| { + channel + .headers + .iter() + .any(|(name, _)| name.eq_ignore_ascii_case("session-id")) + }; + let (state, path) = codex_subscription_state("session"); + let without = upstream_channel(&state, &Format::Responses, None).await; + std::fs::remove_file(&path).unwrap(); + assert!(!has_session(&without.unwrap())); + + // 使用上游 API key 的部署不转发它。 + let channel = upstream_channel(&channel_state(None), &Format::Responses, Some("session-a")) + .await + .unwrap(); + assert!(!has_session(&channel)); + assert_eq!( + channel.headers, + [( + "authorization".to_string(), + "Bearer SYNTHETIC_STATIC_KEY".to_string() + )] + ); + } + #[tokio::test] async fn unreadable_subscription_credentials_fail_the_extraction_channel() { let (state, path) = codex_subscription_state("missing"); std::fs::remove_file(&path).unwrap(); - assert!(upstream_channel(&state, &Format::Responses).await.is_err()); + assert!(upstream_channel(&state, &Format::Responses, None) + .await + .is_err()); } #[tokio::test] diff --git a/gateway/crates/pc-gateway-core/src/executor.rs b/gateway/crates/pc-gateway-core/src/executor.rs index 45b520d6e0..128c9fa7f7 100644 --- a/gateway/crates/pc-gateway-core/src/executor.rs +++ b/gateway/crates/pc-gateway-core/src/executor.rs @@ -850,6 +850,13 @@ where request_body: sent.clone(), response_output, prepared_contexts: call.prepared_contexts.clone(), + session_id: call + .headers + .iter() + .find(|(name, _)| { + name.eq_ignore_ascii_case(crate::prefix_store::UPSTREAM_SESSION_HEADER) + }) + .map(|(_, value)| value.clone()), }, now_ms(), )?; diff --git a/gateway/crates/pc-gateway-core/src/lib.rs b/gateway/crates/pc-gateway-core/src/lib.rs index 0ae2e61672..654b477836 100644 --- a/gateway/crates/pc-gateway-core/src/lib.rs +++ b/gateway/crates/pc-gateway-core/src/lib.rs @@ -39,7 +39,7 @@ pub use executor::*; pub use gate_client::*; pub use http_gate_client::*; pub use lifecycle::*; -pub use prefix_store::{PrefixEntry, PREFIX_TTL_MS}; +pub use prefix_store::{PrefixEntry, PREFIX_TTL_MS, UPSTREAM_SESSION_HEADER}; pub use transcript::source_token_limit; pub use uds_gate_client::*; diff --git a/gateway/crates/pc-gateway-core/src/prefix_store.rs b/gateway/crates/pc-gateway-core/src/prefix_store.rs index 902d844493..ba81b958cc 100644 --- a/gateway/crates/pc-gateway-core/src/prefix_store.rs +++ b/gateway/crates/pc-gateway-core/src/prefix_store.rs @@ -41,8 +41,14 @@ pub struct PrefixEntry { pub response_output: Vec, /// 原请求里注入块的绑定与位置。抽取请求原样沿用,前缀里的注入块才能凭原绑定通过检查。 pub prepared_contexts: Vec, + /// 原请求带给上游的会话标识([`UPSTREAM_SESSION_HEADER`])。上游按它路由提示缓存,抽取请求带同一个值 + /// 才能命中这段前缀的缓存。 + pub session_id: Option, } +/// 上游用来把同一会话的请求路由到同一份提示缓存的请求头。 +pub const UPSTREAM_SESSION_HEADER: &str = "session-id"; + impl PrefixEntry { /// 请求体与响应输出的字节数。 fn bytes(&self) -> usize { @@ -123,6 +129,7 @@ mod tests { request_body: bytes::Bytes::from_static(b"{}"), response_output: Vec::new(), prepared_contexts: Vec::new(), + session_id: None, } } diff --git a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs index 139e1b9d7a..2eef47db37 100644 --- a/gateway/crates/pc-gateway-core/tests/executor_semantics.rs +++ b/gateway/crates/pc-gateway-core/tests/executor_semantics.rs @@ -4441,6 +4441,8 @@ async fn a_terminal_responses_turn_keeps_its_prefix_for_extraction() { c.inject_context = false; c.sediment = true; c.capture_prefix = capture_prefix; + c.headers + .push(("session-id".to_string(), "session-a".to_string())); let outcome = executor .run( request_control(), @@ -4460,6 +4462,8 @@ async fn a_terminal_responses_turn_keeps_its_prefix_for_extraction() { let prefix = executor.prefix(&handle, "project:test").unwrap(); assert_eq!(prefix.conversation_id, "conversation-a"); assert_eq!(prefix.target_profile, "openai:test"); + // 上游按会话标识路由提示缓存,抽取请求要带同一个值。 + assert_eq!(prefix.session_id.as_deref(), Some("session-a")); assert_eq!( prefix.request_body, transport.sends.lock().unwrap()[0], From 5f189766d1167f5666e19c718ebdc56cd97e242d Mon Sep 17 00:00:00 2001 From: jasper-yl Date: Sun, 22 Nov 2026 20:24:54 -0800 Subject: [PATCH 5/5] fix(gateway): use prompt_cache_key when a Codex request has no session-id An agent other than the Codex CLI may not send the session-id header but still sends prompt_cache_key, which Codex fills with the same value. On a Codex subscription the gateway now sends that key as session-id when the header is absent. The body is read for it only on that subscription. Co-Authored-By: Claude --- gateway/SUBSCRIPTIONS.md | 2 +- gateway/crates/pc-gateway-app/src/ingress.rs | 54 ++++++++++++++++++-- 2 files changed, 51 insertions(+), 5 deletions(-) diff --git a/gateway/SUBSCRIPTIONS.md b/gateway/SUBSCRIPTIONS.md index 044bf29624..018b2357b4 100644 --- a/gateway/SUBSCRIPTIONS.md +++ b/gateway/SUBSCRIPTIONS.md @@ -62,7 +62,7 @@ Core must approve the final target, model and protocol through `PC_GATEWAY_UPSTR Codex's endpoint rejects `max_output_tokens`. A Core policy requiring that explicit output cap withholds the request with `output_limit_required`; a configured profile limit cannot make the upstream enforce an unsupported parameter. -The Codex endpoint routes its prompt cache by the `session-id` request header; `prompt_cache_key` in the body does not do this there. The Gateway forwards the client's `session-id` to this endpoint and sends the same value on a prefix extraction request, so requests of one session reach the same cache. A client that sends no `session-id` gets few cache hits. The header is not forwarded to other upstreams. +The Codex endpoint routes its prompt cache by the `session-id` request header; `prompt_cache_key` in the body does not do this there. The Gateway forwards the request's `session-id` to this endpoint, or the body's `prompt_cache_key` as `session-id` when the request has no such header, and sends the same value on a prefix extraction request, so requests of one session reach the same cache. A request with neither gets few cache hits. The header is not forwarded to other upstreams. With `PC_GATEWAY_PREFIX_EXTRACTION=on`, memory extraction over the cached prefix is available on `codex` when Core is confirmed as non-enforcing at startup. Each extraction request is sent with the credentials in the Codex login at that moment, counts against that account's usage limits, and has no output limit; a request that asks for one is refused with `output_limit_unsupported`, and Core uses normal extraction. 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 1f143035d7..67de7fe841 100644 --- a/gateway/crates/pc-gateway-app/src/ingress.rs +++ b/gateway/crates/pc-gateway-app/src/ingress.rs @@ -568,7 +568,11 @@ async fn ingress_model( }) = upstream_channel( &state, &format, - header_id(&headers, pc_gateway_core::UPSTREAM_SESSION_HEADER), + // 只有 Codex 订阅端点用到它;其他上游不为它解析请求体。 + (subscription_kind == Some(pc_gateway_auth::Subscription::Codex)) + .then(|| upstream_session(&headers, &body)) + .flatten() + .as_deref(), ) .await else { @@ -925,9 +929,27 @@ fn conversation_id(headers: &HeaderMap, format: &Format) -> Option { fn header_id<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> { let value = headers.get(name)?.to_str().ok()?; - let valid = - !value.is_empty() && value.len() <= 256 && value.bytes().all(|b| b.is_ascii_graphic()); - valid.then_some(value) + valid_id(value).then_some(value) +} + +fn valid_id(value: &str) -> bool { + !value.is_empty() && value.len() <= 256 && value.bytes().all(|b| b.is_ascii_graphic()) +} + +/// 请求带给上游的会话标识:请求的 `session-id` 头;没有时取请求体的 `prompt_cache_key`。Codex 给两者填同一个值, +/// 不发这个头的 agent 往往仍带后者。值的规则与会话头相同,不合规则时按没有处理。 +fn upstream_session(headers: &HeaderMap, body: &[u8]) -> Option { + if let Some(session) = header_id(headers, pc_gateway_core::UPSTREAM_SESSION_HEADER) { + return Some(session.to_string()); + } + #[derive(Deserialize)] + struct CacheKey { + prompt_cache_key: Option, + } + serde_json::from_slice::(body) + .ok()? + .prompt_cache_key + .filter(|key| valid_id(key)) } const CONVERSATION_ID_HEADER: &str = "x-powercontext-conversation-id"; @@ -2002,6 +2024,30 @@ pub(crate) mod tests { ); } + #[test] + fn the_upstream_session_is_the_session_header_or_else_the_cache_key() { + let body = br#"{"model":"m","prompt_cache_key":"key-1","input":[]}"#; + let mut headers = HeaderMap::new(); + assert_eq!(upstream_session(&headers, body).as_deref(), Some("key-1")); + headers.insert("session-id", "session-a".parse().unwrap()); + assert_eq!( + upstream_session(&headers, body).as_deref(), + Some("session-a") + ); + + // 两者都没有,或值不合规则时,不带会话标识。 + let headers = HeaderMap::new(); + assert_eq!(upstream_session(&headers, br#"{"model":"m"}"#), None); + assert_eq!( + upstream_session(&headers, br#"{"prompt_cache_key":"has space"}"#), + None + ); + assert_eq!( + upstream_session(&headers, br#"{"prompt_cache_key":42}"#), + None + ); + } + #[tokio::test] async fn the_session_header_goes_only_to_a_codex_subscription_upstream() { let has_session = |channel: &UpstreamChannel| {