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(compaction): send the session id as the summary prompt cache key
danfan8846ef00ccb9
diff --git a/docs/project/unreleased.md b/docs/project/unreleased.mdindex 552c8cac6..62f28b6ce 100644--- a/docs/project/unreleased.md+++ b/docs/project/unreleased.md@@ -1,5 +1,11 @@# Unreleased changes+- `/compact` and automatic context compaction work again on a gateway that+ fronts a Codex backend. The summary request of a checkpoint now carries the+ conversation identity every other turn of the session sends+ (`prompt_cache_key`), instead of being the one request the gateway answers+ with `400 invalid codex request`.+- Claude models on a GitHub Copilot account no longer fail with "missingrequired Authorization header". Their Anthropic Messages requests nowauthenticate with `Authorization: Bearer` instead of sending the Copilotdiff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex 06aeb6d7f..e06ea540e 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -1239,6 +1239,17 @@ hands to compaction. That request carries the session's conversation id ratherthan the per-call id the harness would otherwise mint, so a summary reaches thesame gateway backend as the conversation it summarizes.+The same seam restores the conversation key itself. pi-agent-core asks for+`cacheRetention: "none"` on a summary, and the Responses-shaped adapters read+that as "no `prompt_cache_key`", so the summary alone drops the identity every+other turn sends; a gateway fronting a Codex backend rejects such a request with+400 `invalid_responses_request`. For `openai-responses` and+`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+payload hook keeps its own object and its return value still wins.+## 7. System prompt compositiondiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex d81b99fbb..e2be8a831 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -5749,6 +5749,12 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.8. Run a turn where the model calls `new_context` well below the hard budget.9. Invoke `/compact` manually while idle.- **Expected**:+ - The summary request of every checkpoint carries the session's own+ conversation identity: on the Responses-shaped providers+ (`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.- Each `turn_end` is evaluated before another provider request and nevermarks the overall task idle; composer/config controls remain blocked until`agent_end`, `error`, or manual-only `compaction_end`. In-run follow-updiff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.mdindex e38e0c540..8ee838d4d 100644--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md@@ -888,6 +888,15 @@ agent 运行时的职责,与官方 Pi 编码 agent 的归属层保持一致;上。该请求携带会话自己的对话 id,而不是 harness 否则会生成的按次 id,这样摘要就与它所压缩的对话落在同一个网关后端。+同一接缝也会补回对话标识本身:pi-agent-core 对摘要请求要求+`cacheRetention: "none"`,而 Responses 形状的适配器据此不发送+`prompt_cache_key`,于是只有摘要请求会丢掉其他回合都会携带的身份;对接 Codex+后端的网关会以 400 `invalid_responses_request` 拒绝这种请求。因此对+`openai-responses` 与 `openai-codex-responses`,摘要载荷会带上会话 id 作为+`prompt_cache_key`(按适配器的 64 字符上限截断),除非适配器或调用方已设置过。+其他线协议的载荷保持适配器构造的原样;该键添加在副本上,因此调用方的载荷钩子仍+保留自己的对象,其返回值仍然生效。+## 7. 系统提示组成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 092f4e1b3..c983cdbf8 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@@ -3517,6 +3517,11 @@ IPC 请求无法关闭。8. 运行模型调用远低于硬预算的 `new_context` 的回合。9. 空闲时手动调用 `/compact`。- **预期**:+ - 每个检查点的摘要请求都携带会话自己的对话身份:在 Responses 形状的提供商+ (`openai-responses`、`openai-codex-responses`)上,出站载荷会像会话的普通+ 回合一样把会话 id 作为 `prompt_cache_key` 发出,因此对接 Codex 后端的网关会+ 接受该请求,而不是返回 400 `invalid_responses_request`。其他线协议的提供商+ 保持不变。- 每个 `turn_end` 在另一个提供商请求之前都会被评估,并且永远不会标记整体任务空闲; composer/config 控件保持阻塞状态,直到`agent_end`、`error` 或仅手动的 `compaction_end`。diff --git a/packages/agent-runtime/src/compaction-request.test.ts b/packages/agent-runtime/src/compaction-request.test.tsindex 989577761..457f8f9d7 100644--- a/packages/agent-runtime/src/compaction-request.test.ts+++ b/packages/agent-runtime/src/compaction-request.test.ts@@ -1,5 +1,5 @@import { describe, expect, it, vi } from "vitest";-import type { Api, Model, Models } from "@earendil-works/pi-ai";+import type { Api, Model, Models, ModelsSimpleStreamOptions } from "@earendil-works/pi-ai";import {OPENCODE_CLIENT_HEADER,OPENCODE_CLIENT_VALUE,@@ -137,3 +137,125 @@ describe("withCompactionRequestHeaders", () => {expect(getModel).toHaveBeenCalledWith("row-uuid", "glm-5.3-flash");});});++describe("compaction summary conversation key", () => {+ /** A collection whose one request hands its own payload to the option hook. */+ function recordPayload(api: string, seed: Record<string, unknown> = {}) {+ const summaryModel = { ...model, api } as Model<Api>;+ const calls: { payload: Record<string, unknown>; result: unknown }[] = [];+ const collection = {+ completeSimple: async (+ _model: unknown,+ _context: unknown,+ options: ModelsSimpleStreamOptions,+ ) => {+ const payload: Record<string, unknown> = { input: [], ...seed };+ const result = await options.onPayload?.(payload, summaryModel);+ calls.push({ payload, result });+ return "assistant-message";+ },+ } as unknown as Models;+ return {+ model: summaryModel,+ calls,+ wrapped: withCompactionRequestHeaders(collection, provider, "session-1"),+ };+ }++ it.each(["openai-responses", "openai-codex-responses"])(+ "carries the session id as the prompt cache key for %s",+ async (api) => {+ const { model: summaryModel, calls, wrapped } = recordPayload(api);++ await wrapped.completeSimple(summaryModel, context as never, { maxTokens: 4_096 });++ const [call] = calls;+ const sent = (call?.result === undefined ? call?.payload : call?.result) as Record<string, unknown>;+ expect(sent.prompt_cache_key).toBe("session-1");+ // The adapter's own object stays untouched; the key rides the replacement.+ expect(call?.payload.prompt_cache_key).toBeUndefined();+ },+ );++ it.each(["openai-completions", "anthropic-messages", "google-generative-ai"])(+ "leaves a %s payload exactly as the adapter built it",+ async (api) => {+ const { model: summaryModel, calls, wrapped } = recordPayload(api);++ await wrapped.completeSimple(summaryModel, context as never, { maxTokens: 4_096 });++ const [call] = calls;+ expect(call?.result).toBeUndefined();+ expect(call?.payload).not.toHaveProperty("prompt_cache_key");+ },+ );++ it("keeps a prompt cache key the adapter already set", async () => {+ const { model: summaryModel, calls, wrapped } = recordPayload("openai-responses", {+ prompt_cache_key: "explicit-key",+ });++ await wrapped.completeSimple(summaryModel, context as never, { maxTokens: 4_096 });++ const [call] = calls;+ expect(call?.result).toBeUndefined();+ expect(call?.payload.prompt_cache_key).toBe("explicit-key");+ });++ it("clamps a long session id the way the Responses adapter does", async () => {+ const collection = {+ completeSimple: async (+ _model: unknown,+ _context: unknown,+ options: ModelsSimpleStreamOptions,+ ) => {+ const payload: Record<string, unknown> = { input: [] };+ const result = await options.onPayload?.(+ payload,+ { ...model, api: "openai-responses" } as Model<Api>,+ );+ return result === undefined ? payload : result;+ },+ } as unknown as Models;+ const summaryModel = { ...model, api: "openai-responses" } as Model<Api>;+ const wrapped = withCompactionRequestHeaders(collection, provider, "s".repeat(80));++ const sent = (await wrapped.completeSimple(summaryModel, context as never, {+ maxTokens: 4_096,+ })) as unknown as Record<string, unknown>;++ expect(sent.prompt_cache_key).toBe("s".repeat(64));+ });++ it("keeps an existing hook's replacement and mutation semantics", async () => {+ const replaced = { input: [], replaced: true };+ const { model: summaryModel, calls, wrapped } = recordPayload("openai-responses");++ await wrapped.completeSimple(summaryModel, context as never, {+ maxTokens: 4_096,+ onPayload: () => replaced,+ });++ const [call] = calls;+ const sent = (call?.result === undefined ? call?.payload : call?.result) as Record<string, unknown>;+ expect(sent.replaced).toBe(true);+ expect(sent.prompt_cache_key).toBe("session-1");+ expect(replaced).not.toHaveProperty("prompt_cache_key");++ const second = recordPayload("openai-responses");+ await second.wrapped.completeSimple(second.model, context as never, {+ maxTokens: 4_096,+ onPayload: (payload) => {+ (payload as Record<string, unknown>).mutated = true;+ return undefined;+ },+ });++ const [mutated] = second.calls;+ const sentMutation = (mutated?.result === undefined+ ? mutated?.payload+ : mutated?.result) as Record<string, unknown>;+ expect(sentMutation.mutated).toBe(true);+ expect(sentMutation.prompt_cache_key).toBe("session-1");+ });+});diff --git a/packages/agent-runtime/src/compaction-request.ts b/packages/agent-runtime/src/compaction-request.tsindex 99247f402..293344c07 100644--- a/packages/agent-runtime/src/compaction-request.ts+++ b/packages/agent-runtime/src/compaction-request.ts@@ -18,6 +18,7 @@ import type {Models,ModelsSimpleStreamOptions,} from "@earendil-works/pi-ai";+import { clampOpenAIPromptCacheKey } from "@earendil-works/pi-ai/api/openai-prompt-cache";import {openCodeEndpointFromProvider,withOpenCodeSessionHeaders,@@ -56,6 +57,42 @@ export function compactionRequestOptions(input: {);}+/**+ * The two wire APIs that key a conversation by `prompt_cache_key`. A gateway+ * fronting a Codex backend rejects a request without it (400+ * `invalid_responses_request`), and the session's own turns always carry it.+ */+const SUMMARY_CONVERSATION_APIS = new Set([+ "openai-responses",+ "openai-codex-responses",+]);++/**+ * pi-ai's Responses adapters attach `prompt_cache_key` only while the caller+ * keeps some cache retention, and pi-agent-core asks for `"none"` on a summary,+ * so the summary alone loses the conversation identity the adapter would have+ * sent. Restore it for the Responses-shaped APIs and leave every other payload+ * byte-identical. The adapter's own object is never mutated: the key rides a+ * shallow copy that the caller's `onPayload` return value can still replace.+ */+function withSummaryPromptCacheKey(input: {+ payload: unknown;+ api: string;+ sessionId: string;+}): unknown {+ if (!SUMMARY_CONVERSATION_APIS.has(input.api)) return input.payload;+ if (!input.payload || typeof input.payload !== "object" || Array.isArray(input.payload)) {+ return input.payload;+ }+ const body = input.payload as Record<string, unknown>;+ if (body.prompt_cache_key !== undefined && body.prompt_cache_key !== null) {+ return input.payload;+ }+ const key = clampOpenAIPromptCacheKey(input.sessionId);+ if (!key) return input.payload;+ return { ...body, prompt_cache_key: key };+}+/*** `models` with compaction's request routed through that header boundary.*@@ -68,12 +105,25 @@ export function withCompactionRequestHeaders(provider: RuntimeProviderConfig,sessionId: string,): Models {- const completeSimple: Models["completeSimple"] = (model, context, options) =>- models.completeSimple(- model,- context,- compactionRequestOptions({ provider, sessionId, model, context, options }),- );+ const completeSimple: Models["completeSimple"] = (model, context, options) => {+ const requestOptions = compactionRequestOptions({ provider, sessionId, model, context, options });+ const previousOnPayload = requestOptions.onPayload;+ if (SUMMARY_CONVERSATION_APIS.has(model.api)) {+ requestOptions.onPayload = async (payload, requestModel) => {+ const replacement = await previousOnPayload?.(payload, requestModel);+ const base = replacement === undefined ? payload : replacement;+ const keyed = withSummaryPromptCacheKey({+ payload: base,+ api: requestModel.api,+ sessionId,+ });+ // 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;+ };+ }+ return models.completeSimple(model, context, requestOptions);+ };return new Proxy(models, {get: (target, property, receiver) =>property === "completeSimple"diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex f3c844e43..62d155c82 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -10244,3 +10244,86 @@ describe("DesktopAgentRuntime Google Generative AI transport (#1072)", () => {}}, 20_000);});++describe("DesktopAgentRuntime summary conversation key", () => {+ /** Minimal 200 SSE answer for a Responses summary request. */+ function summarySse(): Response {+ const item = {+ id: "msg_fixture_summary",+ type: "message",+ role: "assistant",+ status: "completed",+ content: [{ type: "output_text", text: "A short synthetic summary.", annotations: [] }],+ };+ const events = [+ { type: "response.created", response: { id: "resp_fixture_summary" } },+ { type: "response.output_item.added", output_index: 0, item: { ...item, content: [] } },+ { type: "response.output_text.delta", output_index: 0, content_index: 0, delta: "A short synthetic summary." },+ { type: "response.output_item.done", output_index: 0, item },+ {+ type: "response.completed",+ response: {+ id: "resp_fixture_summary",+ status: "completed",+ output: [item],+ usage: { input_tokens: 100, output_tokens: 8 },+ },+ },+ ];+ return new Response(+ events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(""),+ { headers: { "content-type": "text/event-stream" } },+ );+ }++ it("sends the session id so a conversation-keyed gateway accepts the summary request", async () => {+ const requests: Record<string, unknown>[] = [];+ const fetchMock = vi.fn(async (_input: unknown, init?: RequestInit) => {+ requests.push(JSON.parse(String(init?.body)) as Record<string, unknown>);+ return summarySse();+ });+ const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);+ vi.stubGlobal("fetch", fetchMock);+ const runtime = createRuntime({+ provider: {+ ...provider,+ apiStyle: "responses",+ baseUrl: "https://summary-fixture.invalid/v1",+ apiKey: "sk-fixture-not-for-logs",+ },+ history: [+ {+ id: "old-user",+ role: "user",+ content: "private-fixture-history ".repeat(6_000),+ createdAt: "2026-09-25T00:00:00Z",+ },+ {+ id: "old-assistant",+ role: "assistant",+ content: "Earlier work is complete.",+ status: "complete",+ createdAt: "2026-09-25T00:00:01Z",+ },+ {+ id: "latest-user",+ role: "user",+ content: "Keep working after the checkpoint.",+ createdAt: "2026-09-25T00:00:02Z",+ },+ ],+ });+ try {+ await runtime.compactManually();++ expect(requests).toHaveLength(1);+ expect(requests[0]?.prompt_cache_key).toBe("session-1");+ const logged = stderr.mock.calls.map(([chunk]) => String(chunk)).join("");+ expect(logged).not.toContain("compaction summary failed");+ } finally {+ await runtime.dispose();+ stderr.mockRestore();+ vi.unstubAllGlobals();+ }+ });+});