Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(agent-runtime): cover proxy-safe Responses affinity
vastsabf8acaeb180f
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex 624779465..e1c7441a7 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -1353,24 +1353,31 @@ 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.+the Responses adapters send `session_id` and `x-client-request-id` on each+request, and the Chat Completions and Anthropic Messages adapters send their+session headers 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+reliable to tell them apart: reverse proxies commonly discard `session_id`+because its name contains an underscore, while many gateways do not recognize+`x-client-request-id` as a stable session key.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):+a published vendor host (`NAMED_ENDPOINT_PRESETS`), on the+`openai-completions`, `anthropic-messages`, and `openai-responses` 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+- For Completions and Anthropic, 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 underthe row's own `compat`, so an explicit catalog entry still wins.+- A custom Responses endpoint keeps the adapter's existing `session_id`,+ `x-client-request-id`, and `prompt_cache_key`; agent-runtime adds the stable+ `x-session-affinity` alias through stream options so a reverse proxy can+ route the session after dropping underscore headers.- A Chat Completions request body that carries no `prompt_cache_key` gains thesession id as one, clamped to the adapter's 64-character limit. The key ridesa copy of the payload and is appended after every other payload hook, so an@@ -1379,7 +1386,7 @@ carries its own session header (§6.2):The identity reaches session turns, subagent turns, context-compactionsummaries, and plugin one-shots that were handed a session id. A publishedvendor host keeps its current request bytes, and a caller with no session id-gains no body key.+gains no affinity header or body key.## 7. System prompt compositiondiff --git a/docs/spec/03-runtime/11-provider-model-system.md b/docs/spec/03-runtime/11-provider-model-system.mdindex 12b114f1e..67047b604 100644--- a/docs/spec/03-runtime/11-provider-model-system.md+++ b/docs/spec/03-runtime/11-provider-model-system.md@@ -88,9 +88,12 @@ 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 hostreceives 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).+`prompt_cache_key` body key. A custom `openai-responses` row keeps the+adapter's existing session headers and cache key, and also receives the+hyphenated `x-session-affinity` alias so a reverse proxy can route it after+dropped underscore headers. 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 keepsthe native pi-ai transport metadata instead of treating the row as a genericdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 0f108bda2..5853b0969 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -6829,8 +6829,9 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.- **Preconditions**: Two independent sessions, each with several turns, bound toa provider row whose API style is `chat_completions` and whose base URL pointsat 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.+ published vendor host, a fourth on `anthropic_messages`, and a fifth on+ `openai-responses`, use the same capture endpoint's stand-ins where+ applicable.- **Steps**: 1) Send a turn in each session and capture the full request headersand body of both. 2) Compare the two requests field by field. 3) Trigger acontext-compaction summary in the first session and capture it. 4) Run a@@ -6842,11 +6843,16 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.between the two sessions: `x-session-affinity` and `x-client-request-id`beside `session_id`, plus `prompt_cache_key` in the body, all holding thesession's own conversation id and unchanged across that session's turns.+ - The custom Responses request also carries `x-session-affinity` alongside+ the adapter's existing `session_id`, `x-client-request-id`, and+ `prompt_cache_key`, so a reverse proxy that drops underscore headers can+ still route the session.- The compaction summary, the subagent turn, and the one-shot carry the sameid 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 totheir pre-change requests (the OpenCode row keeps `x-opencode-session`).- - A one-shot call with no session id gains no `prompt_cache_key`.+ - A one-shot call with no session id gains no `prompt_cache_key` or+ `x-session-affinity` header.- **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) + Qualitydiff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex 1751a31f9..54f2190ad 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -7661,19 +7661,24 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.- Agent-runtime stamps a per-session identity onto requests bound for an endpointthe 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+ published vendor host — on the `openai-completions`, `anthropic-messages`,+ and `openai-responses` wire APIs. On Completions and Anthropic, 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 payloadthat carries no `prompt_cache_key` gains the session id as one, clamped to theadapter's 64-character limit. A row's own `compat` still wins, and the key isadded on a copy after every other payload hook.+- A custom Responses row keeps its existing `session_id`, `x-client-request-id`,+ and cache key, and also gets the stable `x-session-affinity` alias so reverse+ proxies that discard underscore headers can route the session.- Identity reaches session turns, subagent turns, context-compaction summaries,and plugin one-shots handed a session id. A published vendor host (matched byhost 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.+ `x-opencode-session`, and the Responses adapters' existing behavior on+ published vendor hosts keep their current request bytes, so no vendor's+ published caching semantics move; a caller with no session id gains no body+ key or `x-session-affinity` header.- Covered by `packages/agent-runtime/src/session-affinity.test.ts` andE2E-PROVIDER-custom-endpoint-session-identity. See issue #1634,`03-runtime/02-agent-runtime.md` §6.3, anddiff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.mdindex c6159dcaf..082c510d7 100644--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md@@ -947,28 +947,33 @@ agent 运行时的职责,与官方 Pi 编码 agent 的归属层保持一致;### 6.3 适配器不作标识的端点上的会话身份(issue #1634)-pi-ai 只在厂商自己发布了约定时才自带对话标识:Responses 适配器每个请求都发,而-Chat Completions 与 Anthropic Messages 适配器只在-`compat.sendSessionAffinityHeaders` 为真时才发,该默认值仅有 OpenRouter;Chat-Completions 的请求体键更窄,硬编码在 `api.openai.com` 上。因此,用户把某一提供商行-指向自己的网关或中转时,同一凭据下的所有会话在出网请求里没有任何字段可以区分,-该网关既无法把一个会话固定到同一后端,也没有按会话隔离 prompt cache 的依据。+pi-ai 只在厂商自己发布了约定时才自带对话标识:Responses 适配器每个请求都会发送+`session_id` 与 `x-client-request-id`,而 Chat Completions 与 Anthropic Messages+适配器只在 `compat.sendSessionAffinityHeaders` 为真时才发送,该默认值仅有+OpenRouter;Chat Completions 的请求体键更窄,硬编码在 `api.openai.com` 上。因此,+用户把某一提供商行指向自己的网关或中转时,同一凭据下的所有会话没有可靠的字段可以+区分:反向代理通常会丢弃名称含下划线的 `session_id`,许多网关也不会把+`x-client-request-id` 识别为稳定会话键。对这种 base URL 主机不属于任何已发布厂商主机(`NAMED_ENDPOINT_PRESETS`)的行,-agent-runtime 自己补上该身份,覆盖 `openai-completions` 与 `anthropic-messages`-两种线协议,但不对已经自带会话标头的 OpenCode 线路(§6.2)生效:+agent-runtime 自己补上该身份,覆盖 `openai-completions`、`anthropic-messages` 与+`openai-responses` 三种线协议,但不对已经自带会话标头的 OpenCode 线路(§6.2)生效:-- 构造出的模型 `compat` 补上 `sendSessionAffinityHeaders: true` 与+- 在 Completions 与 Anthropic 上,构造出的模型 `compat` 补上+ `sendSessionAffinityHeaders: true` 与`sessionAffinityFormat: "openai"`,适配器据此写出 `x-session-affinity` 与`x-client-request-id`,并在格式为 `openai` 时一并写出 `session_id`。该默认值展开在行自身 `compat` 之下,因此显式的目录项仍然优先。+- 自建 Responses 端点保留适配器原有的 `session_id`、`x-client-request-id` 与+ `prompt_cache_key`;agent-runtime 通过 stream options 再加上稳定的+ `x-session-affinity`,即使反向代理丢掉下划线标头也能路由会话。- Chat Completions 的请求体若不含 `prompt_cache_key`,补上会话 id 作为该键,按适配器的 64 字符上限截断。该键添加在载荷副本上,且排在其它所有载荷钩子之后,因此重写载荷的扩展无法把它丢掉。该身份覆盖会话回合、子智能体回合、上下文压缩摘要,以及拿到会话 id 的插件一次性-调用。属于已发布厂商主机的行保持原有出网字节;没有会话 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.mdindex 269ef4be2..19cb2ac9e 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@@ -86,9 +86,10 @@ pi-ai 去发出 `x-opencode-session`。每个提供商行(AI 服务或 OAuth会话身份跟随端点归谁所有。在 `openai-completions` 与 `anthropic-messages` 上,base URL 主机不属于任何已发布厂商主机的行会带上会话亲和标头,并在 Chat-Completions 上带上 `prompt_cache_key` 请求体键,使自建网关或中转可以按会话路由与-缓存。属于已发布厂商主机的行以及 OpenCode 线路保持原有出网字节(issue #1634;-`03-runtime/02-agent-runtime.md` §6.3)。+Completions 上带上 `prompt_cache_key` 请求体键。自建 `openai-responses` 行保留适配器+原有的会话标头与缓存键,并额外带上连字符形式的 `x-session-affinity`,这样反向代理丢掉+下划线标头后仍可按会话路由。属于已发布厂商主机的行以及 OpenCode 线路保持原有出网字节+(issue #1634;`03-runtime/02-agent-runtime.md` §6.3)。当 OAuth 厂商围绕本地 provider 行 id 重建运行时模型时,运行时仍保留 pi-ai原生传输元数据,不会把该行当作普通 OpenAI 端点。GitHub Copilot 请求会保留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.mdindex 5b76ced9a..69d58c90c 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@@ -3806,7 +3806,8 @@ IPC 请求无法关闭。- **前提**:两个互相独立的会话,各进行若干回合,都绑定到 API 风格为`chat_completions`、base URL 指向本地抓包端点(不是已发布厂商主机)的提供商行。- 另有一行位于已发布厂商主机,以及一行使用 `anthropic_messages`。+ 另有一行位于已发布厂商主机、一行使用 `anthropic_messages`,以及一行使用+ `openai-responses`。- **步骤**:1) 在两个会话各发一个回合,抓取两次请求的完整标头与完整请求体。2) 逐字段比对这两个请求。3) 在第一个会话触发一次上下文压缩摘要并抓取。4) 运行一次子智能体回合与一次带会话 id 的插件一次性调用并抓取。@@ -3817,11 +3818,14 @@ IPC 请求无法关闭。`x-client-request-id`,在格式为 `openai` 时还含 `session_id`,请求体中含`prompt_cache_key`,取值都是该会话自己的对话 id,并在该会话的多个回合之间保持不变。+ - 自建 Responses 请求也携带 `x-session-affinity`,同时保留适配器原有的+ `session_id`、`x-client-request-id` 与 `prompt_cache_key`,因此丢弃下划线标头的反向+ 代理仍能路由会话。- 压缩摘要、子智能体回合与一次性调用携带其所属会话的同一个 id,因此网关会把整个会话固定到同一后端。- 位于已发布厂商主机的行与 OpenCode 行的出网请求与改动前逐字节一致(OpenCode行仍带 `x-opencode-session`)。- - 没有会话 id 的一次性调用不会得到 `prompt_cache_key`。+ - 没有会话 id 的一次性调用不会得到 `prompt_cache_key` 或 `x-session-affinity` 标头。- **关联规格**:`03-runtime/02-agent-runtime.md`(§6.2、§6.3)、`03-runtime/11-provider-model-system.md`、issue #1634- **验收**:C (chat/stream) + 质量diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.mdindex 452244dd5..e3dfeb009 100644--- a/docs/zh-CN/spec/08-meta/decisions-log.md+++ b/docs/zh-CN/spec/08-meta/decisions-log.md@@ -5403,15 +5403,17 @@ Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编## 2026-10-13 —— 适配器不作标识的端点上的会话身份(D658)- 对用户自己指向的端点——base URL 主机不属于任何已发布厂商主机的提供商行——agent-runtime- 在 `openai-completions` 与 `anthropic-messages` 两种线协议上补上逐会话身份。构造出的模型+ 在 `openai-completions`、`anthropic-messages` 与 `openai-responses` 三种线协议上补上逐会话身份。在 Completions 与 Anthropic 上,构造出的模型会带上 `compat.sendSessionAffinityHeaders` 与 `sessionAffinityFormat: "openai"`,适配器据此写出 `x-session-affinity` 与 `x-client-request-id`,并在格式为 `openai` 时一并写出`session_id`;Chat Completions 的载荷若不含 `prompt_cache_key`,则补上会话 id 作为该键,按适配器的 64 字符上限截断。行自身 `compat` 仍然优先,该键添加在副本上且排在其它载荷钩子之后。+- 自建 Responses 行保留适配器原有的 `session_id`、`x-client-request-id` 与缓存键,并额外带上稳定的+ `x-session-affinity`,让丢弃下划线标头的反向代理仍可路由会话。- 该身份覆盖会话回合、子智能体回合、上下文压缩摘要,以及拿到会话 id 的插件一次性调用。属于已发布厂商主机的行(按主机与 `NAMED_ENDPOINT_PRESETS` 比对)、OpenCode 线路自带的- `x-opencode-session`,以及 Responses 适配器既有行为都保持原有出网字节,因此不改变任何厂商已发布- 的缓存语义;没有会话 id 的调用方不会得到请求体键。+ `x-opencode-session`,以及已发布厂商主机上 Responses 适配器的行为都保持原有出网字节,因此不改变任何+ 厂商已发布的缓存语义;没有会话 id 的调用方不会得到请求体键或 `x-session-affinity` 标头。- 由 `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.test.ts b/packages/agent-runtime/src/compaction-request.test.tsindex 1702b1dfa..89db7ae2e 100644--- a/packages/agent-runtime/src/compaction-request.test.ts+++ b/packages/agent-runtime/src/compaction-request.test.ts@@ -74,6 +74,46 @@ describe("compactionRequestOptions", () => {expect(options.headers).toEqual({ "X-Team": "platform" });});+ it("adds the proxy-safe affinity header to custom Responses summaries", async () => {+ const responsesProvider: RuntimeProviderConfig = {+ ...provider,+ id: "responses-gateway",+ name: "Responses gateway",+ vendorKey: "custom",+ apiStyle: "responses",+ baseUrl: "https://gateway.example.com/v1",+ };+ const responsesModel = {+ ...model,+ api: "openai-responses",+ provider: responsesProvider.id,+ baseUrl: responsesProvider.baseUrl,+ } as Model<Api>;+ let received: ModelsSimpleStreamOptions | undefined;+ let sentPayload: unknown;+ const collection = {+ completeSimple: async (+ _model: Model<Api>,+ _context: unknown,+ options: ModelsSimpleStreamOptions,+ ) => {+ received = options;+ sentPayload = await options.onPayload?.({ input: [] }, responsesModel);+ return "assistant-message";+ },+ } as unknown as Models;++ const wrapped = withCompactionRequestHeaders(+ collection,+ responsesProvider,+ "session-42",+ );+ await wrapped.completeSimple(responsesModel, context as never, { maxTokens: 4_096 });++ expect(received?.headers).toMatchObject({ "x-session-affinity": "session-42" });+ expect(sentPayload).toMatchObject({ prompt_cache_key: "session-42" });+ });+it("clears a caller-supplied fetch for a Google model, with or without row headers", () => {const callerFetch = vi.fn(async () => new Response("ok"));const googleModel = {diff --git a/packages/agent-runtime/src/compaction-request.ts b/packages/agent-runtime/src/compaction-request.tsindex 19d2c1d51..a008377a4 100644--- a/packages/agent-runtime/src/compaction-request.ts+++ b/packages/agent-runtime/src/compaction-request.ts@@ -30,7 +30,11 @@ import {type RuntimeProviderConfig,} from "./provider-binding.js";import { mergeProviderHeaders, withProviderHeaders } from "./provider-headers.js";-import { providerUsesSessionAffinity, withSessionPromptCacheKey } from "./session-affinity.js";+import {+ providerUsesSessionAffinity,+ withSessionAffinityOptions,+ withSessionPromptCacheKey,+} from "./session-affinity.js";import { compactionRequestShape, type CompactionRequestShape } from "./compaction-diagnostics.js";/**@@ -48,16 +52,19 @@ export function compactionRequestOptions(input: {options?: ModelsSimpleStreamOptions;}): ModelsSimpleStreamOptions {const { provider, sessionId, model, context, options } = input;- return withProviderHeaders(- withOpenCodeSessionHeaders(- { ...options, sessionId, reasoning: requestThinkingLevel(model, options?.reasoning ?? "off") },- { ...openCodeEndpointFromProvider(provider, model), sessionId },- ),- mergeProviderHeaders(- copilotRequestHeaders(provider, context),- provider.headers,+ return withSessionAffinityOptions(+ withProviderHeaders(+ withOpenCodeSessionHeaders(+ { ...options, sessionId, reasoning: requestThinkingLevel(model, options?.reasoning ?? "off") },+ { ...openCodeEndpointFromProvider(provider, model), sessionId },+ ),+ mergeProviderHeaders(+ copilotRequestHeaders(provider, context),+ provider.headers,+ ),+ model.api,),- model.api,+ { provider, api: model.api, baseUrl: model.baseUrl, sessionId },);}diff --git a/packages/agent-runtime/src/one-shot-complete.ts b/packages/agent-runtime/src/one-shot-complete.tsindex a27e93785..2778bb74f 100644--- a/packages/agent-runtime/src/one-shot-complete.ts+++ b/packages/agent-runtime/src/one-shot-complete.ts@@ -28,7 +28,7 @@ import {openCodeEndpointFromProvider,withOpenCodeSessionHeaders,} from "./opencode-session-headers.js";-import { withSessionAffinityPayload } from "./session-affinity.js";+import { withSessionAffinityOptions } from "./session-affinity.js";import { mergeProviderHeaders, withProviderHeaders } from "./provider-headers.js";import {withProviderFetchFailure,@@ -136,7 +136,7 @@ export async function completeOneShot(// 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, {+ const sessionOptions = withSessionAffinityOptions(requestOptions, {provider,api: model.api,baseUrl: model.baseUrl,diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex a779b8ced..b85d50697 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -240,7 +240,7 @@ import {openCodeEndpointFromProvider,withOpenCodeSessionHeaders,} from "./opencode-session-headers.js";-import { withSessionAffinityPayload } from "./session-affinity.js";+import { withSessionAffinityOptions } from "./session-affinity.js";import { withCompactionRequestHeaders } from "./compaction-request.js";import type { CompactionRequestShape } from "./compaction-diagnostics.js";import {@@ -2182,7 +2182,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the),m.api,);- const hookedOptions = withSessionAffinityPayload(+ const hookedOptions = withSessionAffinityOptions(this.withExtensionProviderHooks(requestOptions, m),{provider: this.provider,diff --git a/packages/agent-runtime/src/session-affinity.test.ts b/packages/agent-runtime/src/session-affinity.test.tsindex 736d2901f..46cd84094 100644--- a/packages/agent-runtime/src/session-affinity.test.ts+++ b/packages/agent-runtime/src/session-affinity.test.ts@@ -2,10 +2,11 @@ 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 { streamSimple as responsesStreamSimple } from "@earendil-works/pi-ai/api/openai-responses";import {providerUsesSessionAffinity,sessionAffinityCompat,- withSessionAffinityPayload,+ withSessionAffinityOptions,withSessionPromptCacheKey,type SessionAffinityProvider,} from "./session-affinity.js";@@ -56,9 +57,17 @@ describe("providerUsesSessionAffinity", () => {);});+ it("stamps custom Responses endpoints with a proxy-safe affinity header", () => {+ expect(providerUsesSessionAffinity(ownGateway, "openai-responses", GATEWAY)).toBe(+ true,+ );+ expect(+ providerUsesSessionAffinity(ownGateway, "openai-responses", "https://api.openai.com/v1"),+ ).toBe(false);+ });+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",@@ -269,7 +278,7 @@ describe("withSessionPromptCacheKey", () => {});});-describe("withSessionAffinityPayload", () => {+describe("withSessionAffinityOptions", () => {const input = (overrides: Partial<{provider: SessionAffinityProvider;@@ -288,7 +297,7 @@ describe("withSessionAffinityPayload", () => {it("returns the caller's own options object for a row it does not stamp", () => {const options: SimpleStreamOptions = { temperature: 0 };expect(- withSessionAffinityPayload(options, {+ withSessionAffinityOptions(options, {provider: ownGateway,api: "openai-completions",baseUrl: "https://api.openai.com/v1",@@ -296,27 +305,59 @@ describe("withSessionAffinityPayload", () => {}),).toBe(options);expect(- withSessionAffinityPayload(options, input({ api: "openai-responses" })),+ withSessionAffinityOptions(+ options,+ input({ api: "openai-responses", baseUrl: "https://api.openai.com/v1" }),+ ),).toBe(options);expect(- withSessionAffinityPayload(options, input({ provider: openCodeGoRow })),+ withSessionAffinityOptions(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());+ const result = withSessionAffinityOptions(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("adds a stable hyphenated affinity header to custom Responses options", () => {+ const options: SimpleStreamOptions = {+ temperature: 0,+ sessionId: "session-7",+ headers: { "X-Gateway": "keep" },+ };+ const result = withSessionAffinityOptions(+ options,+ input({ api: "openai-responses" }),+ );++ expect(result).not.toBe(options);+ expect(result.headers).toEqual({+ "X-Gateway": "keep",+ "x-session-affinity": "session-7",+ });+ expect(result.temperature).toBe(0);+ });++ it("does not add a Responses affinity header when the caller has no session id", () => {+ const options: SimpleStreamOptions = { temperature: 0 };+ expect(+ withSessionAffinityOptions(+ options,+ input({ api: "openai-responses", sessionId: undefined }),+ ),+ ).toBe(options);+ });+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 result = withSessionAffinityOptions(options, input());const payload = await result.onPayload?.(adapterPayload, completionsModel);@@ -332,7 +373,7 @@ describe("withSessionAffinityPayload", () => {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 result = withSessionAffinityOptions(options, input());const payload = await result.onPayload?.({ model: "gateway-model-1", stream: true },@@ -347,7 +388,7 @@ describe("withSessionAffinityPayload", () => {const options: SimpleStreamOptions = {onPayload: async () => ({ model: "rewritten", prompt_cache_key: "caller-set" }),};- const result = withSessionAffinityPayload(options, input());+ const result = withSessionAffinityOptions(options, input());expect(await result.onPayload?.({ model: "gateway-model-1" }, completionsModel),@@ -356,7 +397,7 @@ describe("withSessionAffinityPayload", () => {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 result = withSessionAffinityOptions({}, input({ sessionId: undefined }));const payload = await result.onPayload?.(adapterPayload, completionsModel);@@ -367,7 +408,7 @@ describe("withSessionAffinityPayload", () => {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(+ const result = withSessionAffinityOptions({ onPayload: async () => replacement },input({ sessionId: undefined }),);@@ -406,7 +447,7 @@ describe("the pi-ai Completions adapter's session identity", () => {baseUrl,compat: sessionAffinityCompat(provider, "openai-completions", baseUrl),} as Model<"openai-completions">;- const options = withSessionAffinityPayload(+ const options = withSessionAffinityOptions({ apiKey: "sk-test", sessionId: "session-42", fetch: fetchStub },{ provider, api: "openai-completions", baseUrl, sessionId: "session-42" },);@@ -462,7 +503,7 @@ describe("the pi-ai Anthropic adapter's session identity", () => {headers: { "content-type": "text/event-stream" },});};- const options = withSessionAffinityPayload(+ const options = withSessionAffinityOptions({ apiKey: "sk-test", sessionId: "session-42", maxTokens: 16, fetch: fetchStub },{provider: ownAnthropicRelay,@@ -487,3 +528,39 @@ describe("the pi-ai Anthropic adapter's session identity", () => {expect(sent[0].body.prompt_cache_key).toBeUndefined();});});++describe("the pi-ai Responses adapter's proxy-safe session identity", () => {+ it("sends x-session-affinity alongside its existing session headers", async () => {+ const model = {+ ...completionsModel,+ api: "openai-responses",+ baseUrl: GATEWAY,+ } as Model<"openai-responses">;+ 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(JSON.stringify({ error: { message: "fixture response" } }), {+ status: 502,+ headers: { "content-type": "application/json" },+ });+ };+ const options = withSessionAffinityOptions(+ { apiKey: "sk-test", sessionId: "session-42", fetch: fetchStub },+ { provider: ownGateway, api: "openai-responses", baseUrl: GATEWAY, sessionId: "session-42" },+ );++ await responsesStreamSimple(+ model,+ { messages: [{ role: "user", content: "hi", timestamp: 1 }] } as never,+ options,+ ).result();++ 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");+ });+});diff --git a/packages/agent-runtime/src/session-affinity.ts b/packages/agent-runtime/src/session-affinity.tsindex 8701ee482..b0d4917be 100644--- a/packages/agent-runtime/src/session-affinity.ts+++ b/packages/agent-runtime/src/session-affinity.ts@@ -27,10 +27,22 @@ import { clampOpenAIPromptCacheKey } from "@earendil-works/pi-ai/api/openai-promimport { isOpenCodeEndpoint } from "./opencode-session-headers.js";import type { RuntimeProviderConfig } from "./provider-binding.js";-/** Wire APIs whose adapter emits the session headers from `compat`. */+/** Wire APIs where PI-Desktop preserves session identity for custom endpoints. */const SESSION_AFFINITY_APIS: ReadonlySet<string> = new Set(["openai-completions","anthropic-messages",+ "openai-responses",+]);++/** Wire APIs whose adapter reads session headers from `compat`. */+const SESSION_AFFINITY_COMPAT_APIS: ReadonlySet<string> = new Set([+ "openai-completions",+ "anthropic-messages",+]);++/** Responses has native session headers, but needs this proxy-safe alias. */+const SESSION_AFFINITY_OPTION_HEADER_APIS: ReadonlySet<string> = new Set([+ "openai-responses",]);/** Wire APIs that carry the conversation key in the request body. */@@ -85,7 +97,8 @@ export function sessionAffinityCompat(api: string,baseUrl: string | undefined,): SessionAffinityCompat | undefined {- return providerUsesSessionAffinity(provider, api, baseUrl)+ return SESSION_AFFINITY_COMPAT_APIS.has(api) &&+ providerUsesSessionAffinity(provider, api, baseUrl)? { sendSessionAffinityHeaders: true, sessionAffinityFormat: "openai" }: undefined;}@@ -118,8 +131,11 @@ export function withSessionPromptCacheKey(input: {}/**- * `options` with the conversation body key appended after every other- * `onPayload` hook, so a payload-rewriting extension cannot drop it.+ * `options` with session identity appended at the request boundary. Responses+ * already emits `session_id`, but common reverse proxies drop underscore+ * headers; add the stable hyphenated alias for custom endpoints. Completions+ * gets its missing body key 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@@ -127,7 +143,7 @@ export function withSessionPromptCacheKey(input: {* caller with no session id; there the hook adds nothing and the adapter keeps* its own payload.*/-export function withSessionAffinityPayload(+export function withSessionAffinityOptions(options: SimpleStreamOptions,input: {provider: SessionAffinityProvider;@@ -137,17 +153,32 @@ export function withSessionAffinityPayload(},): 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;+ if (!enabled) return options;++ const sessionId = input.sessionId?.trim();+ let nextOptions = options;+ if (sessionId && SESSION_AFFINITY_OPTION_HEADER_APIS.has(input.api)) {+ const headers = { ...(options.headers ?? {}) };+ for (const key of Object.keys(headers)) {+ if (key.toLowerCase() === "x-session-affinity") delete headers[key];+ }+ nextOptions = {+ ...options,+ headers: { ...headers, "x-session-affinity": sessionId },+ };+ }++ if (!SESSION_AFFINITY_BODY_APIS.has(input.api)) return nextOptions;+ const previous = nextOptions.onPayload;return {- ...options,+ ...nextOptions,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,+ sessionId,enabled,});// Nothing to change keeps the hook's own return value, so an untoucheddiff --git a/packages/agent-runtime/src/subagent-model-binding.ts b/packages/agent-runtime/src/subagent-model-binding.tsindex 4406edfbf..183b30ada 100644--- a/packages/agent-runtime/src/subagent-model-binding.ts+++ b/packages/agent-runtime/src/subagent-model-binding.ts@@ -11,7 +11,7 @@ import {openCodeEndpointFromProvider,withOpenCodeSessionHeaders,} from "./opencode-session-headers.js";-import { withSessionAffinityPayload } from "./session-affinity.js";+import { withSessionAffinityOptions } from "./session-affinity.js";import { mergeProviderHeaders, withProviderHeaders } from "./provider-headers.js";import { clampOutputToContext } from "./output-cap.js";import {@@ -103,7 +103,7 @@ export function subagentModelBinding(opts: {// 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, {+ const sessionOptions = withSessionAffinityOptions(requestOptions, {provider: opts.provider,api: m.api,baseUrl: m.baseUrl,