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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions docs/en/docs/operate/deploy-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,9 +212,22 @@ UDS with channel and user authentication.
### 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 carry a host conversation ID
(`X-PowerContext-Conversation-ID`). 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. Set `PC_GATEWAY_INJECTION=on` to inject every request
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.

The gateway identifies the conversation from the first of these request headers that is present:

| Header | Sent by | Conversation |
| --- | --- | --- |
| `X-PowerContext-Conversation-ID` | a host that integrates with PowerContext | the header value; overrides every other source |
| `x-claude-code-session-id`, with `x-claude-code-agent-id` | Claude Code | the session, separately for each subagent |
| `x-opencode-session-id` | OpenCode | the session; a child session has its own ID |
| `thread-id` (Responses route only) | Codex | the thread; a subagent has its own thread ID |

Headers that a client shares between a parent and its subagents, such as Codex `session-id` and `prompt_cache_key` or
OpenCode `x-opencode-session` and `x-session-affinity`, do not identify a conversation. Claude Code speaks the Anthropic
Messages API, which the gateway does not serve, so its headers apply only when a proxy in front of the gateway
translates its requests to the Chat or Responses route and forwards them. Set `PC_GATEWAY_INJECTION=on` to inject every request
(requests without a conversation ID then prepare individually), `PC_GATEWAY_INJECTION=off` to turn injection off, or
`PC_GATEWAY_INJECTION_RESPONSES=off` to keep only the Responses route uninjected. A standalone gateway
(`PC_GATEWAY_CORE_BASE`) injects only with `PC_GATEWAY_INJECTION=on`. An empty or failed preparation sends the request
Expand Down
18 changes: 15 additions & 3 deletions docs/zh/docs/operate/deploy-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,9 +194,21 @@ Rust 可执行程序、联合 launcher、网关配置、私有通道认证、私

### 网关上下文注入

网关通过 UDS 连接 Core(`PC_GATEWAY_CORE_UDS`,即同机组合部署)时,默认向带有宿主会话 ID
(`X-PowerContext-Conversation-ID`)的 Chat 和 Responses 请求注入准备好的上下文。在同一会话内,每条新的用户消息
只准备一次,该回合的后续请求(例如 Agent 的工具循环)精确重放同一结果。设置 `PC_GATEWAY_INJECTION=on` 会注入所有
网关通过 UDS 连接 Core(`PC_GATEWAY_CORE_UDS`,即同机组合部署)时,默认向属于某个会话的 Chat 和 Responses 请求注入
准备好的上下文。在同一会话内,每条新的用户消息只准备一次,该回合的后续请求(例如 Agent 的工具循环)精确重放同一结果。

网关按以下顺序,取第一个出现的请求头确定会话:

| 请求头 | 发送方 | 会话 |
| --- | --- | --- |
| `X-PowerContext-Conversation-ID` | 接入 PowerContext 的宿主 | 头的取值;优先于其他所有来源 |
| `x-claude-code-session-id`,以及 `x-claude-code-agent-id` | Claude Code | 会话,每个子代理各自独立 |
| `x-opencode-session-id` | OpenCode | 会话;子会话有自己的 ID |
| `thread-id`(仅 Responses 入口) | Codex | 线程;子代理有自己的线程 ID |

客户端在父代理与子代理之间共享的头不用于确定会话,例如 Codex 的 `session-id` 和 `prompt_cache_key`,以及 OpenCode 的
`x-opencode-session` 和 `x-session-affinity`。Claude Code 使用 Anthropic Messages API,而网关不提供该接口,所以只有在
网关前的代理把它的请求转换到 Chat 或 Responses 入口并转发这些头时,Claude Code 的头才会生效。设置 `PC_GATEWAY_INJECTION=on` 会注入所有
请求(没有会话 ID 的请求各自准备),设置 `PC_GATEWAY_INJECTION=off` 关闭注入,设置
`PC_GATEWAY_INJECTION_RESPONSES=off` 只关闭 Responses 入口的注入。独立运行的网关(`PC_GATEWAY_CORE_BASE`)只有
设置 `PC_GATEWAY_INJECTION=on` 时才注入。准备结果为空或准备失败时,请求照常发送,不注入内容。
Expand Down
5 changes: 3 additions & 2 deletions gateway/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ An optional Rust executor for PowerContext, defined by the gateway design in #21
### Memory features (#2199 capabilities)

- **Auto-recall injection**: for each new user message the gateway calls `prepare` with `include_reuse`, and injects the returned prepared context **verbatim** into the current user message. The exact UTF-8 byte range is declared in `prepared_contexts` (`ModelJsonTextLocation`); Core verifies the digest of the declared range against the signed reuse binding — a single byte changed by the gateway is rejected. Empty or failed prepares inject nothing and never block the main path. Injection is tail-only (current message), so the client-owned history prefix stays byte-stable (KV prefix-cache friendly, verified with DeepSeek `cached_tokens`).
A host that sends a stable `X-PowerContext-Conversation-ID` gets the RFC 2199 lifecycle: within that conversation, a request whose messages up to and including the last user message are unchanged (a tool continuation or retry) replays the exact prepared content and binding without another retrieval, and a new user message prepares once. Replay state is partitioned by Scope and conversation ID, kept in memory, bounded, and expires with the reuse binding (at most 5 minutes). Without the header, every request prepares on its own and never inherits an earlier injection. An empty result is replayed as well; a failed `prepare` is retried by the next request and never blocks it. Every send and release still goes through `check`.
A request that belongs to a conversation gets the RFC 2199 lifecycle. The gateway takes the conversation from `X-PowerContext-Conversation-ID` when the host sends one; otherwise from the client's native session header: Claude Code `x-claude-code-session-id` combined with `x-claude-code-agent-id` (subagents share the session ID), OpenCode `x-opencode-session-id` (a child session has its own ID; the shared affinity headers are not used), or, on `/gateway/v1/responses` only, Codex `thread-id` (a subagent has its own thread ID; the `session-id` and `prompt_cache_key` it shares with its parent are not used). Claude Code speaks the Anthropic Messages API, which the gateway does not serve, so its headers take effect only behind a proxy that translates its requests to the Chat or Responses route. Within a conversation, a request whose messages up to and including the last user message are unchanged (a tool continuation or retry) replays the exact prepared content and binding without another retrieval, and a new user message prepares once. Replay state is partitioned by Scope and conversation ID, kept in memory, bounded, and expires with the reuse binding (at most 5 minutes). Without a conversation, every request prepares on its own and never inherits an earlier injection. An empty result is replayed as well; a failed `prepare` is retried by the next request and never blocks it. Every send and release still goes through `check`.
- **Sedimentation**: after a released turn, the gateway synchronously captures the transcript via `capture_content_source` (millisecond-scale durable write; extraction happens later in PC background workers). `source_id` is idempotent (derived from the release binding digest). Blocked and degraded turns are never captured. The full loop — conversation → capture → background extraction into Atomic Memory → `prepare` recall in a *new* session — has been verified end-to-end.

### Deployment & ops
Expand Down Expand Up @@ -88,7 +88,8 @@ PC_GATEWAY_UPSTREAM_API_KEY_CHAT=... \
./target/release/pc-gateway

# Injection (prepare + inject on the Chat and Responses routes): in the combined deployment (PC_GATEWAY_CORE_UDS)
# requests that carry X-PowerContext-Conversation-ID are injected by default; standalone is off by default.
# requests that belong to a conversation (X-PowerContext-Conversation-ID or a recognized client session header)
# are injected by default; standalone is off by default.
# PC_GATEWAY_INJECTION=on injects every request, PC_GATEWAY_INJECTION=off disables injection, and
# PC_GATEWAY_INJECTION_RESPONSES=off keeps the Responses route uninjected.
# Optional: PC_GATEWAY_SEDIMENT=on (capture after release),
Expand Down
174 changes: 163 additions & 11 deletions gateway/crates/pc-gateway-app/src/ingress.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ async fn ingress_common(
Format::Responses => pc_gateway_protocol::GatewayRenderer::Responses(Default::default()),
};

let conversation = conversation_id(&headers);
let conversation = conversation_id(&headers, &format);
let call = ManagedCall {
scope_id: state.default_scope.clone(),
target_profile: state.upstream_profile.clone(),
Expand Down Expand Up @@ -421,16 +421,52 @@ fn injects(format: &Format, injection: Injection, responses: bool, has_conversat
enabled && (matches!(format, Format::Chat) || responses)
}

/// 宿主提供的会话 ID(RFC 2199 `X-PowerContext-Conversation-ID`):1~256 个可见 ASCII 字符。
/// 缺失或不合规时按没有会话处理:不在请求之间重放准备结果,请求照常处理。
fn conversation_id(headers: &HeaderMap) -> Option<String> {
let value = headers.get(CONVERSATION_ID_HEADER)?.to_str().ok()?;
/// 请求所属的会话,决定准备结果在哪些请求之间重放。依次取:
/// - 宿主提供的 `X-PowerContext-Conversation-ID`(RFC 2199),优先于各客户端的原生头;
/// - Claude Code 的 `x-claude-code-session-id`:主代理与子代理共享它,子代理的请求另带
/// `x-claude-code-agent-id`,所以会话是二者的组合;
/// - OpenCode 的 `x-opencode-session-id`:子会话有自己的值。`x-opencode-session`、
/// `x-session-affinity` 等亲和头可能让子会话沿用父会话的值,不用作身份;
/// - Responses 入口上,Codex 的 `thread-id`:一个线程的每个请求同值,子代理线程的值不同。它们共享的
/// `session-id` 和 `prompt_cache_key` 不用作身份。`thread-id` 不带客户端前缀,所以只在 Responses
/// 入口识别。
///
/// 各来源加不同前缀,互不相同。值须为 1~256 个可见 ASCII 字符;都没有时按没有会话处理:
/// 不在请求之间重放准备结果,请求照常处理。
fn conversation_id(headers: &HeaderMap, format: &Format) -> Option<String> {
if let Some(id) = header_id(headers, CONVERSATION_ID_HEADER) {
return Some(format!("powercontext:{id}"));
}
if let Some(session) = header_id(headers, CLAUDE_CODE_SESSION_HEADER) {
// 合法值不含空格,用空格分隔会话与代理,组合不会与另一组值重合。
return Some(match header_id(headers, CLAUDE_CODE_AGENT_HEADER) {
Some(agent) => format!("claude-code:{session} {agent}"),
None => format!("claude-code:{session}"),
});
}
if let Some(session) = header_id(headers, OPENCODE_SESSION_HEADER) {
return Some(format!("opencode:{session}"));
}
match format {
Format::Responses => {
header_id(headers, CODEX_THREAD_ID_HEADER).map(|id| format!("codex-thread:{id}"))
}
Format::Chat => None,
}
}

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(|| value.to_owned())
valid.then_some(value)
}

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";
const OPENCODE_SESSION_HEADER: &str = "x-opencode-session-id";
const CODEX_THREAD_ID_HEADER: &str = "thread-id";

fn bearer_headers(key: &str) -> Vec<(String, String)> {
if key.is_empty() {
Expand Down Expand Up @@ -1000,16 +1036,132 @@ mod tests {
#[test]
fn conversation_id_comes_only_from_a_valid_header() {
let mut headers = HeaderMap::new();
assert_eq!(conversation_id(&headers), None);
assert_eq!(conversation_id(&headers, &Format::Chat), None);
headers.insert(CONVERSATION_ID_HEADER, "coding-client-001".parse().unwrap());
assert_eq!(
conversation_id(&headers).as_deref(),
Some("coding-client-001")
conversation_id(&headers, &Format::Chat).as_deref(),
Some("powercontext:coding-client-001")
);
headers.insert(CONVERSATION_ID_HEADER, "has space".parse().unwrap());
assert_eq!(conversation_id(&headers), None);
assert_eq!(conversation_id(&headers, &Format::Chat), None);
headers.insert(CONVERSATION_ID_HEADER, "x".repeat(257).parse().unwrap());
assert_eq!(conversation_id(&headers), None);
assert_eq!(conversation_id(&headers, &Format::Chat), None);
}

/// Codex 0.145 的请求头:同一会话的父线程与子代理线程共享 `session-id`,`thread-id` 不同。
fn codex_headers(thread: &str) -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert(
"session-id",
"019a0000-0000-7000-8000-000000000001".parse().unwrap(),
);
headers.insert("x-client-request-id", thread.parse().unwrap());
headers.insert(CODEX_THREAD_ID_HEADER, thread.parse().unwrap());
headers
}

#[test]
fn codex_threads_are_separate_conversations_on_the_responses_route() {
let root = codex_headers("019a0000-0000-7000-8000-00000000000a");
let child = codex_headers("019a0000-0000-7000-8000-00000000000b");
let root_id = conversation_id(&root, &Format::Responses);
assert_eq!(
root_id.as_deref(),
Some("codex-thread:019a0000-0000-7000-8000-00000000000a")
);
assert_eq!(
conversation_id(&root, &Format::Responses),
root_id,
"every request of a thread"
);
assert_ne!(conversation_id(&child, &Format::Responses), root_id);
// 只在 Responses 入口识别 Codex 的线程头;宿主提供的会话 ID 优先。
assert_eq!(conversation_id(&root, &Format::Chat), None);
let mut hosted = root.clone();
hosted.insert(CONVERSATION_ID_HEADER, "host-1".parse().unwrap());
assert_eq!(
conversation_id(&hosted, &Format::Responses).as_deref(),
Some("powercontext:host-1")
);
}

#[test]
fn claude_code_subagents_are_separate_conversations() {
// Claude Code 的主代理与子代理共享会话 ID,子代理的请求另带代理 ID。
let mut main = HeaderMap::new();
main.insert(CLAUDE_CODE_SESSION_HEADER, "session-1".parse().unwrap());
let mut subagent = main.clone();
subagent.insert(CLAUDE_CODE_AGENT_HEADER, "agent-a".parse().unwrap());
let mut nested = main.clone();
nested.insert(CLAUDE_CODE_AGENT_HEADER, "agent-b".parse().unwrap());
nested.insert("x-claude-code-parent-agent-id", "agent-a".parse().unwrap());
for format in [Format::Chat, Format::Responses] {
let main_id = conversation_id(&main, &format);
assert_eq!(main_id.as_deref(), Some("claude-code:session-1"));
assert_eq!(
conversation_id(&subagent, &format).as_deref(),
Some("claude-code:session-1 agent-a")
);
assert_eq!(
conversation_id(&nested, &format).as_deref(),
Some("claude-code:session-1 agent-b")
);
}
// 会话与代理的组合不会与另一个会话重合。
let mut slash = HeaderMap::new();
slash.insert(
CLAUDE_CODE_SESSION_HEADER,
"session-1/agent-a".parse().unwrap(),
);
assert_ne!(
conversation_id(&slash, &Format::Chat),
conversation_id(&subagent, &Format::Chat)
);
}

#[test]
fn opencode_child_sessions_are_separate_conversations() {
// 子会话有自己的会话 ID,亲和头与父会话相同。
let affinity = "ses_0123456789abcdef";
let mut parent = HeaderMap::new();
parent.insert(OPENCODE_SESSION_HEADER, "ses_parent".parse().unwrap());
parent.insert("x-opencode-session", affinity.parse().unwrap());
parent.insert("x-session-affinity", affinity.parse().unwrap());
let mut child = parent.clone();
child.insert(OPENCODE_SESSION_HEADER, "ses_child".parse().unwrap());
child.insert(
"x-opencode-parent-session-id",
"ses_parent".parse().unwrap(),
);
for format in [Format::Chat, Format::Responses] {
assert_eq!(
conversation_id(&parent, &format).as_deref(),
Some("opencode:ses_parent")
);
assert_eq!(
conversation_id(&child, &format).as_deref(),
Some("opencode:ses_child")
);
}
// 只有亲和头时不算会话。
let mut affinity_only = HeaderMap::new();
affinity_only.insert("x-opencode-session", affinity.parse().unwrap());
affinity_only.insert("x-session-affinity", affinity.parse().unwrap());
assert_eq!(conversation_id(&affinity_only, &Format::Chat), None);
}

#[test]
fn the_powercontext_header_overrides_every_native_identity() {
let mut headers = codex_headers("thread-a");
headers.insert(CLAUDE_CODE_SESSION_HEADER, "session-1".parse().unwrap());
headers.insert(OPENCODE_SESSION_HEADER, "ses_parent".parse().unwrap());
headers.insert(CONVERSATION_ID_HEADER, "host-1".parse().unwrap());
for format in [Format::Chat, Format::Responses] {
assert_eq!(
conversation_id(&headers, &format).as_deref(),
Some("powercontext:host-1")
);
}
}

#[test]
Expand Down
Loading