Skip to content
2 changes: 2 additions & 0 deletions gateway/SUBSCRIPTIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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.

Memory extraction over the cached prefix is enabled by default on `codex` when Core is confirmed as non-enforcing at startup; `PC_GATEWAY_PREFIX_EXTRACTION=off` disables it. 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.
Expand Down
140 changes: 121 additions & 19 deletions gateway/crates/pc-gateway-app/src/ingress.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -563,7 +565,16 @@ async fn ingress_model(
target_url,
renderer,
headers: upstream_headers,
}) = upstream_channel(&state, &format).await
}) = upstream_channel(
&state,
&format,
// 只有 Codex 订阅端点用到它;其他上游不为它解析请求体。
(subscription_kind == Some(pc_gateway_auth::Subscription::Codex))
.then(|| upstream_session(&headers, &body))
.flatten()
.as_deref(),
)
.await
else {
return subscription_auth_failed();
};
Expand Down Expand Up @@ -918,9 +929,27 @@ fn conversation_id(headers: &HeaderMap, format: &Format) -> Option<String> {

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<String> {
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<String>,
}
serde_json::from_slice::<CacheKey>(body)
.ok()?
.prompt_cache_key
.filter(|key| valid_id(key))
}

const CONVERSATION_ID_HEADER: &str = "x-powercontext-conversation-id";
Expand All @@ -930,6 +959,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,
Expand All @@ -939,6 +971,7 @@ struct UpstreamChannel {
async fn upstream_channel(
state: &AppState,
format: &Format,
session: Option<&str>,
) -> Result<UpstreamChannel, pc_gateway_auth::AuthError> {
let subscription_kind = state.subscription.as_ref().map(|auth| auth.kind());
let mut renderer = pc_gateway_protocol::SubscriptionRenderer {
Expand Down Expand Up @@ -968,7 +1001,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)
Expand All @@ -987,6 +1020,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,
Expand Down Expand Up @@ -1733,6 +1774,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(),
Expand Down Expand Up @@ -1797,6 +1839,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 {
Expand Down Expand Up @@ -1860,7 +1903,6 @@ pub(crate) mod tests {

/// 使用 Codex 订阅的网关状态;凭据文件是合成的,测试不发出网络请求。
fn codex_subscription_state(name: &str) -> (Arc<AppState>, 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()
Expand All @@ -1870,7 +1912,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<pc_gateway_auth::SubscriptionAuth>) -> Arc<AppState> {
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(
Expand All @@ -1884,13 +1937,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,
Expand All @@ -1902,15 +1949,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();

Expand All @@ -1931,6 +1977,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 {
Expand All @@ -1949,6 +1997,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(),
Expand All @@ -1975,11 +2024,64 @@ 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| {
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]
Expand Down
7 changes: 7 additions & 0 deletions gateway/crates/pc-gateway-core/src/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
)?;
Expand Down
2 changes: 1 addition & 1 deletion gateway/crates/pc-gateway-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::*;

Expand Down
7 changes: 7 additions & 0 deletions gateway/crates/pc-gateway-core/src/prefix_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,14 @@ pub struct PrefixEntry {
pub response_output: Vec<serde_json::Value>,
/// 原请求里注入块的绑定与位置。抽取请求原样沿用,前缀里的注入块才能凭原绑定通过检查。
pub prepared_contexts: Vec<pc_gateway_types::PreparedContextLocation>,
/// 原请求带给上游的会话标识([`UPSTREAM_SESSION_HEADER`])。上游按它路由提示缓存,抽取请求带同一个值
/// 才能命中这段前缀的缓存。
pub session_id: Option<String>,
}

/// 上游用来把同一会话的请求路由到同一份提示缓存的请求头。
pub const UPSTREAM_SESSION_HEADER: &str = "session-id";

impl PrefixEntry {
/// 请求体与响应输出的字节数。
fn bytes(&self) -> usize {
Expand Down Expand Up @@ -123,6 +129,7 @@ mod tests {
request_body: bytes::Bytes::from_static(b"{}"),
response_output: Vec::new(),
prepared_contexts: Vec::new(),
session_id: None,
}
}

Expand Down
4 changes: 4 additions & 0 deletions gateway/crates/pc-gateway-core/tests/executor_semantics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand All @@ -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],
Expand Down