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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ Codex is officially maintained; other Agent and Python framework integrations ar
## Learn more

- [Core concepts](https://powercontext.oceanbase.io/en/docs/get-started/core-concepts/) · [Architecture and responsibilities](https://powercontext.oceanbase.io/en/docs/workflows/architecture/) · [Plugins](https://powercontext.oceanbase.io/en/docs/develop/plugins/)
- [Python / HTTP / MCP interfaces](https://powercontext.oceanbase.io/en/docs/develop/interfaces/) · [Deploy the Server](https://powercontext.oceanbase.io/en/docs/operate/deploy-server/)
- [Python / HTTP / MCP interfaces](https://powercontext.oceanbase.io/en/docs/develop/interfaces/) · [Deploy the Server](https://powercontext.oceanbase.io/en/docs/operate/deploy-server/) · [Select a Scope per Gateway request](docs/en/docs/operate/deploy-server.md#gateway-request-scope)
- [Token benchmark report](docs/benchmarks/token-savings/README.md) · [Blog](https://powercontext.oceanbase.io/en/blog/)

## Community
Expand Down
2 changes: 1 addition & 1 deletion README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ Codex 为官方维护;其余 Agent 和 Python 框架集成为社区维护;Bu
## 了解更多

- [核心概念](https://powercontext.oceanbase.io/zh/docs/get-started/core-concepts/) · [架构与职责边界](https://powercontext.oceanbase.io/zh/docs/workflows/architecture/) · [插件开发](https://powercontext.oceanbase.io/zh/docs/develop/plugins/)
- [Python / HTTP / MCP 接口](https://powercontext.oceanbase.io/zh/docs/develop/interfaces/) · [部署 Server](https://powercontext.oceanbase.io/zh/docs/operate/deploy-server/)
- [Python / HTTP / MCP 接口](https://powercontext.oceanbase.io/zh/docs/develop/interfaces/) · [部署 Server](https://powercontext.oceanbase.io/zh/docs/operate/deploy-server/) · [为每个 Gateway 请求选择 Scope](docs/zh/docs/operate/deploy-server.md#gateway-请求-scope)
- [Token 评测报告](docs/benchmarks/token-savings/README_CN.md) · [博客](https://powercontext.oceanbase.io/zh/blog/)

## 社区
Expand Down
2 changes: 1 addition & 1 deletion README_JP.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ Codex 連携は公式メンテナンス、その他の Agent と Python フレ
## さらに詳しく

- [基本概念](https://powercontext.oceanbase.io/en/docs/get-started/core-concepts/) · [アーキテクチャと責任範囲](https://powercontext.oceanbase.io/en/docs/workflows/architecture/) · [プラグイン](https://powercontext.oceanbase.io/en/docs/develop/plugins/)
- [Python / HTTP / MCP インターフェース](https://powercontext.oceanbase.io/en/docs/develop/interfaces/) · [Server のデプロイ](https://powercontext.oceanbase.io/en/docs/operate/deploy-server/)
- [Python / HTTP / MCP インターフェース](https://powercontext.oceanbase.io/en/docs/develop/interfaces/) · [Server のデプロイ](https://powercontext.oceanbase.io/en/docs/operate/deploy-server/) · [Gateway のリクエストごとに Scope を選択する](docs/en/docs/operate/deploy-server.md#gateway-request-scope)
- [トークン削減のベンチマーク](docs/benchmarks/token-savings/README.md) · [ブログ](https://powercontext.oceanbase.io/en/blog/)

## コミュニティ
Expand Down
10 changes: 6 additions & 4 deletions docs/en/docs/integrations/codex.md
Original file line number Diff line number Diff line change
Expand Up @@ -412,9 +412,10 @@ default. Set:
- `PC_GATEWAY_API_KEY` to the key that Codex sends as `PC_GATEWAY_KEY`. A non-loopback listener requires it.
- `PC_GATEWAY_CORE_TOKEN` when Core enforces authentication.
- `PC_GATEWAY_SEDIMENT=on`, so that the gateway captures each completed turn as a Source.
- `PC_GATEWAY_DEFAULT_SCOPE` to the Scope this plugin resolves for the workspace. Running `scope_binding.py` without
- `PC_GATEWAY_DEFAULT_SCOPE` to the fallback Scope. To use the Scope this plugin resolves for the workspace,
run `scope_binding.py` without
`--bind-scope`, as described in [Hand off the current work in one turn](#hand-off-the-current-work-in-one-turn),
prints that Scope.
to print that Scope.

The gateway reads these settings at startup. For its authentication and injection settings, see
[Deploy the Server](../operate/deploy-server.md#gateway-authentication-boundaries). A model request body through the
Expand All @@ -423,8 +424,9 @@ gateway is limited to at most 1 MiB, so a long thread can be refused before it i

With recall off, prompt-time context comes only from the gateway, with two differences:

- The gateway prepares and captures every conversation in the one Scope set by `PC_GATEWAY_DEFAULT_SCOPE`, not in
the Scope this plugin resolves for each Session or workspace.
- The gateway prepares and captures in the Scope selected by `X-PowerContext-Scope-ID` and uses the fallback Scope
when the header is absent. The plugin's Session and workspace bindings are independent. See
[Gateway request Scope](../operate/deploy-server.md#gateway-request-scope).
- The gateway does not send the bootstrap receipt, so Memory already injected by
[Session bootstrap context](#opt-in-to-session-bootstrap-context) can appear again in the gateway's context.

Expand Down
7 changes: 4 additions & 3 deletions docs/en/docs/integrations/opencode.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,10 @@ a complete PowerContext prepared-context block, the gateway replaces that result
`PowerContext plugin prepared context omitted by the gateway.` and keeps its tool call ID. The request and response
still go through Core's normal checks.

With recall off, prompt-time context comes only from the gateway. The gateway prepares and captures in the Scope set
by `PC_GATEWAY_DEFAULT_SCOPE`, not in the Scope this plugin resolves for the Session or workspace. Set it to the same
Scope.
With recall off, prompt-time context comes only from the gateway. The gateway prepares and captures in the Scope
selected by `X-PowerContext-Scope-ID` and uses `PC_GATEWAY_DEFAULT_SCOPE` when the header is absent. To match the Scope
the plugin resolves for the Session or workspace, use that Scope in the header or as the default. See
[Gateway request Scope](../operate/deploy-server.md#gateway-request-scope).

OpenCode sends its session ID in the `x-opencode-session-id` header of every model request. A gateway connected to
the Core over UDS therefore prepares and injects each OpenCode turn by default; a standalone gateway needs
Expand Down
6 changes: 6 additions & 0 deletions docs/en/docs/operate/deploy-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,12 @@ Gemini disables Gateway context injection. Claude CLI accepts fresh text-only tu

Do not route Core's own generation through automatic Gateway recall or capture without a separate recursion boundary.

### Gateway request Scope

Send `X-PowerContext-Scope-ID` on `/gateway/v1/chat/completions` or `/gateway/v1/responses` to select the Scope for recall, both Core checks, and turn capture. Send one Scope ID of 1–256 visible ASCII characters, excluding commas. An invalid or repeated value returns HTTP 400 with `invalid_scope_id`. When the header is absent, the Gateway uses `PC_GATEWAY_DEFAULT_SCOPE` (defaults to `gateway:default`). Clients should send the same Scope on every request in a conversation. The Gateway partitions prepared context replay by Scope and conversation ID.

Use a Gateway with clients trusted to select the Scopes available to its Core credential. Core checks access under that credential according to its configured access mode. A client or a trusted proxy can set the header on each request.

### Gateway context injection

When the gateway connects to the Core over UDS (`PC_GATEWAY_CORE_UDS`, the combined deployment), it injects prepared context by default into Chat and Responses requests that belong to a conversation. Within a conversation it prepares once per new user message and replays the exact result for the rest of that turn, such as an agent's tool loop.
Expand Down
8 changes: 4 additions & 4 deletions docs/zh/docs/integrations/codex.md
Original file line number Diff line number Diff line change
Expand Up @@ -357,17 +357,17 @@ codex
- `PC_GATEWAY_API_KEY` 设为 Codex 以 `PC_GATEWAY_KEY` 发送的密钥。监听非回环地址时必须设置。
- Core 启用鉴权时,设置 `PC_GATEWAY_CORE_TOKEN`。
- `PC_GATEWAY_SEDIMENT=on`,让 gateway 把每个完成的轮次采集为 Source。
- `PC_GATEWAY_DEFAULT_SCOPE` 设为插件为该 workspace 解析的 Scope。按[一句话交接当前工作](#一句话交接当前工作)中的
说明,不带 `--bind-scope` 运行 `scope_binding.py`,即可打印这个 Scope。
- `PC_GATEWAY_DEFAULT_SCOPE` 设为回退 Scope。若要使用插件为该 workspace 解析的 Scope,按
[一句话交接当前工作](#一句话交接当前工作)中的说明,不带 `--bind-scope` 运行 `scope_binding.py`,即可打印这个 Scope。

gateway 在启动时读取这些设置。gateway 的鉴权和注入设置见[部署 Server](../operate/deploy-server.md#网关认证边界)。
经过 gateway 的模型请求正文最多 1 MiB,过长的 thread 可能在发送前被拒绝,见
[Gateway 字节容量](../operate/deploy-server.md#gateway-字节容量)。

关闭召回后,提示词时上下文只来自 gateway,有两点不同:

- gateway 把所有对话都放在 `PC_GATEWAY_DEFAULT_SCOPE` 指定的同一个 Scope 中准备和采集,而不是插件为每个 Session
或 workspace 解析的 Scope。
- gateway 在 `X-PowerContext-Scope-ID` 选择的 Scope 中准备和采集,未发送该请求头时使用回退 Scope。插件的
Session 和 workspace binding 独立生效。见 [Gateway 请求 Scope](../operate/deploy-server.md#gateway-请求-scope)。
- gateway 不发送启动上下文的 receipt,因此[启动上下文](#选择启用-session-启动上下文)已经注入的 Memory
可能再次出现在 gateway 的上下文中。

Expand Down
5 changes: 3 additions & 2 deletions docs/zh/docs/integrations/opencode.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,9 @@ opencode
gateway 会将该结果的文本替换为 `PowerContext plugin prepared context omitted by the gateway.`,并保留工具调用 ID。
请求和响应仍会经过 Core 的常规检查。

关闭召回后,提示词时上下文只来自 gateway。gateway 在 `PC_GATEWAY_DEFAULT_SCOPE` 指定的 Scope 中准备和采集,
而不是插件为 Session 或 workspace 解析的 Scope。请把它设为同一个 Scope。
关闭召回后,提示词时上下文只来自 gateway。gateway 在 `X-PowerContext-Scope-ID` 选择的 Scope 中准备和采集,
未发送该请求头时使用 `PC_GATEWAY_DEFAULT_SCOPE`。若要使用插件为 Session 或 workspace 解析的 Scope,请在请求头
中指定该 Scope,或将其设为默认值。见 [Gateway 请求 Scope](../operate/deploy-server.md#gateway-请求-scope)。

OpenCode 在每个模型请求的 `x-opencode-session-id` 头中发送会话 ID。因此,通过 UDS 连接 Core 的 gateway 默认为
OpenCode 的每一轮准备并注入上下文;独立运行的 gateway 需要设置 `PC_GATEWAY_INJECTION=on`。见
Expand Down
6 changes: 6 additions & 0 deletions docs/zh/docs/operate/deploy-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,12 @@ Gemini 关闭 Gateway 上下文注入。Claude CLI 只接受新的单轮文本

不要在缺少独立递归边界时,让 Core 内部生成回经自动召回或捕获对话的 Gateway。

### Gateway 请求 Scope

向 `/gateway/v1/chat/completions` 或 `/gateway/v1/responses` 发送 `X-PowerContext-Scope-ID` 请求头,可选择召回、Core 两阶段检查和轮次采集使用的 Scope。请发送一个 Scope ID,由 1–256 个可见 ASCII 字符组成,不含逗号。请求头无效或重复时,返回 HTTP 400 和 `invalid_scope_id`。未发送该请求头时,Gateway 使用 `PC_GATEWAY_DEFAULT_SCOPE`(默认值为 `gateway:default`)。同一对话的每个请求应使用相同的 Scope。Gateway 按 Scope 和对话 ID 隔离已准备上下文的重放。

请只让受信任的客户端使用 Gateway,这些客户端可以选择其 Core 凭据可访问的 Scope。Core 按配置的访问模式检查该凭据的权限。客户端或受信任的代理可以在每个请求中设置此请求头。

### 网关上下文注入

网关通过 UDS 连接 Core(`PC_GATEWAY_CORE_UDS`,即同机组合部署)时,默认向属于某个会话的 Chat 和 Responses 请求注入准备好的上下文。在同一会话内,每条新的用户消息只准备一次,该回合的后续请求(例如 Agent 的工具循环)精确重放同一结果。
Expand Down
2 changes: 2 additions & 0 deletions gateway/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ Use `X-PowerContext-Conversation-ID` to identify a conversation. The Gateway als

The Gateway classifies each request tail as `user_turn`, `tool_continuation`, `assistant_only` or `empty`, and records it in call evidence and debug logs. Responses items are classified by their own role and type rather than the verbatim carrier. Every kind other than `user_turn` reuses the turn's prepared block when a replay entry exists and otherwise skips preparation and replay.

Send `X-PowerContext-Scope-ID` on Chat or Responses requests to select the Scope for recall, both Core checks, and capture. Requests without the header use `PC_GATEWAY_DEFAULT_SCOPE`. Core applies its access rules using the Gateway's Core credentials. See [request Scope settings](../docs/en/docs/operate/deploy-server.md#gateway-request-scope).

Set `PC_GATEWAY_SEDIMENT=on` to capture completed user turns as Sources for later extraction. Capture excludes injected context and provider reasoning ciphertext. Tool continuations remain open until the final response. Long turns are split into Sources, and Core stores all parts in one batch. With a trusted conversation ID, captures share a turn digest and include a digest of the ordered normalized Source parts in their Source IDs. Distinct terminal records are stored independently; identical normalized parts are idempotent even when provider response IDs or usage change. Existing Sources remain unchanged, and a repeated capture under the former turn-only ID creates a new Source. Capture requires a Core that supports batch capture. Capture failure does not prevent response delivery. Blocked and degraded turns are not captured.

Prefix extraction is enabled by default for supported upstreams on both model routes. Chat extraction requires a captured non-streaming turn with a single completed text reply and a conversation ID. `PC_GATEWAY_PREFIX_EXTRACTION=off` disables prefix extraction. With a subscription this applies to `codex` only, on a Core confirmed as non-enforcing; the extraction requests use the subscription account. Traffic of the other subscriptions uses normal extraction. Capture remains opt-in. Core also needs its gateway callback URL and generation model configured. With that URL configured, the Server defaults to `one_pass` unless a processing mode was explicitly supplied; `POWERCONTEXT_SERVER_RUNTIME_ATOMIC_MEMORY_PROCESSING_MODE=per_candidate` retains the previous mode. Both processing modes can reuse an eligible agent prefix when estimated cheaper, with normal extraction as the fallback. See [prefix extraction settings](../docs/en/docs/operate/deploy-server.md#memory-extraction-over-the-cached-prefix).
Expand Down
35 changes: 32 additions & 3 deletions gateway/crates/pc-gateway-app/src/ingress.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,10 @@ pub async fn extract(
if let Some(rejected) = unauthorized(&state, &headers) {
return rejected;
}
let scope_id = match request_scope(&headers, &state.default_scope) {
Ok(scope_id) => scope_id,
Err(error) => return error.into_response(),
};
if request.instruction.trim().is_empty()
|| request.instruction.len() > MAX_EXTRACT_INSTRUCTION_BYTES
{
Expand All @@ -240,7 +244,7 @@ pub async fn extract(
if !valid_continuation(&request.continuation) {
return error(StatusCode::BAD_REQUEST, "invalid_continuation");
}
let Some(prefix) = state.executor.prefix(&request.handle, &state.default_scope) else {
let Some(prefix) = state.executor.prefix(&request.handle, scope_id) else {
return error(StatusCode::NOT_FOUND, "prefix_unavailable");
};
if prefix.target_profile != state.upstream_profile {
Expand All @@ -262,7 +266,7 @@ pub async fn extract(
return subscription_auth_failed();
};
let call = ManagedCall {
scope_id: state.default_scope.clone(),
scope_id: scope_id.to_owned(),
target_profile: state.upstream_profile.clone(),
request: canonical,
target_url: channel.target_url,
Expand Down Expand Up @@ -511,6 +515,10 @@ async fn ingress_model(
if let Some(rejected) = unauthorized(&state, &headers) {
return rejected;
}
let scope_id = match request_scope(&headers, &state.default_scope) {
Ok(scope_id) => scope_id,
Err(error) => return error.into_response(),
};

if state.max_body_bytes == 0 {
return respond(
Expand Down Expand Up @@ -704,7 +712,7 @@ async fn ingress_model(
tracing::warn!("context injection skipped: no conversation identity");
}
let call = ManagedCall {
scope_id: state.default_scope.clone(),
scope_id: scope_id.to_owned(),
target_profile: state.upstream_profile.clone(),
request: canonical,
target_url,
Expand Down Expand Up @@ -1110,6 +1118,26 @@ fn valid_id(value: &str) -> bool {
!value.is_empty() && value.len() <= 256 && value.bytes().all(|b| b.is_ascii_graphic())
}

/// Select the Scope once for the request. Reject ambiguous or invalid explicit selections.
fn request_scope<'a>(
headers: &'a HeaderMap,
default_scope: &'a str,
) -> Result<&'a str, (StatusCode, Json<serde_json::Value>)> {
let mut values = headers.get_all(SCOPE_ID_HEADER).into_iter();
let Some(value) = values.next() else {
return Ok(default_scope);
};
if let Ok(scope_id) = value.to_str() {
if valid_id(scope_id) && !scope_id.contains(',') && values.next().is_none() {
return Ok(scope_id);
}
}
Err((
StatusCode::BAD_REQUEST,
Json(serde_json::json!({ "error": "invalid_scope_id" })),
))
}

/// 请求带给上游的会话标识:请求的 `session-id` 头;没有时取请求体的 `prompt_cache_key`。Codex 给两者填同一个值,
/// 不发这个头的 agent 往往仍带后者。值的规则与会话头相同,不合规则时按没有处理。
fn upstream_session(headers: &HeaderMap, body: &[u8]) -> Option<String> {
Expand All @@ -1126,6 +1154,7 @@ fn upstream_session(headers: &HeaderMap, body: &[u8]) -> Option<String> {
.filter(|key| valid_id(key))
}

const SCOPE_ID_HEADER: &str = "x-powercontext-scope-id";
const CONVERSATION_ID_HEADER: &str = "x-powercontext-conversation-id";
const CLAUDE_CODE_SESSION_HEADER: &str = "x-claude-code-session-id";
const CLAUDE_CODE_AGENT_HEADER: &str = "x-claude-code-agent-id";
Expand Down
Loading
Loading