Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(agent-runtime): stamp the session id on self-hosted endpoints

arsonist-g7ad736e69960
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index faf09f5d3..76a6b5ae8 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -1329,9 +1329,41 @@ other turn sends; a gateway fronting a Codex backend rejects such a request with
`openai-codex-responses` the summary payload therefore carries the session id as
`prompt_cache_key` (clamped to the adapter's 64-character limit) unless the
adapter or a caller already set one. Every other wire API keeps its payload
-exactly as the adapter built it, and the key is added on a copy, so a caller's
+exactly as the adapter built it, apart from the unrecognized-endpoint key of
+§6.3, and the key is added on a copy, so a caller's
payload hook keeps its own object and its return value still wins.
+### 6.3 Session identity for endpoints the adapters leave anonymous (issue #1634)
+
+pi-ai supplies a conversation id by itself only where a vendor published one:
+the Responses adapters send it on every request, and the Chat Completions and
+Anthropic Messages adapters send it only while
+`compat.sendSessionAffinityHeaders` is set, which defaults to OpenRouter; the
+Chat Completions body key is narrower still, gated on `api.openai.com`. A
+provider row the user pointed at their own gateway or relay would therefore
+send every session of one credential with nothing to tell them apart, leaving
+that gateway unable to pin a conversation to one backend or to isolate its
+prompt cache.
+
+Agent-runtime stamps that identity itself for a row whose base URL host is not
+a published vendor host (`NAMED_ENDPOINT_PRESETS`), on the `openai-completions`
+and `anthropic-messages` wire APIs, and not on the OpenCode path that already
+carries its own session header (§6.2):
+
+- The built model's `compat` gains `sendSessionAffinityHeaders: true` with
+ `sessionAffinityFormat: "openai"`, so the adapter writes `x-session-affinity`
+ and `x-client-request-id` beside `session_id`. That default is spread under
+ the row's own `compat`, so an explicit catalog entry still wins.
+- A Chat Completions request body that carries no `prompt_cache_key` gains the
+ session id as one, clamped to the adapter's 64-character limit. The key rides
+ a copy of the payload and is appended after every other payload hook, so an
+ extension that rewrites the payload cannot drop it.
+
+The identity reaches session turns, subagent turns, context-compaction
+summaries, and plugin one-shots that were handed a session id. A published
+vendor host keeps its current request bytes, and a caller with no session id
+gains no body key.
+
## 7. System prompt composition
diff --git a/docs/spec/03-runtime/11-provider-model-system.md b/docs/spec/03-runtime/11-provider-model-system.md
index 05233b501..12b114f1e 100644
--- a/docs/spec/03-runtime/11-provider-model-system.md
+++ b/docs/spec/03-runtime/11-provider-model-system.md
@@ -85,6 +85,13 @@ rather than wrapped (issue #1072). Because those adapters never see the wrapper
transport cause: `Retry-After` falls back to the bounded backoff ladder, and
the issue-234 transport diagnostics and rebuild do not fire for it.
+Session identity follows the endpoint's owner. On `openai-completions` and
+`anthropic-messages`, a row whose base URL host is not a published vendor host
+receives the session-affinity headers and, on Chat Completions, a
+`prompt_cache_key` body key, so a self-hosted gateway or relay can route and
+cache per session. A published vendor host and the OpenCode path keep their
+current request bytes (issue #1634; `03-runtime/02-agent-runtime.md` §6.3).
+
When an OAuth vendor is rebuilt around a local provider-row id, runtime keeps
the native pi-ai transport metadata instead of treating the row as a generic
OpenAI endpoint. GitHub Copilot requests retain the pinned model's IDE identity
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 845308d0e..3d81a4d46 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -6625,7 +6625,10 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
(`openai-responses`, `openai-codex-responses`) the outgoing payload keeps
the session id as `prompt_cache_key`, exactly as the session's turns do, so
a gateway fronting a Codex backend accepts it instead of answering 400
- `invalid_responses_request`. Providers on other wire APIs are unchanged.
+ `invalid_responses_request`. A provider on another wire API, or on a
+ published vendor host, is unchanged; an unrecognized endpoint on Chat
+ Completions gains the key for the reason
+ `E2E-PROVIDER-custom-endpoint-session-identity` records.
- Each `turn_end` is evaluated before another provider request and never
marks the overall task idle; composer/config controls remain blocked until
`agent_end`, `error`, or manual-only `compaction_end`. In-run follow-up
@@ -6700,6 +6703,36 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
`context-compaction.test.mjs`, `assistant-turns.test.mjs`, host-core
transcript/session unit tests); full provider/UI journey Draft
+#### E2E-PROVIDER-custom-endpoint-session-identity: A self-hosted endpoint receives the session id
+
+- **Preconditions**: Two independent sessions, each with several turns, bound to
+ a provider row whose API style is `chat_completions` and whose base URL points
+ at a local capture endpoint (not a published vendor host). A third row on a
+ published vendor host, and a fourth on `anthropic_messages`, use the same
+ capture endpoint's stand-ins where applicable.
+- **Steps**: 1) Send a turn in each session and capture the full request headers
+ and body of both. 2) Compare the two requests field by field. 3) Trigger a
+ context-compaction summary in the first session and capture it. 4) Run a
+ subagent turn and a plugin one-shot that carry a session id, and capture both.
+ 5) Repeat step 1 on the row whose base URL host is a published vendor host.
+ 6) Repeat step 1 on a row whose API style is `opencode_go`.
+- **Expected**:
+ - Both captured requests carry a stable per-session identifier that differs
+ between the two sessions: `x-session-affinity` and `x-client-request-id`
+ beside `session_id`, plus `prompt_cache_key` in the body, all holding the
+ session's own conversation id and unchanged across that session's turns.
+ - The compaction summary, the subagent turn, and the one-shot carry the same
+ id for their session, so a gateway pins the whole session to one backend.
+ - The published-vendor-host row and the OpenCode row are byte-identical to
+ their pre-change requests (the OpenCode row keeps `x-opencode-session`).
+ - A one-shot call with no session id gains no `prompt_cache_key`.
+- **Specs linked**: `03-runtime/02-agent-runtime.md` (§6.2, §6.3),
+ `03-runtime/11-provider-model-system.md`, issue #1634
+- **Acceptance**: C (chat/stream) + Quality
+- **Milestone**: M5
+- **Status**: Unit-covered (`session-affinity.test.ts`); full gateway capture
+ journey Draft
+
#### E2E-AGENTS-001: Project instruction chain configures an agent session
- **Preconditions**: A project contains root `AGENTS.md`, nested
@@ -9748,6 +9781,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
| A / H / Quality — Renderer process crash recovery | E2E-RUNTIME-renderer-crash-recovery |
| C / F / Quality — Project folder with chats detaches and deletes safely | E2E-048c |
| B / F / Security — Provider copy | E2E-PROVIDER-copy-config-without-credentials |
+| C / Quality — Self-hosted endpoint receives the session id | E2E-PROVIDER-custom-endpoint-session-identity |
| B / F / Quality — Selected model order | E2E-MODEL-selected-order-persists |
| E / F / Quality — MCP server timeout override | E2E-261 |
| A — App startup | E2E-001, E2E-002, E2E-003, E2E-004, E2E-067, E2E-076, E2E-079, E2E-092, E2E-097, E2E-143, E2E-150, E2E-168, E2E-204 |
diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.md
index f8aa947e5..1751a31f9 100644
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@ -7656,3 +7656,25 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
`apps/desktop/test/browser-local-file-feedback.test.mjs`, and E2E-059. See
ADR 0328, `04-ux/08-component-spec.md`, `07-plugins/03-plugin-api.md`, and
`05-security/01-security.md`.
+
+## 2026-10-13 — Session identity on endpoints the adapters leave anonymous (D658)
+
+- Agent-runtime stamps a per-session identity onto requests bound for an endpoint
+ the user pointed at themselves — a provider row whose base URL host is not a
+ published vendor host — on the `openai-completions` and `anthropic-messages`
+ wire APIs. The built model gains `compat.sendSessionAffinityHeaders` with
+ `sessionAffinityFormat: "openai"`, so the adapter writes `x-session-affinity`
+ and `x-client-request-id` beside `session_id`, and a Chat Completions payload
+ that carries no `prompt_cache_key` gains the session id as one, clamped to the
+ adapter's 64-character limit. A row's own `compat` still wins, and the key is
+ added on a copy after every other payload hook.
+- Identity reaches session turns, subagent turns, context-compaction summaries,
+ and plugin one-shots handed a session id. A published vendor host (matched by
+ host against `NAMED_ENDPOINT_PRESETS`), the OpenCode path's own
+ `x-opencode-session`, and the Responses adapters' existing behavior keep their
+ current request bytes, so no vendor's published caching semantics move; a
+ caller with no session id gains no body key.
+- Covered by `packages/agent-runtime/src/session-affinity.test.ts` and
+ E2E-PROVIDER-custom-endpoint-session-identity. See issue #1634,
+ `03-runtime/02-agent-runtime.md` §6.3, and
+ `03-runtime/11-provider-model-system.md`.
diff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
index 0a71c906d..9e252e81e 100644
--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
@@ -934,8 +934,33 @@ agent 运行时的职责,与官方 Pi 编码 agent 的归属层保持一致;
后端的网关会以 400 `invalid_responses_request` 拒绝这种请求。因此对
`openai-responses` 与 `openai-codex-responses`,摘要载荷会带上会话 id 作为
`prompt_cache_key`(按适配器的 64 字符上限截断),除非适配器或调用方已设置过。
-其他线协议的载荷保持适配器构造的原样;该键添加在副本上,因此调用方的载荷钩子仍
-保留自己的对象,其返回值仍然生效。
+其他线协议的载荷保持适配器构造的原样,§6.3 的未识别端点键除外;该键添加在副本
+上,因此调用方的载荷钩子仍保留自己的对象,其返回值仍然生效。
+
+### 6.3 适配器不作标识的端点上的会话身份(issue #1634)
+
+pi-ai 只在厂商自己发布了约定时才自带对话标识:Responses 适配器每个请求都发,而
+Chat Completions 与 Anthropic Messages 适配器只在
+`compat.sendSessionAffinityHeaders` 为真时才发,该默认值仅有 OpenRouter;Chat
+Completions 的请求体键更窄,硬编码在 `api.openai.com` 上。因此,用户把某一提供商行
+指向自己的网关或中转时,同一凭据下的所有会话在出网请求里没有任何字段可以区分,
+该网关既无法把一个会话固定到同一后端,也没有按会话隔离 prompt cache 的依据。
+
+对这种 base URL 主机不属于任何已发布厂商主机(`NAMED_ENDPOINT_PRESETS`)的行,
+agent-runtime 自己补上该身份,覆盖 `openai-completions` 与 `anthropic-messages`
+两种线协议,但不对已经自带会话标头的 OpenCode 线路(§6.2)生效:
+
+- 构造出的模型 `compat` 补上 `sendSessionAffinityHeaders: true` 与
+ `sessionAffinityFormat: "openai"`,适配器据此写出 `x-session-affinity` 与
+ `x-client-request-id`,并在格式为 `openai` 时一并写出 `session_id`。该默认值
+ 展开在行自身 `compat` 之下,因此显式的目录项仍然优先。
+- Chat Completions 的请求体若不含 `prompt_cache_key`,补上会话 id 作为该键,按
+ 适配器的 64 字符上限截断。该键添加在载荷副本上,且排在其它所有载荷钩子之后,
+ 因此重写载荷的扩展无法把它丢掉。
+
+该身份覆盖会话回合、子智能体回合、上下文压缩摘要,以及拿到会话 id 的插件一次性
+调用。属于已发布厂商主机的行保持原有出网字节;没有会话 id 的调用方不会得到请求体
+键。
## 7. 系统提示组成
diff --git a/docs/zh-CN/spec/03-runtime/11-provider-model-system.md b/docs/zh-CN/spec/03-runtime/11-provider-model-system.md
index 8b91191a7..269ef4be2 100644
--- a/docs/zh-CN/spec/03-runtime/11-provider-model-system.md
+++ b/docs/zh-CN/spec/03-runtime/11-provider-model-system.md
@@ -84,6 +84,12 @@ pi-ai 去发出 `x-opencode-session`。每个提供商行(AI 服务或 OAuth
`onResponse`,这样的行不上报捕获到的 HTTP 状态与传输原因:`Retry-After`
退回有界退避阶梯,issue-234 的传输诊断与重建对它不生效。
+会话身份跟随端点归谁所有。在 `openai-completions` 与 `anthropic-messages` 上,
+base URL 主机不属于任何已发布厂商主机的行会带上会话亲和标头,并在 Chat
+Completions 上带上 `prompt_cache_key` 请求体键,使自建网关或中转可以按会话路由与
+缓存。属于已发布厂商主机的行以及 OpenCode 线路保持原有出网字节(issue #1634;
+`03-runtime/02-agent-runtime.md` §6.3)。
+
当 OAuth 厂商围绕本地 provider 行 id 重建运行时模型时,运行时仍保留 pi-ai
原生传输元数据,不会把该行当作普通 OpenAI 端点。GitHub Copilot 请求会保留
固定 pin 模型的 IDE 身份标头,包括 `Editor-Version`、`Editor-Plugin-Version`
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 4c17cbb59..7e633a041 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -3729,8 +3729,9 @@ IPC 请求无法关闭。
- 每个检查点的摘要请求都携带会话自己的对话身份:在 Responses 形状的提供商
(`openai-responses`、`openai-codex-responses`)上,出站载荷会像会话的普通
回合一样把会话 id 作为 `prompt_cache_key` 发出,因此对接 Codex 后端的网关会
- 接受该请求,而不是返回 400 `invalid_responses_request`。其他线协议的提供商
- 保持不变。
+ 接受该请求,而不是返回 400 `invalid_responses_request`。其他线协议的提供商,
+ 以及位于已发布厂商主机上的行,保持不变;未识别端点在 Chat Completions 上会补
+ 上该键,理由见 `E2E-PROVIDER-custom-endpoint-session-identity`。
- 每个 `turn_end` 在另一个提供商请求之前都会被评估,并且永远不会
标记整体任务空闲; composer/config 控件保持阻塞状态,直到
`agent_end`、`error` 或仅手动的 `compaction_end`。
@@ -3791,6 +3792,32 @@ IPC 请求无法关闭。
`context-compaction.test.mjs`、`assistant-turns.test.mjs`、host-core
transcript/session 单元测试);完整的 provider/UI 旅程草稿
+#### E2E-PROVIDER-custom-endpoint-session-identity:自建端点收到会话 id
+
+- **前提**:两个互相独立的会话,各进行若干回合,都绑定到 API 风格为
+ `chat_completions`、base URL 指向本地抓包端点(不是已发布厂商主机)的提供商行。
+ 另有一行位于已发布厂商主机,以及一行使用 `anthropic_messages`。
+- **步骤**:1) 在两个会话各发一个回合,抓取两次请求的完整标头与完整请求体。
+ 2) 逐字段比对这两个请求。3) 在第一个会话触发一次上下文压缩摘要并抓取。
+ 4) 运行一次子智能体回合与一次带会话 id 的插件一次性调用并抓取。
+ 5) 在位于已发布厂商主机的那一行上重复第 1 步。6) 在 API 风格为 `opencode_go`
+ 的行上重复第 1 步。
+- **预期**:
+ - 两次抓取的请求都携带稳定且逐会话不同的标识:`x-session-affinity` 与
+ `x-client-request-id`,在格式为 `openai` 时还含 `session_id`,请求体中含
+ `prompt_cache_key`,取值都是该会话自己的对话 id,并在该会话的多个回合之间保持
+ 不变。
+ - 压缩摘要、子智能体回合与一次性调用携带其所属会话的同一个 id,因此网关会把整个
+ 会话固定到同一后端。
+ - 位于已发布厂商主机的行与 OpenCode 行的出网请求与改动前逐字节一致(OpenCode
+ 行仍带 `x-opencode-session`)。
+ - 没有会话 id 的一次性调用不会得到 `prompt_cache_key`。
+- **关联规格**:`03-runtime/02-agent-runtime.md`(§6.2、§6.3)、
+ `03-runtime/11-provider-model-system.md`、issue #1634
+- **验收**:C (chat/stream) + 质量
+- **里程碑**:M5
+- **状态**:单元测试覆盖(`session-affinity.test.ts`);完整网关抓包旅程草稿
+
#### E2E-AGENTS-001:项目指令链配置代理会话
- **先决条件**:项目包含根 `AGENTS.md`,嵌套
@@ -5648,6 +5675,7 @@ eleven-tool-round desktop paths are verified by
| A / H / Quality — 渲染器进程崩溃恢复 | E2E-RUNTIME-renderer-crash-recovery |
| C / F / Quality — 含聊天的项目文件夹安全分离并删除 | E2E-048c |
| B / F / Security — 提供商复制 | E2E-PROVIDER-copy-config-without-credentials |
+| C / Quality — 自建端点收到会话 id | E2E-PROVIDER-custom-endpoint-session-identity |
| B / F / Quality — 已选模型顺序 | E2E-MODEL-selected-order-persists |
| E / F / Quality — MCP 服务器超时覆盖 | E2E-261 |
| C / D / Quality — 折叠项目后重置会话历史 | E2E-263 |
diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.md
index 526300583..452244dd5 100644
--- a/docs/zh-CN/spec/08-meta/decisions-log.md
+++ b/docs/zh-CN/spec/08-meta/decisions-log.md
@@ -5399,3 +5399,19 @@ Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编
- 由 `apps/desktop/test/browser-pane-navigation.test.mjs`、
`apps/desktop/test/browser-local-file-feedback.test.mjs` 与 E2E-059 覆盖。见 ADR 0328、
`04-ux/08-component-spec.md`、`07-plugins/03-plugin-api.md` 与 `05-security/01-security.md`。
+
+## 2026-10-13 —— 适配器不作标识的端点上的会话身份(D658)
+
+- 对用户自己指向的端点——base URL 主机不属于任何已发布厂商主机的提供商行——agent-runtime
+ 在 `openai-completions` 与 `anthropic-messages` 两种线协议上补上逐会话身份。构造出的模型
+ 会带上 `compat.sendSessionAffinityHeaders` 与 `sessionAffinityFormat: "openai"`,适配器据此
+ 写出 `x-session-affinity` 与 `x-client-request-id`,并在格式为 `openai` 时一并写出
+ `session_id`;Chat Completions 的载荷若不含 `prompt_cache_key`,则补上会话 id 作为该键,按
+ 适配器的 64 字符上限截断。行自身 `compat` 仍然优先,该键添加在副本上且排在其它载荷钩子之后。
+- 该身份覆盖会话回合、子智能体回合、上下文压缩摘要,以及拿到会话 id 的插件一次性调用。属于已发布
+ 厂商主机的行(按主机与 `NAMED_ENDPOINT_PRESETS` 比对)、OpenCode 线路自带的
+ `x-opencode-session`,以及 Responses 适配器既有行为都保持原有出网字节,因此不改变任何厂商已发布
+ 的缓存语义;没有会话 id 的调用方不会得到请求体键。
+- 由 `packages/agent-runtime/src/session-affinity.test.ts` 与
+ E2E-PROVIDER-custom-endpoint-session-identity 覆盖。见 issue #1634、
+ `03-runtime/02-agent-runtime.md` §6.3 与 `03-runtime/11-provider-model-system.md`。
diff --git a/packages/agent-runtime/src/compaction-request.ts b/packages/agent-runtime/src/compaction-request.ts
index 1143dde63..19d2c1d51 100644
--- a/packages/agent-runtime/src/compaction-request.ts
+++ b/packages/agent-runtime/src/compaction-request.ts
@@ -30,6 +30,7 @@ import {
type RuntimeProviderConfig,
} from "./provider-binding.js";
import { mergeProviderHeaders, withProviderHeaders } from "./provider-headers.js";
+import { providerUsesSessionAffinity, withSessionPromptCacheKey } from "./session-affinity.js";
import { compactionRequestShape, type CompactionRequestShape } from "./compaction-diagnostics.js";
/**
@@ -113,15 +114,34 @@ export function withCompactionRequestHeaders(
const identity = { ...requestUsageIdentity(model, provider.id), costStatus: nativeCostStatus(provider.modelConfig?.nativeCost) };
const requestOptions = compactionRequestOptions({ provider, sessionId, model, context, options });
const previousOnPayload = requestOptions.onPayload;
- if (SUMMARY_CONVERSATION_APIS.has(model.api) || onRequestShape) {
+ if (
+ SUMMARY_CONVERSATION_APIS.has(model.api) ||
+ providerUsesSessionAffinity(provider, model.api, model.baseUrl) ||
+ onRequestShape
+ ) {
requestOptions.onPayload = async (payload, requestModel) => {
const replacement = await previousOnPayload?.(payload, requestModel);
const base = replacement === undefined ? payload : replacement;
- const keyed = withSummaryPromptCacheKey({
+ // Two shapes, one owner each, and each pass is a no-op for the other's
+ // API: the summary adapter asks for `"none"` retention on the Responses
+ // APIs, which is what costs the adapter's own key there, while the
+ // Completions adapter keys only `api.openai.com`. Both add only an
+ // absent key, so a payload that already carries one is left alone.
+ const summaryKeyed = withSummaryPromptCacheKey({
payload: base,
api: requestModel.api,
sessionId,
});
+ const keyed = withSessionPromptCacheKey({
+ payload: summaryKeyed,
+ api: requestModel.api,
+ sessionId,
+ enabled: providerUsesSessionAffinity(
+ provider,
+ requestModel.api,
+ requestModel.baseUrl,
+ ),
+ });
// Nothing to change keeps the hook's own return value, so an untouched
// payload stays the adapter's object instead of a copy of it.
onRequestShape?.(compactionRequestShape({
diff --git a/packages/agent-runtime/src/one-shot-complete.ts b/packages/agent-runtime/src/one-shot-complete.ts
index 8b99ca6ff..2ec6e9fd1 100644
--- a/packages/agent-runtime/src/one-shot-complete.ts
+++ b/packages/agent-runtime/src/one-shot-complete.ts
@@ -28,6 +28,7 @@ import {
openCodeEndpointFromProvider,
withOpenCodeSessionHeaders,
} from "./opencode-session-headers.js";
+import { withSessionAffinityPayload } from "./session-affinity.js";
import { mergeProviderHeaders, withProviderHeaders } from "./provider-headers.js";
import {
withProviderFetchFailure,
@@ -131,10 +132,19 @@ export async function completeOneShot(
),
model.api,
);
+ // A one-shot call spends the session's credential like any turn does, so it
+ // carries the session id too; a caller that supplies none keeps an unkeyed
+ // request, and an endpoint that is not stamped is returned unchanged.
+ const sessionOptions = withSessionAffinityPayload(requestOptions, {
+ provider,
+ api: model.api,
+ baseUrl: model.baseUrl,
+ sessionId: options.sessionId,
+ });
const stream = createProviderRetryStream(
model,
context,
- requestOptions,
+ sessionOptions,
(retryOptions) => accountModelStream(model, () => streamSimple(model, context, retryOptions), {
providerId: provider.id, nativeCost: provider.modelConfig?.nativeCost,
onUsage: attemptUsage => { usage = addUsage(usage, attemptUsage); },
diff --git a/packages/agent-runtime/src/provider-binding.test.ts b/packages/agent-runtime/src/provider-binding.test.ts
index 00bbe1116..676e30a11 100644
--- a/packages/agent-runtime/src/provider-binding.test.ts
+++ b/packages/agent-runtime/src/provider-binding.test.ts
@@ -1480,3 +1480,126 @@ describe("DeepSeek-family relay reasoning replay (#296)", () => {
);
});
});
+
+describe("session affinity for the adapters' anonymous endpoints (#1634)", () => {
+ const ownEndpoint = (
+ overrides: Partial<RuntimeProviderConfig> = {},
+ ): RuntimeProviderConfig => ({
+ id: "gateway-row",
+ name: "Own gateway",
+ vendorKey: "custom",
+ baseUrl: "https://gateway.example.com/v1",
+ modelId: "gateway-model-1",
+ apiKey: "sk-test",
+ authKind: "api_key_and_base_url",
+ apiStyle: "chat_completions",
+ supportsReasoning: false,
+ supportedThinkingLevels: ["off"],
+ ...overrides,
+ });
+ const compatOf = (
+ provider: RuntimeProviderConfig,
+ ): Record<string, unknown> | undefined =>
+ buildProviderModel(provider).compat as Record<string, unknown> | undefined;
+
+ it("gives the built model the adapter's non-OpenRouter session shape", () => {
+ expect(compatOf(ownEndpoint())).toMatchObject({
+ sendSessionAffinityHeaders: true,
+ sessionAffinityFormat: "openai",
+ });
+ expect(
+ compatOf(
+ ownEndpoint({
+ apiStyle: "anthropic_messages",
+ baseUrl: "https://relay.example.com",
+ }),
+ ),
+ ).toMatchObject({
+ sendSessionAffinityHeaders: true,
+ sessionAffinityFormat: "openai",
+ });
+ });
+
+ it("leaves a published vendor host and the OpenCode path on their own shape", () => {
+ expect(
+ compatOf(
+ ownEndpoint({
+ vendorKey: "deepseek",
+ baseUrl: "https://api.deepseek.com",
+ apiStyle: "chat_completions",
+ }),
+ )?.sendSessionAffinityHeaders,
+ ).toBeUndefined();
+ expect(
+ compatOf(
+ ownEndpoint({
+ vendorKey: "openai",
+ baseUrl: "https://api.openai.com/v1",
+ apiStyle: "chat_completions",
+ }),
+ )?.sendSessionAffinityHeaders,
+ ).toBeUndefined();
+ expect(
+ compatOf(
+ ownEndpoint({
+ vendorKey: "opencode-go",
+ baseUrl: "https://opencode.ai/zen/go/v1",
+ apiStyle: "opencode_go",
+ }),
+ )?.sendSessionAffinityHeaders,
+ ).toBeUndefined();
+ });
+
+ it("spreads the default under a catalog entry that already answers", () => {
+ const provider = ownEndpoint();
+ const model = buildProviderModel({
+ ...provider,
+ modelConfig: {
+ source: "generic",
+ name: "Gateway model 1",
+ baseUrl: provider.baseUrl!,
+ reasoning: false,
+ input: ["text"],
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ contextWindow: 128_000,
+ maxTokens: 8_192,
+ compat: {
+ sendSessionAffinityHeaders: false,
+ sessionAffinityFormat: "openrouter",
+ },
+ },
+ });
+ expect(model.compat).toMatchObject({
+ sendSessionAffinityHeaders: false,
+ sessionAffinityFormat: "openrouter",
+ });
+ });
+
+ it("reaches the wire as the three headers §6.3 names", async () => {
+ const provider = ownEndpoint();
+ const model = buildProviderModel(provider);
+ let headers: Headers | undefined;
+ const fetch = async (_input: RequestInfo | URL, init?: RequestInit) => {
+ headers = new Headers(init?.headers);
+ return new Response("data: [DONE]\n\n", {
+ status: 200,
+ headers: { "content-type": "text/event-stream" },
+ });
+ };
+
+ await createProviderModels(provider, model)
+ .streamSimple(
+ model,
+ {
+ systemPrompt: "system",
+ messages: [{ role: "user", content: "hello", timestamp: 1 }],
+ } as never,
+ { sessionId: "session-9", fetch },
+ )
+ .result();
+
+ expect(headers?.get("session_id")).toBe("session-9");
+ expect(headers?.get("x-client-request-id")).toBe("session-9");
+ expect(headers?.get("x-session-affinity")).toBe("session-9");
+ });
+});
diff --git a/packages/agent-runtime/src/provider-binding.ts b/packages/agent-runtime/src/provider-binding.ts
index 0618a651f..a647f9ac8 100644
--- a/packages/agent-runtime/src/provider-binding.ts
+++ b/packages/agent-runtime/src/provider-binding.ts
@@ -42,6 +42,7 @@ import {
type ThinkingLevel,
} from "@pi-desktop/shared";
import { genericModelConfig } from "./model-capabilities.js";
+import { sessionAffinityCompat } from "./session-affinity.js";
import type { ModelConfig } from "./thinking-level.js";
export type RuntimeProviderConfig = {
@@ -405,7 +406,13 @@ export function buildProviderModel(
}) === "on"
? true
: undefined,
- compat: { ...compat, ...transcriptCompat(catalog, provider.modelId, binding.api, baseUrl) },
+ // The session-affinity default sits under the row's own compat, so a
+ // catalog entry that already answers the question keeps its answer.
+ compat: {
+ ...(sessionAffinityCompat(provider, binding.api, baseUrl) ?? {}),
+ ...compat,
+ ...transcriptCompat(catalog, provider.modelId, binding.api, baseUrl),
+ },
...(Object.keys(modelHeaders).length > 0 ? { headers: modelHeaders } : {}),
} as Model<Api>;
}
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 752044810..979780db3 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -240,6 +240,7 @@ import {
openCodeEndpointFromProvider,
withOpenCodeSessionHeaders,
} from "./opencode-session-headers.js";
+import { withSessionAffinityPayload } from "./session-affinity.js";
import { withCompactionRequestHeaders } from "./compaction-request.js";
import type { CompactionRequestShape } from "./compaction-diagnostics.js";
import {
@@ -2117,7 +2118,15 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
),
m.api,
);
- const hookedOptions = this.withExtensionProviderHooks(requestOptions, m);
+ const hookedOptions = withSessionAffinityPayload(
+ this.withExtensionProviderHooks(requestOptions, m),
+ {
+ provider: this.provider,
+ api: m.api,
+ baseUrl: m.baseUrl,
+ sessionId: this.sessionId,
+ },
+ );
// The watchdog must be able to *stop* what it abandons. It wraps the
// retry adapter, so draining alone would let the adapter wake from its
// backoff and open a second request for this turn while the runtime is
diff --git a/packages/agent-runtime/src/session-affinity.test.ts b/packages/agent-runtime/src/session-affinity.test.ts
new file mode 100644
index 000000000..736d2901f
--- /dev/null
+++ b/packages/agent-runtime/src/session-affinity.test.ts
@@ -0,0 +1,489 @@
+import { describe, expect, it, vi } from "vitest";
+import type { Model, SimpleStreamOptions } from "@earendil-works/pi-ai";
+import { streamSimple } from "@earendil-works/pi-ai/api/anthropic-messages";
+import { streamSimple as completionsStreamSimple } from "@earendil-works/pi-ai/api/openai-completions";
+import {
+ providerUsesSessionAffinity,
+ sessionAffinityCompat,
+ withSessionAffinityPayload,
+ withSessionPromptCacheKey,
+ type SessionAffinityProvider,
+} from "./session-affinity.js";
+
+/** A row the user pointed at a self-hosted OpenAI-compatible gateway. */
+const ownGateway: SessionAffinityProvider = {
+ apiStyle: "chat_completions",
+ vendorKey: "custom",
+};
+/** A row the user pointed at a self-hosted Anthropic-compatible relay. */
+const ownAnthropicRelay: SessionAffinityProvider = {
+ apiStyle: "anthropic_messages",
+ vendorKey: "custom",
+};
+/** A row on OpenCode Go's own apiStyle. */
+const openCodeGoRow: SessionAffinityProvider = {
+ apiStyle: "opencode_go",
+ vendorKey: "opencode-go",
+};
+
+const GATEWAY = "https://gateway.example.com/v1";
+const ANTHROPIC_RELAY = "https://relay.example.com";
+const LOCAL = "http://127.0.0.1:11434/v1";
+
+const completionsModel = {
+ id: "gateway-model-1",
+ name: "Gateway Model 1",
+ api: "openai-completions",
+ provider: "gateway-uuid",
+ baseUrl: GATEWAY,
+ reasoning: false,
+ input: ["text"],
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ contextWindow: 128_000,
+ maxTokens: 8_192,
+} as Model<"openai-completions">;
+
+describe("providerUsesSessionAffinity", () => {
+ it("stamps the user's own Completions and Anthropic endpoints", () => {
+ expect(providerUsesSessionAffinity(ownGateway, "openai-completions", GATEWAY)).toBe(
+ true,
+ );
+ expect(
+ providerUsesSessionAffinity(ownAnthropicRelay, "anthropic-messages", ANTHROPIC_RELAY),
+ ).toBe(true);
+ expect(providerUsesSessionAffinity(ownGateway, "openai-completions", LOCAL)).toBe(
+ true,
+ );
+ });
+
+ it("leaves every other wire API on the adapter's own behavior", () => {
+ for (const api of [
+ "openai-responses",
+ "openai-codex-responses",
+ "google-generative-ai",
+ "google-vertex",
+ "pi-messages",
+ "",
+ ]) {
+ expect(providerUsesSessionAffinity(ownGateway, api, GATEWAY)).toBe(false);
+ }
+ });
+
+ it("stays off the OpenCode path, which carries its own session header", () => {
+ expect(providerUsesSessionAffinity(openCodeGoRow, "openai-completions", GATEWAY)).toBe(
+ false,
+ );
+ // Each case below isolates one guard: the host is neither OpenCode's nor a
+ // published vendor host, so only the named guard can be the one answering.
+ for (const vendorKey of ["opencode", "opencode-go"]) {
+ expect(
+ providerUsesSessionAffinity(
+ { apiStyle: "chat_completions", vendorKey },
+ "openai-completions",
+ GATEWAY,
+ ),
+ ).toBe(false);
+ }
+ expect(
+ providerUsesSessionAffinity(
+ { apiStyle: "chat_completions", vendorKey: "custom" },
+ "openai-completions",
+ // An opencode.ai host the preset table does not list.
+ "https://sub.opencode.ai/v1",
+ ),
+ ).toBe(false);
+ expect(
+ providerUsesSessionAffinity(
+ { apiStyle: "chat_completions", vendorKey: "custom" },
+ "openai-completions",
+ "https://opencode.ai/zen/v1",
+ ),
+ ).toBe(false);
+ });
+
+ it("keeps a published vendor host on its current request bytes", () => {
+ expect(
+ providerUsesSessionAffinity(ownGateway, "openai-completions", "https://api.openai.com/v1"),
+ ).toBe(false);
+ expect(
+ providerUsesSessionAffinity(
+ ownAnthropicRelay,
+ "anthropic-messages",
+ "https://api.anthropic.com",
+ ),
+ ).toBe(false);
+ // The preset record spells `https://api.deepseek.com` with no path.
+ expect(
+ providerUsesSessionAffinity(ownGateway, "openai-completions", "https://api.deepseek.com/v1"),
+ ).toBe(false);
+ });
+
+ it("treats a host that merely contains a vendor host as the user's own", () => {
+ expect(
+ providerUsesSessionAffinity(
+ ownGateway,
+ "openai-completions",
+ "https://api.openai.com.evil.test/v1",
+ ),
+ ).toBe(true);
+ });
+
+ it("stamps a row whose base URL has no host at all", () => {
+ expect(providerUsesSessionAffinity(ownGateway, "openai-completions", undefined)).toBe(
+ true,
+ );
+ expect(providerUsesSessionAffinity(ownGateway, "openai-completions", "not a url")).toBe(
+ true,
+ );
+ });
+});
+
+describe("sessionAffinityCompat", () => {
+ it("returns the adapter's own non-OpenRouter shape for the user's endpoint", () => {
+ expect(sessionAffinityCompat(ownGateway, "openai-completions", GATEWAY)).toEqual({
+ sendSessionAffinityHeaders: true,
+ sessionAffinityFormat: "openai",
+ });
+ expect(
+ sessionAffinityCompat(ownAnthropicRelay, "anthropic-messages", ANTHROPIC_RELAY),
+ ).toEqual({ sendSessionAffinityHeaders: true, sessionAffinityFormat: "openai" });
+ });
+
+ it("is undefined whenever the row is not stamped", () => {
+ expect(
+ sessionAffinityCompat(ownGateway, "openai-completions", "https://api.openai.com/v1"),
+ ).toBeUndefined();
+ expect(sessionAffinityCompat(ownGateway, "openai-responses", GATEWAY)).toBeUndefined();
+ expect(
+ sessionAffinityCompat(openCodeGoRow, "openai-completions", GATEWAY),
+ ).toBeUndefined();
+ });
+});
+
+describe("withSessionPromptCacheKey", () => {
+ const input = (overrides: Partial<Parameters<typeof withSessionPromptCacheKey>[0]> = {}) => ({
+ payload: { model: "gateway-model-1", messages: [] },
+ api: "openai-completions",
+ sessionId: "session-7",
+ enabled: true,
+ ...overrides,
+ });
+
+ it("adds the session id to a Completions payload on a copy", () => {
+ const payload = { model: "gateway-model-1", messages: [] };
+ const result = withSessionPromptCacheKey(input({ payload }));
+ expect(result).toEqual({
+ model: "gateway-model-1",
+ messages: [],
+ prompt_cache_key: "session-7",
+ });
+ expect(result).not.toBe(payload);
+ expect(payload).toEqual({ model: "gateway-model-1", messages: [] });
+ });
+
+ it("leaves every other wire API's payload untouched", () => {
+ const payload = { model: "gateway-model-1", messages: [] };
+ expect(
+ withSessionPromptCacheKey(input({ payload, api: "anthropic-messages" })),
+ ).toBe(payload);
+ expect(withSessionPromptCacheKey(input({ payload, api: "openai-responses" }))).toBe(
+ payload,
+ );
+ });
+
+ it("adds nothing when the endpoint is not stamped", () => {
+ const payload = { model: "gateway-model-1", messages: [] };
+ expect(withSessionPromptCacheKey(input({ payload, enabled: false }))).toBe(payload);
+ });
+
+ it("never overwrites a key the adapter or a caller already set", () => {
+ const payload = {
+ model: "gateway-model-1",
+ messages: [],
+ prompt_cache_key: "caller-set",
+ };
+ const result = withSessionPromptCacheKey(input({ payload }));
+ expect(result).toBe(payload);
+ expect(payload.prompt_cache_key).toBe("caller-set");
+ });
+
+ it("fills a key that is explicitly null", () => {
+ expect(
+ withSessionPromptCacheKey(
+ input({ payload: { model: "gateway-model-1", prompt_cache_key: null } }),
+ ),
+ ).toEqual({ model: "gateway-model-1", prompt_cache_key: "session-7" });
+ });
+
+ it("preserves a non-null empty-string key", () => {
+ const payload = { model: "gateway-model-1", prompt_cache_key: "" };
+ expect(withSessionPromptCacheKey(input({ payload }))).toBe(payload);
+ });
+
+ it("leaves a payload the adapter did not hand over as a plain object", () => {
+ for (const payload of [undefined, null, "body", 42, [], true]) {
+ expect(withSessionPromptCacheKey(input({ payload }))).toBe(payload);
+ }
+ });
+
+ it("adds no key without a usable session id", () => {
+ const payload = { model: "gateway-model-1", messages: [] };
+ expect(withSessionPromptCacheKey(input({ payload, sessionId: undefined }))).toBe(
+ payload,
+ );
+ expect(withSessionPromptCacheKey(input({ payload, sessionId: "" }))).toBe(payload);
+ expect(withSessionPromptCacheKey(input({ payload, sessionId: " " }))).toBe(payload);
+ expect(withSessionPromptCacheKey(input({ payload, sessionId: "\n\t" }))).toBe(payload);
+ });
+
+ it("trims the session id it does write", () => {
+ expect(
+ withSessionPromptCacheKey(
+ input({ payload: { model: "m" }, sessionId: " session-7 " }),
+ ),
+ ).toEqual({ model: "m", prompt_cache_key: "session-7" });
+ });
+
+ // Oracle: derived. 64 is the adapter's own OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH
+ // (pi-ai dist/api/openai-prompt-cache.js), and the limit counts code points.
+ it("clamps the key to the adapter's 64-character limit", () => {
+ const longAscii = "s".repeat(80);
+ expect(
+ withSessionPromptCacheKey(input({ payload: { model: "m" }, sessionId: longAscii })),
+ ).toEqual({ model: "m", prompt_cache_key: "s".repeat(64) });
+
+ const longAstral = Array.from({ length: 70 }, () => "🙂").join("");
+ expect(
+ withSessionPromptCacheKey(input({ payload: { model: "m" }, sessionId: longAstral })),
+ ).toEqual({
+ model: "m",
+ prompt_cache_key: Array.from({ length: 64 }, () => "🙂").join(""),
+ });
+ });
+
+ it("keeps a key at the limit whole", () => {
+ const exact = "k".repeat(64);
+ expect(
+ withSessionPromptCacheKey(input({ payload: { model: "m" }, sessionId: exact })),
+ ).toEqual({ model: "m", prompt_cache_key: exact });
+ });
+});
+
+describe("withSessionAffinityPayload", () => {
+ const input = (
+ overrides: Partial<{
+ provider: SessionAffinityProvider;
+ api: string;
+ baseUrl: string | undefined;
+ sessionId: string | undefined;
+ }> = {},
+ ) => ({
+ provider: ownGateway,
+ api: "openai-completions",
+ baseUrl: GATEWAY,
+ sessionId: "session-7",
+ ...overrides,
+ });
+
+ it("returns the caller's own options object for a row it does not stamp", () => {
+ const options: SimpleStreamOptions = { temperature: 0 };
+ expect(
+ withSessionAffinityPayload(options, {
+ provider: ownGateway,
+ api: "openai-completions",
+ baseUrl: "https://api.openai.com/v1",
+ sessionId: "session-7",
+ }),
+ ).toBe(options);
+ expect(
+ withSessionAffinityPayload(options, input({ api: "openai-responses" })),
+ ).toBe(options);
+ expect(
+ withSessionAffinityPayload(options, input({ provider: openCodeGoRow })),
+ ).toBe(options);
+ });
+
+ it("keeps the caller's other options while adding its own hook", () => {
+ const options: SimpleStreamOptions = { temperature: 0, sessionId: "session-7" };
+ const result = withSessionAffinityPayload(options, input());
+ expect(result).not.toBe(options);
+ expect(result.temperature).toBe(0);
+ expect(result.sessionId).toBe("session-7");
+ expect(result.onPayload).toEqual(expect.any(Function));
+ });
+
+ it("keys the adapter payload and still runs the caller's payload hook first", async () => {
+ const previous = vi.fn(async (payload: unknown) => payload);
+ const options: SimpleStreamOptions = { onPayload: previous };
+ const adapterPayload = { model: "gateway-model-1", stream: true };
+ const result = withSessionAffinityPayload(options, input());
+
+ const payload = await result.onPayload?.(adapterPayload, completionsModel);
+
+ expect(previous).toHaveBeenCalledWith(adapterPayload, completionsModel);
+ expect(payload).toEqual({
+ model: "gateway-model-1",
+ stream: true,
+ prompt_cache_key: "session-7",
+ });
+ expect(adapterPayload).toEqual({ model: "gateway-model-1", stream: true });
+ });
+
+ it("adds the key to whatever the caller's hook returned, not to the adapter payload", async () => {
+ const replacement = { model: "rewritten", extra: true };
+ const options: SimpleStreamOptions = { onPayload: async () => replacement };
+ const result = withSessionAffinityPayload(options, input());
+
+ const payload = await result.onPayload?.(
+ { model: "gateway-model-1", stream: true },
+ completionsModel,
+ );
+
+ expect(payload).toEqual({ model: "rewritten", extra: true, prompt_cache_key: "session-7" });
+ expect(replacement).toEqual({ model: "rewritten", extra: true });
+ });
+
+ it("lets a key the caller's hook set survive", async () => {
+ const options: SimpleStreamOptions = {
+ onPayload: async () => ({ model: "rewritten", prompt_cache_key: "caller-set" }),
+ };
+ const result = withSessionAffinityPayload(options, input());
+
+ expect(
+ await result.onPayload?.({ model: "gateway-model-1" }, completionsModel),
+ ).toEqual({ model: "rewritten", prompt_cache_key: "caller-set" });
+ });
+
+ it("adds no key for a caller with no session id", async () => {
+ const adapterPayload = { model: "gateway-model-1", stream: true };
+ const result = withSessionAffinityPayload({}, input({ sessionId: undefined }));
+
+ const payload = await result.onPayload?.(adapterPayload, completionsModel);
+
+ // `undefined` is pi-ai's "keep the payload the adapter built".
+ expect(payload).toBeUndefined();
+ expect(adapterPayload).toEqual({ model: "gateway-model-1", stream: true });
+ });
+
+ it("leaves the adapter's payload as the caller's hook returned it when nothing is added", async () => {
+ const replacement = { model: "rewritten", stream: true };
+ const result = withSessionAffinityPayload(
+ { onPayload: async () => replacement },
+ input({ sessionId: undefined }),
+ );
+
+ expect(
+ await result.onPayload?.({ model: "gateway-model-1" }, completionsModel),
+ ).toBe(replacement);
+ });
+});
+
+/**
+ * Oracle: derived, from the adapter this module feeds
+ * (pi-ai dist/api/openai-completions.js createClient / buildParams): it writes
+ * `session_id`, `x-client-request-id` and `x-session-affinity` beside the body
+ * key, and only the non-OpenRouter format does so.
+ */
+describe("the pi-ai Completions adapter's session identity", () => {
+ it("sends the headers and body key §6.3 names, and no key on a published host", async () => {
+ const sent: Array<{ headers: Headers; body: Record<string, unknown> }> = [];
+ const fetchStub: typeof globalThis.fetch = async (_url, init) => {
+ sent.push({
+ headers: new Headers(init?.headers),
+ body: JSON.parse(String(init?.body)) as Record<string, unknown>,
+ });
+ return new Response("data: [DONE]\n\n", {
+ status: 200,
+ headers: { "content-type": "text/event-stream" },
+ });
+ };
+ const streamOnce = async (
+ baseUrl: string,
+ provider: SessionAffinityProvider,
+ ): Promise<void> => {
+ const model = {
+ ...completionsModel,
+ baseUrl,
+ compat: sessionAffinityCompat(provider, "openai-completions", baseUrl),
+ } as Model<"openai-completions">;
+ const options = withSessionAffinityPayload(
+ { apiKey: "sk-test", sessionId: "session-42", fetch: fetchStub },
+ { provider, api: "openai-completions", baseUrl, sessionId: "session-42" },
+ );
+ for await (const _event of completionsStreamSimple(
+ model,
+ { messages: [{ role: "user", content: "hi", timestamp: 1 }] } as never,
+ options,
+ )) {
+ // drain so the request the stub captured is the whole request
+ }
+ };
+
+ await streamOnce(GATEWAY, ownGateway);
+ expect(sent).toHaveLength(1);
+ expect(sent[0].headers.get("session_id")).toBe("session-42");
+ expect(sent[0].headers.get("x-client-request-id")).toBe("session-42");
+ expect(sent[0].headers.get("x-session-affinity")).toBe("session-42");
+ expect(sent[0].body.prompt_cache_key).toBe("session-42");
+
+ await streamOnce("https://api.deepseek.com/v1", ownGateway);
+ expect(sent).toHaveLength(2);
+ expect(sent[1].headers.get("x-session-affinity")).toBeNull();
+ expect(sent[1].headers.get("session_id")).toBeNull();
+ expect(sent[1].body.prompt_cache_key).toBeUndefined();
+ });
+});
+
+/**
+ * Oracle: derived, from the Anthropic adapter's own header choice
+ * (pi-ai dist/api/anthropic-messages.js: any format but `openrouter` writes
+ * `x-session-affinity`, and `openrouter` would write `x-session-id` instead).
+ */
+describe("the pi-ai Anthropic adapter's session identity", () => {
+ it("writes x-session-affinity for the user's own relay", async () => {
+ const model = {
+ ...completionsModel,
+ api: "anthropic-messages",
+ baseUrl: ANTHROPIC_RELAY,
+ compat: sessionAffinityCompat(
+ ownAnthropicRelay,
+ "anthropic-messages",
+ ANTHROPIC_RELAY,
+ ),
+ } as Model<"anthropic-messages">;
+ const sent: Array<{ headers: Headers; body: Record<string, unknown> }> = [];
+ const fetchStub: typeof globalThis.fetch = async (_url, init) => {
+ sent.push({
+ headers: new Headers(init?.headers),
+ body: JSON.parse(String(init?.body)) as Record<string, unknown>,
+ });
+ return new Response("", {
+ status: 200,
+ headers: { "content-type": "text/event-stream" },
+ });
+ };
+ const options = withSessionAffinityPayload(
+ { apiKey: "sk-test", sessionId: "session-42", maxTokens: 16, fetch: fetchStub },
+ {
+ provider: ownAnthropicRelay,
+ api: "anthropic-messages",
+ baseUrl: ANTHROPIC_RELAY,
+ sessionId: "session-42",
+ },
+ );
+
+ for await (const _event of streamSimple(
+ model,
+ { messages: [{ role: "user", content: "hi", timestamp: 1 }] } as never,
+ options,
+ )) {
+ // drain: only the captured request matters here
+ }
+
+ expect(sent).toHaveLength(1);
+ expect(sent[0].headers.get("x-session-affinity")).toBe("session-42");
+ expect(sent[0].headers.get("x-session-id")).toBeNull();
+ // The body key is the Chat Completions channel only.
+ expect(sent[0].body.prompt_cache_key).toBeUndefined();
+ });
+});
diff --git a/packages/agent-runtime/src/session-affinity.ts b/packages/agent-runtime/src/session-affinity.ts
new file mode 100644
index 000000000..8701ee482
--- /dev/null
+++ b/packages/agent-runtime/src/session-affinity.ts
@@ -0,0 +1,158 @@
+/**
+ * Session identity for endpoints the adapters leave anonymous.
+ *
+ * pi-ai stamps a conversation id by itself only where a vendor documented one:
+ * the Responses adapters send it on every request, and the Completions and
+ * Anthropic adapters send it only while `compat.sendSessionAffinityHeaders` is
+ * set — which defaults to OpenRouter. The Completions body key is narrower
+ * still: `prompt_cache_key` is gated on `api.openai.com`. A self-hosted gateway
+ * or a relay therefore sees every session of one credential as the same
+ * conversation, so it can pin a conversation to no particular backend and has
+ * no per-session basis for isolating a prompt cache.
+ *
+ * This module stamps that identity for endpoints the user pointed at
+ * themselves, so a gateway can read one conversation per session again. A row
+ * that still resolves to a published vendor host keeps its current request
+ * bytes: those vendors' caching semantics are not ours to change, and the
+ * OpenCode path already carries its own session header.
+ *
+ * The two channels answer different questions and are both needed: the headers
+ * let a gateway route a conversation to one backend, the body key lets an
+ * upstream isolate its prompt cache.
+ */
+
+import { addressesPublishedVendorHost } from "@pi-desktop/shared";
+import type { SimpleStreamOptions } from "@earendil-works/pi-ai";
+import { clampOpenAIPromptCacheKey } from "@earendil-works/pi-ai/api/openai-prompt-cache";
+import { isOpenCodeEndpoint } from "./opencode-session-headers.js";
+import type { RuntimeProviderConfig } from "./provider-binding.js";
+
+/** Wire APIs whose adapter emits the session headers from `compat`. */
+const SESSION_AFFINITY_APIS: ReadonlySet<string> = new Set([
+ "openai-completions",
+ "anthropic-messages",
+]);
+
+/** Wire APIs that carry the conversation key in the request body. */
+const SESSION_AFFINITY_BODY_APIS: ReadonlySet<string> = new Set([
+ "openai-completions",
+]);
+
+export type SessionAffinityCompat = {
+ sendSessionAffinityHeaders: true;
+ sessionAffinityFormat: "openai";
+};
+
+/** The provider fields that decide whether this row is the user's own endpoint. */
+export type SessionAffinityProvider = Pick<RuntimeProviderConfig, "apiStyle" | "vendorKey">;
+
+/**
+ * Whether PI-Desktop stamps this request itself.
+ *
+ * False for every endpoint that already answers the question: a wire API with
+ * no session channel, the OpenCode path (whose own header is applied
+ * separately), and any row whose base URL is still a published vendor host.
+ */
+export function providerUsesSessionAffinity(
+ provider: SessionAffinityProvider,
+ api: string,
+ baseUrl: string | undefined,
+): boolean {
+ if (!SESSION_AFFINITY_APIS.has(api)) return false;
+ if (
+ isOpenCodeEndpoint({
+ apiStyle: provider.apiStyle,
+ vendorKey: provider.vendorKey,
+ baseUrl,
+ })
+ ) {
+ return false;
+ }
+ return !addressesPublishedVendorHost(baseUrl);
+}
+
+/**
+ * The model `compat` entry that makes the adapter write the session headers.
+ *
+ * `openai` is the adapter's own non-OpenRouter shape: `x-session-affinity` and
+ * `x-client-request-id` beside `session_id`. The Anthropic adapter reads the
+ * same flag and, for any format but `openrouter`, writes `x-session-affinity`.
+ * An endpoint reached through a provider row's own `compat` keeps its say: this
+ * value is spread under it, so an explicit catalog entry still wins.
+ */
+export function sessionAffinityCompat(
+ provider: SessionAffinityProvider,
+ api: string,
+ baseUrl: string | undefined,
+): SessionAffinityCompat | undefined {
+ return providerUsesSessionAffinity(provider, api, baseUrl)
+ ? { sendSessionAffinityHeaders: true, sessionAffinityFormat: "openai" }
+ : undefined;
+}
+
+/**
+ * Add the conversation key to the request body when this endpoint is stamped
+ * and the adapter would not have added one itself.
+ *
+ * A payload that already carries the key is returned untouched, and so is a
+ * payload the adapter did not hand over as a plain object. The adapter's own
+ * object is never mutated: the key rides a shallow copy, so a caller's
+ * `onPayload` return value can still replace the whole payload.
+ */
+export function withSessionPromptCacheKey(input: {
+ payload: unknown;
+ api: string;
+ sessionId: string | undefined;
+ enabled: boolean;
+}): unknown {
+ const { payload, api, sessionId, enabled } = input;
+ if (!enabled || !SESSION_AFFINITY_BODY_APIS.has(api)) return payload;
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) return payload;
+ const body = payload as Record<string, unknown>;
+ if (body.prompt_cache_key !== undefined && body.prompt_cache_key !== null) {
+ return payload;
+ }
+ const key = clampOpenAIPromptCacheKey(sessionId?.trim() || undefined);
+ if (!key) return payload;
+ return { ...body, prompt_cache_key: key };
+}
+
+/**
+ * `options` with the conversation body key appended after every other
+ * `onPayload` hook, so a payload-rewriting extension cannot drop it.
+ *
+ * An endpoint that is not stamped, or a wire API with no body channel, gets
+ * its options back unchanged — no hook is installed and the request object
+ * stays the one the caller built. A stamped endpoint takes the hook even for a
+ * caller with no session id; there the hook adds nothing and the adapter keeps
+ * its own payload.
+ */
+export function withSessionAffinityPayload(
+ options: SimpleStreamOptions,
+ input: {
+ provider: SessionAffinityProvider;
+ api: string;
+ baseUrl: string | undefined;
+ sessionId: string | undefined;
+ },
+): SimpleStreamOptions {
+ const enabled = providerUsesSessionAffinity(input.provider, input.api, input.baseUrl);
+ if (!enabled || !SESSION_AFFINITY_BODY_APIS.has(input.api)) return options;
+ const previous = options.onPayload;
+ return {
+ ...options,
+ onPayload: async (payload, model) => {
+ const replacement = await previous?.(payload, model);
+ const base = replacement === undefined ? payload : replacement;
+ const keyed = withSessionPromptCacheKey({
+ payload: base,
+ api: model.api,
+ sessionId: input.sessionId,
+ enabled,
+ });
+ // Nothing to change keeps the hook's own return value, so an untouched
+ // payload stays the adapter's object instead of a copy of it.
+ return keyed === base ? replacement : keyed;
+ },
+ };
+}
diff --git a/packages/agent-runtime/src/subagent-model-binding.ts b/packages/agent-runtime/src/subagent-model-binding.ts
index 11c84a605..088af22d0 100644
--- a/packages/agent-runtime/src/subagent-model-binding.ts
+++ b/packages/agent-runtime/src/subagent-model-binding.ts
@@ -11,6 +11,7 @@ import {
openCodeEndpointFromProvider,
withOpenCodeSessionHeaders,
} from "./opencode-session-headers.js";
+import { withSessionAffinityPayload } from "./session-affinity.js";
import { mergeProviderHeaders, withProviderHeaders } from "./provider-headers.js";
import { clampOutputToContext } from "./output-cap.js";
import {
@@ -98,10 +99,19 @@ export function subagentModelBinding(opts: {
),
m.api,
);
+ // The conversation key rides the same options object the retry stream
+ // reuses, so every attempt of this delegate carries the parent session's
+ // id rather than only the first.
+ const sessionOptions = withSessionAffinityPayload(requestOptions, {
+ provider: opts.provider,
+ api: m.api,
+ baseUrl: m.baseUrl,
+ sessionId: opts.sessionId,
+ });
return createProviderRetryStream(
m,
context,
- requestOptions,
+ sessionOptions,
(retryOptions) => accountModelStream(m, () =>
omitThinking
? models.stream(omitThinkingModel, context, retryOptions)
diff --git a/packages/shared/src/provider-presets.test.ts b/packages/shared/src/provider-presets.test.ts
index c714c53cd..152526fcf 100644
--- a/packages/shared/src/provider-presets.test.ts
+++ b/packages/shared/src/provider-presets.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import {
NAMED_ENDPOINT_PRESETS,
+ addressesPublishedVendorHost,
deepseekRequestCompat,
DEEPSEEK_REASONING_REPLAY_PLACEHOLDER,
isDeepSeekReasoningReplay,
@@ -284,3 +285,60 @@ describe("pi-ai built-in API-key services", () => {
}
});
});
+
+describe("addressesPublishedVendorHost", () => {
+ it("matches the hosts the preset table publishes", () => {
+ for (const baseUrl of [
+ "https://api.openai.com/v1",
+ "https://api.anthropic.com",
+ "https://generativelanguage.googleapis.com/v1beta",
+ "https://api.deepseek.com",
+ "https://api.moonshot.cn/v1",
+ "https://openrouter.ai/api/v1",
+ "https://opencode.ai/zen/go/v1",
+ "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
+ ]) {
+ expect(addressesPublishedVendorHost(baseUrl)).toBe(true);
+ }
+ });
+
+ it("matches by host, not by the full canonical URL", () => {
+ // The preset records spell `https://api.deepseek.com` and
+ // `https://api.groq.com/openai/v1`; both paths below are still that host.
+ expect(addressesPublishedVendorHost("https://api.deepseek.com/v1")).toBe(true);
+ expect(addressesPublishedVendorHost("https://api.deepseek.com/beta")).toBe(true);
+ expect(addressesPublishedVendorHost("https://api.groq.com/v1")).toBe(true);
+ expect(addressesPublishedVendorHost("https://api.openai.com/v1/")).toBe(true);
+ expect(addressesPublishedVendorHost("https://API.OPENAI.COM/v1")).toBe(true);
+ });
+
+ it("leaves a self-hosted gateway, relay, or loopback to the user", () => {
+ for (const baseUrl of [
+ "https://gateway.example.com/v1",
+ "https://relay.example.com",
+ "http://127.0.0.1:11434/v1",
+ "https://llm.internal:8443/v1",
+ ]) {
+ expect(addressesPublishedVendorHost(baseUrl)).toBe(false);
+ }
+ });
+
+ it("does not accept a host that merely contains a vendor host", () => {
+ expect(addressesPublishedVendorHost("https://api.openai.com.evil.test/v1")).toBe(false);
+ expect(addressesPublishedVendorHost("https://openai.com/v1")).toBe(false);
+ expect(addressesPublishedVendorHost("https://api.anthropic.com.evil.test")).toBe(false);
+ });
+
+ it("is false for missing or malformed input", () => {
+ for (const baseUrl of [
+ undefined,
+ "",
+ " ",
+ "not a url",
+ "://broken",
+ "http://",
+ ]) {
+ expect(addressesPublishedVendorHost(baseUrl)).toBe(false);
+ }
+ });
+});
diff --git a/packages/shared/src/provider-presets.ts b/packages/shared/src/provider-presets.ts
index b2ec3f7b8..f93377d77 100644
--- a/packages/shared/src/provider-presets.ts
+++ b/packages/shared/src/provider-presets.ts
@@ -374,6 +374,31 @@ function normalizedVendorKey(value: string | undefined): string {
return (value ?? "").trim().toLowerCase().replace(/_/g, "-");
}
+function endpointHost(value: string | undefined): string | undefined {
+ const normalized = normalizeEndpointUrl(value);
+ if (!normalized) return undefined;
+ try {
+ return new URL(normalized).host.toLowerCase();
+ } catch {
+ return undefined;
+ }
+}
+
+/**
+ * Whether a configured base URL addresses a vendor's own published endpoint.
+ *
+ * Matching is by host, not by the full canonical URL: an OpenAI-compatible
+ * vendor is routinely configured with a path the preset record does not spell
+ * out (`/v1`, a Coding-Plan suffix, a regional host) and that is still the
+ * vendor's host. A row pointed anywhere else belongs to the user — a
+ * self-hosted gateway or a relay — and the runtime decides its request shape.
+ */
+export function addressesPublishedVendorHost(baseUrl: string | undefined): boolean {
+ const host = endpointHost(baseUrl);
+ if (!host) return false;
+ return NAMED_ENDPOINT_PRESETS.some((preset) => endpointHost(preset.baseUrl) === host);
+}
+
function presetByUrl(url: string): NamedEndpointPreset | undefined {
const exact = NAMED_ENDPOINT_PRESETS.find(
(preset) => normalizeEndpointUrl(preset.baseUrl) === url,