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): preserve Copilot Bearer auth for Claude models
Yinglun Zhangabed67371bd1
diff --git a/docs/project/unreleased.md b/docs/project/unreleased.mdindex 66c69f732..552c8cac6 100644--- a/docs/project/unreleased.md+++ b/docs/project/unreleased.md@@ -1,5 +1,10 @@# Unreleased changes+- Claude models on a GitHub Copilot account no longer fail with "missing+ required Authorization header". Their Anthropic Messages requests now+ authenticate with `Authorization: Bearer` instead of sending the Copilot+ token as `X-Api-Key`.+- Google Gemini rows send requests again. A provider row on the nativegenerative-AI endpoint no longer hands pi-ai's Google adapter the internalresponse-capture `fetch` it refuses before the request leaves, custom providerdiff --git a/docs/spec/03-runtime/11-provider-model-system.md b/docs/spec/03-runtime/11-provider-model-system.mdindex 433ef74cd..f27f41df5 100644--- a/docs/spec/03-runtime/11-provider-model-system.md+++ b/docs/spec/03-runtime/11-provider-model-system.md@@ -94,6 +94,12 @@ headers, including `Editor-Version`, `Editor-Plugin-Version`, andowns auth binding and transcript identity, and user-supplied provider headersremain the final override.+Copilot Anthropic Messages (Claude) requests carry the per-request OAuth token+as `Authorization: Bearer` with `X-Api-Key` removed, because pi-ai+only selects Copilot Bearer auth when `model.provider` is `github-copilot`.+OpenAI-style Copilot wire APIs keep signing the token as the request key; all+wires retain per-request auth resolution and the account-specific `baseUrl`.+Zhipu / GLM and Z.AI are named OpenAI-compatible endpoint presets among ashort models.dev-backed Service list of first-party vendors (includingXiaomi). The add-provider Service picker persists the matching models.devdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex c4200cbf0..aa5456842 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -892,20 +892,24 @@ identify the platform validation still needed.headers. 2) Send a follow-up after the assistant response and capture thenext request. 3) Repeat with an image attachment when the selected modelsupports vision. 4) Set a saved custom header with the same name as one of- the Copilot defaults and send another turn.+ the Copilot defaults and send another turn. 5) Select a Claude model on the+ same account (Anthropic Messages) and send a turn, capturing its auth and+ identity headers.- **Expected**: Every Copilot model request includes the pinned pi-aitransport identity headers `Editor-Version`, `Editor-Plugin-Version`, and`Copilot-Integration-Id`. `X-Initiator` is `user` for a user-led request and`agent` for a continuation; `Openai-Intent` is `conversation-edits`, andimage requests include `Copilot-Vision-Request: true`. The OAuth row keepsits local provider id for account binding, and a saved custom header remains- the final override.+ the final override. Claude requests carry `Authorization: Bearer <Copilot token>`+ and no `X-Api-Key`, while retaining the same IDE identity and context headers.- **Specs linked**: `03-runtime/11-provider-model-system.md`,`03-runtime/12-provider-config-schema.md`, ADR 0095- **Acceptance**: B (model configuration), F (runtime provider requests)- **Milestone**: M2- **Status**: Unit-covered (row-scoped model headers and request-context- headers); live Copilot account journey pending+ headers, Anthropic Messages Bearer auth and rotating tokens); live Copilot+ account journey pending#### E2E-005H: Select every visible model from a long service listdiff --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 afd48c05c..1a00893c7 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@@ -91,6 +91,12 @@ pi-ai 去发出 `x-opencode-session`。每个提供商行(AI 服务或 OAuth`X-Initiator`、`Openai-Intent` 与图像请求标头。本地行 id 仍然拥有认证绑定与对话记录身份;用户设置的提供商 headers 仍是最后的覆盖层。+Copilot 的 Anthropic Messages(Claude)请求将每次请求解析的 OAuth 令牌作为+`Authorization: Bearer` 标头认证发送,不携带 `X-Api-Key`,因为 pi-ai 仅在+`model.provider` 为 `github-copilot` 时选择 Copilot Bearer 认证。+OpenAI 风格的 Copilot 线路 API 仍将令牌作为请求密钥签名;所有线路均保留+逐请求认证解析与账户专属的 `baseUrl`。+智谱 / GLM 与 Z.AI 是命名的 OpenAI 兼容端点预设,收录在一份由 models.dev支撑的、简短的第一方厂商服务列表中(含小米)。添加提供商时的「服务」选择器会持久化匹配的 models.dev `vendorKey`,并使用已发布的端点,在命名服务这条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 9fe563bd2..0822edfd7 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@@ -394,12 +394,12 @@ task-candidate E2E 从请求工作树运行,但使用主工作区已经准备#### E2E-005J:GitHub Copilot OAuth 请求携带原生 IDE 标头- **前提条件**:已有一个登录的 GitHub Copilot OAuth 账户并选定模型;确定性的捕获代理会记录模型请求标头。-- **步骤**:1)针对该账户发起 Agent 回合并记录请求标头。2)助手回复后发送后续回合并记录下一次请求。3)选定模型支持视觉时,用图像附件重复测试。4)设置一个与 Copilot 默认标头同名的已保存自定义 header,再发送一次回合。-- **预期**:每次 Copilot 模型请求都包含固定 pin 的 pi-ai 传输身份标头 `Editor-Version`、`Editor-Plugin-Version` 与 `Copilot-Integration-Id`。用户发起的请求中 `X-Initiator` 为 `user`,延续请求中为 `agent`;`Openai-Intent` 为 `conversation-edits`,图像请求包含 `Copilot-Vision-Request: true`。OAuth 行继续使用本地 provider id 进行账户绑定,已保存的自定义 header 仍是最后的覆盖层。+- **步骤**:1)针对该账户发起 Agent 回合并记录请求标头。2)助手回复后发送后续回合并记录下一次请求。3)选定模型支持视觉时,用图像附件重复测试。4)设置一个与 Copilot 默认标头同名的已保存自定义 header,再发送一次回合。5)在同一账户上选择 Claude 模型(Anthropic Messages)并发送回合,记录认证与身份标头。+- **预期**:每次 Copilot 模型请求都包含固定 pin 的 pi-ai 传输身份标头 `Editor-Version`、`Editor-Plugin-Version` 与 `Copilot-Integration-Id`。用户发起的请求中 `X-Initiator` 为 `user`,延续请求中为 `agent`;`Openai-Intent` 为 `conversation-edits`,图像请求包含 `Copilot-Vision-Request: true`。OAuth 行继续使用本地 provider id 进行账户绑定,已保存的自定义 header 仍是最后的覆盖层。Claude 请求携带 `Authorization: Bearer <Copilot token>`,不携带 `X-Api-Key`,并保留相同的 IDE 身份与上下文标头。- **链接规格**:`03-runtime/11-provider-model-system.md`、`03-runtime/12-provider-config-schema.md`、ADR 0095- **验收**:B(模型配置)、F(运行时提供商请求)- **里程碑**:M2-- **状态**:单元覆盖(行级模型标头与请求上下文标头);真实 Copilot 账户旅程待验证+- **状态**:单元覆盖(行级模型标头、请求上下文标头、Anthropic Messages Bearer 认证与令牌轮换);真实 Copilot 账户旅程待验证#### E2E-006:密钥在重启后仍然存在diff --git a/packages/agent-runtime/src/provider-binding.test.ts b/packages/agent-runtime/src/provider-binding.test.tsindex bfef94b6a..ccd53816c 100644--- a/packages/agent-runtime/src/provider-binding.test.ts+++ b/packages/agent-runtime/src/provider-binding.test.ts@@ -116,6 +116,42 @@ describe("Anthropic runtime endpoint", () => {expect(result.stopReason).toBe("error");expect(urls).toEqual(["https://gw.example/anthropic/v1/messages?beta=true"]);});++ it("signs a plain Anthropic API-key row without a Bearer header", async () => {+ const provider: RuntimeProviderConfig = {+ ...keyedProvider,+ id: "anthropic-api-key-row",+ name: "Anthropic",+ baseUrl: "https://api.anthropic.com",+ modelId: "claude-sonnet-4-6",+ apiStyle: "anthropic_messages",+ };+ const model = buildProviderModel(provider);+ let request: Request | undefined;+ const fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ request = new Request(input, init);+ return new Response(+ JSON.stringify({ type: "error", error: { type: "invalid_request_error", message: "test response" } }),+ { status: 400, headers: { "content-type": "application/json" } },+ );+ });++ const result = await createProviderModels(provider, model)+ .streamSimple(+ model,+ {+ systemPrompt: "system",+ messages: [{ role: "user", content: "hello", timestamp: Date.now() }],+ tools: [],+ },+ { fetch, maxRetries: 0 },+ )+ .result();++ expect(result.stopReason).toBe("error");+ expect(request?.headers.get("x-api-key")).toBe("sk-test");+ expect(request?.headers.get("Authorization")).toBeNull();+ });});describe("Anthropic adaptive thinking from models.dev reasoning options", () => {@@ -850,6 +886,98 @@ describe("GitHub Copilot transport identity", () => {expect(request?.headers.get("Copilot-Integration-Id")).toBe("vscode-chat");expect(request?.headers.get("X-Initiator")).toBe("user");expect(request?.headers.get("Openai-Intent")).toBe("conversation-edits");+ expect(request?.headers.get("Authorization")).toBe("Bearer copilot-token");+ expect(request?.headers.get("x-api-key")).toBeNull();+ });++ it("sends Bearer auth and the complete identity on a row-scoped Claude request", async () => {+ const claudeProvider: RuntimeProviderConfig = {+ ...provider,+ modelId: "claude-sonnet-4.6",+ apiStyle: "anthropic_messages",+ resolveAuth: async () => ({+ apiKey: "copilot-token",+ baseUrl: "https://api.business.githubcopilot.com",+ }),+ };+ const model = buildProviderModel(claudeProvider);+ const context = {+ systemPrompt: "system",+ messages: [{ role: "user" as const, content: "hello", timestamp: Date.now() }],+ tools: [],+ };+ let request: Request | undefined;+ const fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ request = new Request(input, init);+ return new Response(+ JSON.stringify({ type: "error", error: { type: "invalid_request_error", message: "test response" } }),+ { status: 400, headers: { "content-type": "application/json" } },+ );+ });++ const result = await createProviderModels(claudeProvider, model)+ .streamSimple(model, context, {+ fetch,+ maxRetries: 0,+ headers: copilotRequestHeaders(claudeProvider, context),+ })+ .result();++ expect(result.stopReason).toBe("error");+ expect(request?.headers.get("Authorization")).toBe("Bearer copilot-token");+ expect(request?.headers.get("x-api-key")).toBeNull();+ expect(request?.headers.get("Editor-Version")).toBe("vscode/1.107.0");+ expect(request?.headers.get("Editor-Plugin-Version")).toBe("copilot-chat/0.35.0");+ expect(request?.headers.get("Copilot-Integration-Id")).toBe("vscode-chat");+ expect(request?.headers.get("X-Initiator")).toBe("user");+ expect(request?.headers.get("Openai-Intent")).toBe("conversation-edits");+ expect(request?.url).toBe("https://api.business.githubcopilot.com/v1/messages?beta=true");+ expect(model.provider).toBe(claudeProvider.id);+ });++ it("re-resolves the rotating Bearer token for each row-scoped Claude request", async () => {+ const resolveAuth = vi.fn<NonNullable<RuntimeProviderConfig["resolveAuth"]>>()+ .mockResolvedValueOnce({ apiKey: "first-token" })+ .mockResolvedValueOnce({ apiKey: "second-token" });+ const claudeProvider: RuntimeProviderConfig = {+ ...provider,+ modelId: "claude-sonnet-4.6",+ apiStyle: "anthropic_messages",+ resolveAuth,+ };+ const model = buildProviderModel(claudeProvider);+ const models = createProviderModels(claudeProvider, model);+ const context = {+ systemPrompt: "system",+ messages: [{ role: "user" as const, content: "hello", timestamp: Date.now() }],+ tools: [],+ };+ const requests: Request[] = [];+ const fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ requests.push(new Request(input, init));+ return new Response(+ JSON.stringify({ type: "error", error: { type: "invalid_request_error", message: "test response" } }),+ { status: 400, headers: { "content-type": "application/json" } },+ );+ });++ for (let turn = 0; turn < 2; turn++) {+ const result = await models+ .streamSimple(model, context, {+ fetch,+ maxRetries: 0,+ headers: copilotRequestHeaders(claudeProvider, context),+ })+ .result();+ expect(result.stopReason).toBe("error");+ }++ expect(requests.map((request) => request.headers.get("Authorization"))).toEqual([+ "Bearer first-token",+ "Bearer second-token",+ ]);+ expect(requests.map((request) => request.headers.get("x-api-key"))).toEqual([null, null]);+ expect(resolveAuth).toHaveBeenCalledTimes(2);});});diff --git a/packages/agent-runtime/src/provider-binding.ts b/packages/agent-runtime/src/provider-binding.tsindex 64fd7cb8a..575bb335d 100644--- a/packages/agent-runtime/src/provider-binding.ts+++ b/packages/agent-runtime/src/provider-binding.ts@@ -232,6 +232,38 @@ export function copilotRequestHeaders(});}+/**+ * Row-scoped models bypass pi-ai's native Copilot Bearer branch, so the token+ * would leave as X-Api-Key. Send it as Bearer and null out X-Api-Key instead.+ * Keep apiKey set so the Anthropic SDK skips its default credential chain.+ * OpenAI-style adapters already sign an apiKey as Bearer.+ */+function copilotRequestAuth(+ provider: Pick<RuntimeProviderConfig, "vendorKey">,+ api: Api,+ auth: ModelAuth,+): ModelAuth {+ if (+ provider.vendorKey?.trim().toLowerCase() !== "github-copilot" ||+ api !== "anthropic-messages" ||+ !auth.apiKey+ ) {+ return auth;+ }+ const { apiKey, headers, ...rest } = auth;+ const requestHeaders: NonNullable<ModelAuth["headers"]> = Object.fromEntries(+ Object.entries(headers ?? {}).filter(([name]) => {+ const lowerName = name.toLowerCase();+ return lowerName !== "authorization" && lowerName !== "x-api-key";+ }),+ );+ return {+ ...rest,+ apiKey,+ headers: { ...requestHeaders, Authorization: `Bearer ${apiKey}`, "X-Api-Key": null },+ };+}+/*** Claude models that publish an effort ladder without a `budget_tokens`* option (Opus 4.7+, Opus 5.x, Fable, ...) reject `thinking.type=enabled`@@ -331,17 +363,21 @@ export function createProviderModels(auth: {apiKey: {name: `${provider.name} API key`,- // Plain apiKey semantics let each adapter emit its own auth header+ // Stored apiKey semantics let each adapter emit its own auth header// (Bearer for OpenAI-style APIs, x-api-key for Anthropic, …).//// A vendor account resolves instead through Electron main, which// returns the whole `ModelAuth` — token, headers, and the// per-credential baseUrl GitHub Copilot hands out. pi-ai calls this// for every request and caches nothing, so a token that rotates- // mid-session is picked up on the next one.+ // mid-session is picked up on the next one. Copilot's Anthropic wire+ // needs explicit Bearer auth because the model uses a row id.resolve: async () =>resolveAuth- ? { auth: await resolveAuth(), source: "OAuth" }+ ? {+ auth: copilotRequestAuth(provider, model.api, await resolveAuth()),+ source: "OAuth",+ }: { auth: { apiKey: requestKey } },},},