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(runtime): use proxy-safe headers for custom completions
Seraph-x49a3e2e70367
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex 7c8847596..5c7754d69 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -1490,11 +1490,16 @@ a published vendor host (`NAMED_ENDPOINT_PRESETS`), on theand not on the OpenCode path that already carries its own session header(§6.2):-- For Completions and Anthropic, the built model's `compat` gains+- For Completions, 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.+ `sessionAffinityFormat: "openai-nosession"`, so the adapter writes+ `x-session-affinity` and `x-client-request-id` without `session_id`. Strict+ gateways can reject the underscore header before authentication (issue+ #2278); the two hyphenated headers preserve session routing. Anthropic keeps+ `sendSessionAffinityHeaders: true` with `sessionAffinityFormat: "openai"`,+ which emits only `x-session-affinity` on that adapter. These defaults are+ spread under the row's own `compat`, so an explicit catalog entry still wins,+ including an explicit Completions `openai` format requiring `session_id`.- 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 candiff --git a/docs/spec/03-runtime/11-provider-model-system.md b/docs/spec/03-runtime/11-provider-model-system.mdindex 8f4402699..f1867f241 100644--- a/docs/spec/03-runtime/11-provider-model-system.md+++ b/docs/spec/03-runtime/11-provider-model-system.md@@ -88,7 +88,11 @@ 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. A custom `openai-responses` row keeps the+`prompt_cache_key` body key. Custom Chat Completions defaults to the adapter's+`openai-nosession` format: `x-session-affinity` and `x-client-request-id`,+without the `session_id` header rejected by strict gateways (issue #2278).+Explicit model `compat` settings still take precedence. A custom+`openai-responses` row keeps theadapter's existing session headers and cache key, and also receives thehyphenated `x-session-affinity` alias so a reverse proxy can route it afterdropped underscore headers. A published vendor host and the OpenCode pathdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 5ee166e85..fd6bbc1e7 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -7980,11 +7980,16 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.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`.+ 7) For Chat Completions, reject `session_id` with a plain-text 400 at the+ capture endpoint and send two turns in one session and one in the other.- **Expected**:- Both captured requests carry a stable per-session identifier that differsbetween the two sessions: `x-session-affinity` and `x-client-request-id`- beside `session_id`, plus `prompt_cache_key` in the body, all holding the+ without `session_id`, plus `prompt_cache_key` in the body, all holding thesession's own conversation id and unchanged across that session's turns.+ - All three Chat Completions turns finish with a complete assistant reply+ through the strict endpoint. Explicit model `compat` can still opt into+ the legacy `openai` headers or disable affinity headers.- The custom Responses request also carries `x-session-affinity` alongsidethe adapter's existing `session_id`, `x-client-request-id`, and`prompt_cache_key`, so a reverse proxy that drops underscore headers can@@ -7996,11 +8001,15 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.- 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+ `03-runtime/11-provider-model-system.md`, issues #1634 and #2278- **Acceptance**: C (chat/stream) + Quality- **Milestone**: M5-- **Status**: Unit-covered (`session-affinity.test.ts`); full gateway capture- journey Draft+- **Status**: Adapter-covered (`session-affinity.test.ts`); the real Runtime /+ HTTP gateway regression (`session-affinity-flow.test.ts`, issue #2278) covers+ repeated Chat Completions turns in two sessions against an edge that returns+ 400 for `session_id`, verifying completed replies, stable hyphenated headers,+ distinct session ids, and the body cache key. Full cross-path gateway capture+ journey Draft.#### E2E-AGENTS-001: Project instruction chain configures an agent sessiondiff --git a/packages/agent-runtime/src/provider-binding.test.ts b/packages/agent-runtime/src/provider-binding.test.tsindex 66504b30c..9157d31a1 100644--- a/packages/agent-runtime/src/provider-binding.test.ts+++ b/packages/agent-runtime/src/provider-binding.test.ts@@ -1705,10 +1705,10 @@ describe("session affinity for the adapters' anonymous endpoints (#1634)", () =>): Record<string, unknown> | undefined =>buildProviderModel(provider).compat as Record<string, unknown> | undefined;- it("gives the built model the adapter's non-OpenRouter session shape", () => {+ it("gives Completions proxy-safe affinity without changing Anthropic", () => {expect(compatOf(ownEndpoint())).toMatchObject({sendSessionAffinityHeaders: true,- sessionAffinityFormat: "openai",+ sessionAffinityFormat: "openai-nosession",});expect(compatOf(@@ -1753,7 +1753,12 @@ describe("session affinity for the adapters' anonymous endpoints (#1634)", () =>).toBeUndefined();});- it("spreads the default under a catalog entry that already answers", () => {+ it.each([+ { sendSessionAffinityHeaders: false, sessionAffinityFormat: "openrouter" as const, sessionHeader: null },+ { sendSessionAffinityHeaders: true, sessionAffinityFormat: "openai" as const, sessionHeader: "session-9" },+ ])("honors explicit catalog affinity settings: $sessionAffinityFormat / $sendSessionAffinityHeaders", async ({+ sendSessionAffinityHeaders, sessionAffinityFormat, sessionHeader,+ }) => {const provider = ownEndpoint();const model = buildProviderModel({...provider,@@ -1767,18 +1772,33 @@ describe("session affinity for the adapters' anonymous endpoints (#1634)", () =>contextWindow: 128_000,maxTokens: 8_192,compat: {- sendSessionAffinityHeaders: false,- sessionAffinityFormat: "openrouter",+ sendSessionAffinityHeaders,+ sessionAffinityFormat,},},});expect(model.compat).toMatchObject({- sendSessionAffinityHeaders: false,- sessionAffinityFormat: "openrouter",+ sendSessionAffinityHeaders,+ sessionAffinityFormat,});+ let headers: Headers | undefined;+ await createProviderModels(provider, model).streamSimple(+ model,+ { messages: [{ role: "user", content: "hello", timestamp: 1 }] },+ {+ sessionId: "session-9",+ fetch: async (_input: RequestInfo | URL, init?: RequestInit) => {+ headers = new Headers(init?.headers);+ return new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } });+ },+ },+ ).result();+ expect(headers?.get("session_id")).toBe(sessionHeader);+ expect(headers?.get("x-session-affinity")).toBe(sessionHeader);+ expect(headers?.get("x-client-request-id")).toBe(sessionHeader);});- it("reaches the wire as the three headers §6.3 names", async () => {+ it("reaches the wire without the session_id header rejected by strict gateways", async () => {const provider = ownEndpoint();const model = buildProviderModel(provider);let headers: Headers | undefined;@@ -1801,7 +1821,7 @@ describe("session affinity for the adapters' anonymous endpoints (#1634)", () =>).result();- expect(headers?.get("session_id")).toBe("session-9");+ expect(headers?.get("session_id")).toBeNull();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/session-affinity-flow.test.ts b/packages/agent-runtime/src/session-affinity-flow.test.tsnew file mode 100644index 000000000..35c83fc7a--- /dev/null+++ b/packages/agent-runtime/src/session-affinity-flow.test.ts@@ -0,0 +1,108 @@+import { createServer, type IncomingHttpHeaders } from "node:http";+import { once } from "node:events";+import { describe, expect, it } from "vitest";+import type { AgentEventEnvelope } from "@pi-desktop/shared";+import { DesktopAgentRuntime } from "./runtime.js";+import type { RuntimeProviderConfig } from "./provider-binding.js";++describe("custom Completions through a strict HTTP gateway (#2278)", () => {+ it("completes repeated turns while keeping distinct sessions identifiable", async () => {+ const requests: Array<{+ headers: IncomingHttpHeaders;+ body: Record<string, unknown>;+ }> = [];+ const server = createServer(async (request, response) => {+ let body = "";+ for await (const chunk of request) body += chunk;+ requests.push({ headers: request.headers, body: JSON.parse(body) });+ // Reproduce the external edge's observed rejection before streaming.+ if (request.headers.session_id !== undefined) {+ response.writeHead(400, { "content-type": "text/plain" });+ response.end("Bad Request");+ return;+ }+ const completion = {+ id: "fixture-completion",+ object: "chat.completion.chunk",+ created: 1,+ model: "fixture-model",+ choices: [{+ index: 0,+ delta: { role: "assistant", content: "Reply from strict gateway" },+ finish_reason: "stop",+ }],+ };+ response.writeHead(200, { "content-type": "text/event-stream" });+ response.end(`data: ${JSON.stringify(completion)}\n\ndata: [DONE]\n\n`);+ });+ server.listen(0, "127.0.0.1");+ await once(server, "listening");+ const address = server.address();+ if (!address || typeof address === "string") throw new Error("Missing fixture port");+ const provider: RuntimeProviderConfig = {+ id: "custom-gateway",+ name: "Strict gateway",+ vendorKey: "custom",+ baseUrl: `http://127.0.0.1:${address.port}/v1`,+ modelId: "fixture-model",+ apiKey: "fixture-only",+ apiStyle: "chat_completions",+ supportsReasoning: false,+ supportedThinkingLevels: ["off"],+ };+ const events: AgentEventEnvelope[] = [];+ const runtimes: DesktopAgentRuntime[] = [];+ const createRuntime = (sessionId: string) => {+ const runtime = new DesktopAgentRuntime({+ sessionId, mode: "agent", provider, thinkingLevel: "off",+ commandShell: {+ id: "bash", label: "Bash", dialect: "posix",+ available: true, isDefault: true,+ },+ host: {+ async call<T>(method: string): Promise<T> {+ if (method === "tools.fileBatchCapabilities") return { version: 1, supported: false } as T;+ if (method === "session.appendMessage") return undefined as T;+ throw new Error(`Unexpected host method: ${method}`);+ },+ },+ onEvent: (event) => events.push(event),+ });+ runtimes.push(runtime);+ return runtime;+ };+ try {+ const first = createRuntime("session-a");+ await first.prompt("hi");+ await first.prompt("hi again");+ await createRuntime("session-b").prompt("hi");++ expect(events.filter(({ event }) => event.type === "error")).toEqual([]);+ const replies = events.flatMap(({ event }) =>+ event.type === "message_end" && event.message.role === "assistant"+ ? [event.message] : []);+ expect(replies).toHaveLength(3);+ expect(replies.every(message =>+ message.status === "complete" && message.content === "Reply from strict gateway")).toBe(true);+ expect(requests).toHaveLength(3);+ expect(requests.map(({ headers }) => headers.session_id)).toEqual([+ undefined, undefined, undefined,+ ]);+ for (const header of ["x-session-affinity", "x-client-request-id"]) {+ expect(requests.map(({ headers }) => headers[header])).toEqual([+ "session-a", "session-a", "session-b",+ ]);+ }+ expect(requests.map(({ body }) => body.prompt_cache_key)).toEqual([+ "session-a", "session-a", "session-b",+ ]);+ } finally {+ try {+ await Promise.all(runtimes.map(runtime => runtime.dispose()));+ } finally {+ server.closeAllConnections();+ await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));+ }+ }+ });+});diff --git a/packages/agent-runtime/src/session-affinity.test.ts b/packages/agent-runtime/src/session-affinity.test.tsindex 46cd84094..002d89b67 100644--- a/packages/agent-runtime/src/session-affinity.test.ts+++ b/packages/agent-runtime/src/session-affinity.test.ts@@ -148,10 +148,10 @@ describe("providerUsesSessionAffinity", () => {});describe("sessionAffinityCompat", () => {- it("returns the adapter's own non-OpenRouter shape for the user's endpoint", () => {+ it("uses proxy-safe Completions headers and preserves the Anthropic format", () => {expect(sessionAffinityCompat(ownGateway, "openai-completions", GATEWAY)).toEqual({sendSessionAffinityHeaders: true,- sessionAffinityFormat: "openai",+ sessionAffinityFormat: "openai-nosession",});expect(sessionAffinityCompat(ownAnthropicRelay, "anthropic-messages", ANTHROPIC_RELAY),@@ -421,9 +421,9 @@ describe("withSessionAffinityOptions", () => {/*** 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.+ * (pi-ai dist/api/openai-completions.js createClient / buildParams): the+ * `openai-nosession` format keeps `x-client-request-id` and `x-session-affinity`+ * beside the body key without the underscore header rejected by strict gateways.*/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 () => {@@ -462,7 +462,7 @@ describe("the pi-ai Completions adapter's session identity", () => {await streamOnce(GATEWAY, ownGateway);expect(sent).toHaveLength(1);- expect(sent[0].headers.get("session_id")).toBe("session-42");+ expect(sent[0].headers.get("session_id")).toBeNull();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");diff --git a/packages/agent-runtime/src/session-affinity.ts b/packages/agent-runtime/src/session-affinity.tsindex b0d4917be..185dbbf59 100644--- a/packages/agent-runtime/src/session-affinity.ts+++ b/packages/agent-runtime/src/session-affinity.ts@@ -52,7 +52,7 @@ const SESSION_AFFINITY_BODY_APIS: ReadonlySet<string> = new Set([export type SessionAffinityCompat = {sendSessionAffinityHeaders: true;- sessionAffinityFormat: "openai";+ sessionAffinityFormat: "openai" | "openai-nosession";};/** The provider fields that decide whether this row is the user's own endpoint. */@@ -86,9 +86,9 @@ export function providerUsesSessionAffinity(/*** 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`.+ * Completions uses `openai-nosession` to keep `x-session-affinity` and+ * `x-client-request-id` without `session_id`, which strict gateways reject+ * (#2278). Anthropic keeps its existing format and `x-session-affinity` header.* 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.*/@@ -99,7 +99,10 @@ export function sessionAffinityCompat(): SessionAffinityCompat | undefined {return SESSION_AFFINITY_COMPAT_APIS.has(api) &&providerUsesSessionAffinity(provider, api, baseUrl)- ? { sendSessionAffinityHeaders: true, sessionAffinityFormat: "openai" }+ ? {+ sendSessionAffinityHeaders: true,+ sessionAffinityFormat: api === "openai-completions" ? "openai-nosession" : "openai",+ }: undefined;}