Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): 修正 Anthropic OAuth 请求构造并保留原生 beta 头 (#4031)
AquaHydro3a08da1778e1
diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.tsindex 4b76259e4a..b0d3b7921b 100644--- a/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts@@ -16,6 +16,8 @@* bridge handler 注册,scope 门单测见 providerRoute.test.ts。)*/+import { createServer, type IncomingHttpHeaders } from 'node:http';+import { createAnthropicCompatProxy, type ProxyHandle } from '@cindy/anthropic-compat-proxy';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';vi.mock('../../appCapabilities.js', () => ({@@ -501,6 +503,77 @@ describe('pi routingTransform — xdt session header selects the Pi provider rouexpect(authenticatePiProxySession('sess-pi', 'stable-secret')).toBe(false);});+ it('preserves Pi OAuth betas and fallbacks on the final upstream request while replacing placeholder auth', async () => {+ const placeholder = 'sk-ant-oat01';+ const beta = 'claude-code-20250219,oauth-2025-04-20,server-side-fallback-2026-07-01';+ const body = {+ model: 'claude-opus-5',+ messages: [{ role: 'user', content: 'ping' }],+ max_tokens: 16,+ fallbacks: [{ model: 'claude-opus-4-8' }],+ };+ const received: Array<{ headers: IncomingHttpHeaders; body: string }> = [];+ const upstream = createServer(async (req, res) => {+ let raw = '';+ for await (const chunk of req) raw += chunk;+ received.push({ headers: req.headers, body: raw });+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end('{}');+ });+ let proxy: ProxyHandle | undefined;+ try {+ await new Promise<void>((resolve) => upstream.listen(0, '127.0.0.1', resolve));+ const address = upstream.address();+ if (!address || typeof address === 'string') throw new Error('Missing test upstream address');+ const upstreamUrl = `http://127.0.0.1:${address.port}`;+ setSessionProvider('sess-pi', 'anthropic');+ setProviderOAuthTokenReader((providerId, agent) =>+ providerId === 'anthropic' && agent === 'pi' ? 'fixture-claude-token' : null,+ );+ registerPiProxySession('sess-pi', 'session-secret', () => 'anthropic');+ const route = createModelRoutingTransform();+ proxy = await createAnthropicCompatProxy({+ upstream: upstreamUrl,+ routingTransform: async (requestBody, ctx) => {+ const decision = await route(requestBody, ctx);+ expect(decision?.upstreamOverride).toBe('https://api.anthropic.com');+ // Keep the real routing/header decision; only replace its network destination.+ return { ...decision, upstreamOverride: upstreamUrl };+ },+ });+ const response = await fetch(`${proxy.url}/v1/messages`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ authorization: `Bearer ${placeholder}`,+ 'x-api-key': placeholder,+ 'anthropic-beta': beta,+ 'x-cindy-pi-session-id': 'sess-pi',+ 'x-cindy-pi-session-token': 'session-secret',+ 'x-cindy-pi-provider-id': 'anthropic',+ },+ body: JSON.stringify(body),+ signal: AbortSignal.timeout(5_000),+ });+ expect(response.status).toBe(200);+ await response.text();+ expect(received).toHaveLength(1);+ expect(received[0].headers).toMatchObject({+ authorization: 'Bearer fixture-claude-token',+ 'anthropic-version': '2023-06-01',+ 'anthropic-beta': beta,+ });+ for (const name of ['x-api-key', 'x-cindy-pi-session-id', 'x-cindy-pi-session-token', 'x-cindy-pi-provider-id']) {+ expect(received[0].headers[name]).toBeUndefined();+ }+ expect(JSON.stringify(received[0])).not.toContain(placeholder);+ expect(JSON.parse(received[0].body)).toEqual(body);+ } finally {+ await proxy?.dispose();+ await new Promise<void>((resolve, reject) => upstream.close((error) => error ? reject(error) : resolve()));+ }+ });+it('routes an Anthropic Pi request with host-managed OAuth and strips Pi placeholder auth', async () => {setClaudeProxyGatewayKeyReader(() => 'sk-gw');setSessionProvider('sess-pi', 'anthropic');@@ -521,7 +594,6 @@ describe('pi routingTransform — xdt session header selects the Pi provider rouupstreamOverride: 'https://api.anthropic.com',headerOverride: {'anthropic-version': '2023-06-01',- 'anthropic-beta': 'oauth-2025-04-20',authorization: 'Bearer pi-claude-token',},headerDelete: [@@ -533,6 +605,45 @@ describe('pi routingTransform — xdt session header selects the Pi provider rou});});+ it.each([+ ['sk-gw'],+ [null],+ ])(+ 'pins an Anthropic Pi request to the subscription route when the session holds no explicit source (gateway key %s)',+ async (gatewayKey) => {+ // model-only set_model 与老会话 hydrate 都会让 session store 为空,而 Pi 已经跑在+ // anthropic 原生 provider 上。掉回 ② 段默认路由 = 有网关 key 时静默改走网关计费,+ // 无网关 key 时把 `sk-ant-oat` 占位 token 直发 api.anthropic.com。+ setClaudeProxyGatewayKeyReader(() => gatewayKey);+ setProviderOAuthTokenReader((providerId, agent) =>+ providerId === 'anthropic' && agent === 'pi' ? Promise.resolve('pi-claude-token') : null,+ );+ registerPiProxySession('sess-pi', 'session-secret', () => 'anthropic');+ const decision = createModelRoutingTransform()(+ { model: 'claude-opus-5' },+ ctxWith({+ 'x-cindy-pi-session-id': 'sess-pi',+ 'x-cindy-pi-session-token': 'session-secret',+ 'x-cindy-pi-provider-id': 'anthropic',+ authorization: 'Bearer sk-ant-oat01',+ }),+ );+ await expect(Promise.resolve(decision)).resolves.toEqual({+ upstreamOverride: 'https://api.anthropic.com',+ headerOverride: {+ 'anthropic-version': '2023-06-01',+ authorization: 'Bearer pi-claude-token',+ },+ headerDelete: [+ 'x-api-key',+ 'x-cindy-pi-session-id',+ 'x-cindy-pi-session-token',+ 'x-cindy-pi-provider-id',+ ],+ });+ },+ );+it.each([['/v1/messages', { 'x-api-key': 'sk-gw', authorization: 'Bearer sk-gw' }],['/v1/responses', { authorization: 'Bearer sk-gw' }],@@ -643,7 +754,6 @@ describe('pi routingTransform — xdt session header selects the Pi provider rouupstreamOverride: 'https://api.anthropic.com',headerOverride: {'anthropic-version': '2023-06-01',- 'anthropic-beta': 'oauth-2025-04-20',authorization: 'Bearer pi-claude-token',},headerDelete: [diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.tsindex f409c06ff9..bf19932b4c 100644--- a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts@@ -853,8 +853,12 @@ describe('buildPiNativeProvidersFromConfigs', () => {sourceProviderId: 'anthropic',baseUrl: 'http://127.0.0.1:4567/',inheritModels: true,+ apiKeyEnvVar: 'CINDY_PI_ANTHROPIC_PROXY_KEY',models: [{ id: 'claude-opus-5', wireId: 'claude-opus-5' }],});+ // Pi 按 `sk-ant-oat` 前缀识别 OAuth 形态,才会自己拼 claude-code/oauth/server-side-fallback+ // 等 beta 头与 Claude Code 身份;占位值不能是真 token 形态之外的普通字串。+ expect(env.CINDY_PI_ANTHROPIC_PROXY_KEY).toContain('sk-ant-oat');expect(providers[1]).toMatchObject({sourceProviderId: 'openai',baseUrl: 'http://127.0.0.1:4567/',diff --git a/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.tsindex f6ee0762d6..16d06c324f 100644--- a/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts@@ -317,7 +317,6 @@ describe('pi: provider-aware Anthropic wire routing', () => {upstreamOverride: ANTHROPIC_DIRECT_UPSTREAM,headerOverride: {'anthropic-version': '2023-06-01',- 'anthropic-beta': 'oauth-2025-04-20',authorization: 'Bearer claude-live-token',},headerDelete: ['x-api-key'],diff --git a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.tsindex 722550daa3..bd478d109a 100644--- a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts+++ b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts@@ -668,11 +668,21 @@ export function createModelRoutingTransform(): RoutingTransform {);}- if (subagentRoute && piProviderId) {+ if (piProviderId && piProviderId !== 'xd' && (subagentRoute || !selectedPiProviderId)) {// A provider-pinned child token is both the authorization boundary and// the route source. Re-reading the parent session provider here would// authenticate Anthropic but still route through an OpenAI/XD parent,// eventually falling into the proxy's default upstream.+ //+ // Root tokens take the same pin whenever the session store holds no+ // explicit source: a model-only `set_model` (runtimeSetModel only writes+ // the store when `providerId !== undefined`) and a legacy session whose+ // `sessions.provider_id` is empty both leave it null while PI already+ // runs on the resolved subscription provider. ② 段默认路由会把这种请求+ // 拿网关 key 打到网关(用户以为在用 Claude 订阅,实际计费在网关),无网关+ // key 时更会把 `sk-ant-oat` 占位 token 直发 api.anthropic.com。这里的+ // piProviderId 已过 registered 匹配门,就是授权边界也是路由来源;openai /+ // xai 在上方已按同一判据早返回,'xd' 留给网关分支(记账 + sanitize)。return resolveProviderRouteDecision(piProviderId, 'pi', gatewayKey).then((resolved) => resolved?.decision ?? unavailablePiProviderRoute(piProviderId)).catch(() => unavailablePiProviderRoute(piProviderId));diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.tsindex 063ea2f131..41c2926805 100644--- a/apps/desktop/src/main/maker-host/pi-host.ts+++ b/apps/desktop/src/main/maker-host/pi-host.ts@@ -121,6 +121,22 @@ const PI_SESSION_ID_ENV = 'CINDY_PI_SESSION_ID';const PI_SESSION_TOKEN_ENV = 'CINDY_PI_SESSION_TOKEN';const PI_PROVIDER_AUTH_PLACEHOLDER_KEY = 'cindy-pi-provider-auth-placeholder';const PI_OPENAI_PROXY_KEY_ENV = 'CINDY_PI_OPENAI_PROXY_KEY';+const PI_ANTHROPIC_PROXY_KEY_ENV = 'CINDY_PI_ANTHROPIC_PROXY_KEY';+/**+ * Claude 订阅占位 token。Pi 的 anthropic 适配器按 `apiKey.includes('sk-ant-oat')` 判定+ * OAuth 形态,命中后才走原生订阅请求构造:Bearer 鉴权、`claude-code-20250219,oauth-2025-04-20`+ * 加各 beta(fine-grained tool streaming / server-side fallback 等)、Claude Code 身份 system+ * 段与 `claude-cli` UA。占位值本身不含授权能力;真 token 由 loopback proxy 在解析出+ * anthropic provider 路由时覆盖 `authorization`,故该路由是占位值被换掉的唯一保证 ——+ * 请求带 provider 头就必须钉在该路由上,不能落回默认上游(见+ * anthropic-compat-proxy-host 的 piProviderId 钉住分支)。+ * 用普通字串会让 Pi 按 x-api-key 形态发请求,proxy 再补 beta 头就会+ * 与 body 里 Pi 已注入的 `fallbacks` 等字段脱节(400 `fallbacks: Extra inputs are not permitted`)。+ *+ * 取值即探针要求的最短形态(二进制里只有 `sk-ant-oat` 这一个字面量,版本段不参与判定),+ * 与仓内既有 OAuth 形态夹具同值 —— 不额外造一个更长、更像真 token 的字串去撞密钥扫描。+ */+const PI_ANTHROPIC_PROXY_PLACEHOLDER_TOKEN = 'sk-ant-oat01';const PI_PROVIDER_HEADER = 'x-cindy-pi-provider-id';export interface PiBundledModelInfo {@@ -544,6 +560,7 @@ export function buildPiSubscriptionNativeProviders(const env: Record<string, string> = {[PI_OPENAI_PROXY_KEY_ENV]: piOpenaiProxyPlaceholderJwt(),[PI_XAI_PROXY_API_KEY_ENV]: PI_PROVIDER_AUTH_PLACEHOLDER_KEY,+ [PI_ANTHROPIC_PROXY_KEY_ENV]: PI_ANTHROPIC_PROXY_PLACEHOLDER_TOKEN,};const add = (sourceProviderId: 'anthropic' | 'openai' | 'xai',@@ -606,6 +623,7 @@ export function buildPiSubscriptionNativeProviders(name,baseUrl,inheritModels: true,+ ...(sourceProviderId === 'anthropic' ? { apiKeyEnvVar: PI_ANTHROPIC_PROXY_KEY_ENV } : {}),...(sourceProviderId === 'openai' ? { apiKeyEnvVar: PI_OPENAI_PROXY_KEY_ENV } : {}),...(sourceProviderId === 'xai' ? { apiKeyEnvVar: PI_XAI_PROXY_API_KEY_ENV } : {}),modelIdAliases,diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.tsindex eac238fe58..961c10e969 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts@@ -10,7 +10,7 @@*/import { spawn } from 'node:child_process';-import { createServer, type Server } from 'node:http';+import { createServer, type IncomingHttpHeaders, type Server } from 'node:http';import {chmodSync,existsSync,@@ -337,6 +337,7 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewalet agentHome = '';const seenRequests: Array<{url: string;+ headers: IncomingHttpHeaders;auth: string | undefined;sessionId: string | undefined;providerId: string | undefined;@@ -353,6 +354,7 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewareq.on('end', () => {seenRequests.push({url: req.url ?? '',+ headers: req.headers,auth: (req.headers['x-api-key'] as string | undefined) ?? (req.headers.authorization as string | undefined),sessionId: req.headers['x-cindy-pi-session-id'] as string | undefined,providerId: req.headers['x-cindy-pi-provider-id'] as string | undefined,@@ -733,7 +735,7 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa);it(- 'uses PI native Anthropic Messages for a host Claude subscription model',+ 'uses PI native OAuth identity and fallback betas for a host Claude subscription model',{ timeout: 60_000 },async () => {const deps = buildDeps();@@ -757,6 +759,7 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewaname: 'Anthropic',baseUrl: endpoint,inheritModels: true,+ apiKeyEnvVar: 'CINDY_PI_ANTHROPIC_PROXY_KEY',headers: {'x-cindy-pi-session-id': '$CINDY_PI_SESSION_ID','x-cindy-pi-session-token': '$CINDY_PI_SESSION_TOKEN',@@ -764,7 +767,7 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa},models: [{ id: 'claude-opus-5', wireId: 'claude-opus-5' }],}],- env: {},+ env: { CINDY_PI_ANTHROPIC_PROXY_KEY: 'sk-ant-oat01' },});const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-agent-native-anthropic-cwd-'));let handle: AgentSessionHandle | null = null;@@ -793,6 +796,19 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewaproviderId: 'anthropic',}),]));+ const request = seenRequests.slice(requestsBefore).find((item) => item.providerId === 'anthropic')!;+ expect(request.headers.authorization).toBe('Bearer sk-ant-oat01');+ expect(request.headers['x-api-key']).toBeUndefined();+ expect(request.headers['user-agent']).toMatch(/^claude-cli\//);+ expect(String(request.headers['anthropic-beta']).split(',')).toEqual(expect.arrayContaining([+ 'claude-code-20250219', 'oauth-2025-04-20', 'server-side-fallback-2026-07-01',+ ]));+ expect(JSON.parse(request.body)).toMatchObject({+ system: expect.arrayContaining([+ expect.objectContaining({ type: 'text', text: "You are Claude Code, Anthropic's official CLI for Claude." }),+ ]),+ fallbacks: expect.arrayContaining([expect.objectContaining({ model: expect.any(String) })]),+ });} finally {await handle?.close();rmSync(workingDir, { recursive: true, force: true });diff --git a/packages/model-providers/src/__tests__/user-provider.test.ts b/packages/model-providers/src/__tests__/user-provider.test.tsindex 133fe4493d..ac68271f7d 100644--- a/packages/model-providers/src/__tests__/user-provider.test.ts+++ b/packages/model-providers/src/__tests__/user-provider.test.ts@@ -1236,10 +1236,15 @@ describe('custom model defaults with partial registry metadata', () => {models: [{id: 'sparse-model', name: 'Sparse model',efforts: ['low', 'medium', 'high'],- ...(declared !== undefined ? { defaultEffort: declared } : {}),routes: [{ providerId: 'relay', modelId: 'sparse-model', agents: ['codex'] }],}],};+ if (declared === null) {+ // @ts-expect-error Exercise malformed registry metadata outside the wire contract.+ modelRegistry.models[0].defaultEffort = declared;+ } else if (declared !== undefined) {+ modelRegistry.models[0].defaultEffort = declared;+ }const provider = buildUserProvider({id: 'relay', name: 'Custom relay',runtimes: { codex: { baseUrl: 'https://relay.example/v1', models: [{ id: 'sparse-model', name: 'My model' }] } },diff --git a/packages/model-providers/src/builtin.ts b/packages/model-providers/src/builtin.tsindex f6c459ef8b..ec0f866c2e 100644--- a/packages/model-providers/src/builtin.ts+++ b/packages/model-providers/src/builtin.ts@@ -137,10 +137,11 @@ const ANTHROPIC_PROVIDER: Provider = {upstream: 'https://api.anthropic.com',wireProtocol: 'anthropic-messages',authStrategy: 'provider-oauth-header',- headerOverride: {- 'anthropic-version': '2023-06-01',- 'anthropic-beta': 'oauth-2025-04-20',- },+ // Pi 拿的是 `sk-ant-oat` 形态占位 token(pi-host),自己就按原生订阅方式发请求:+ // `anthropic-beta` 由 Pi 按模型拼好(oauth / claude-code / server-side-fallback 等),+ // 这里只换 authorization,不得覆盖 beta 头——覆盖会让 body 里 Pi 注入的 `fallbacks`+ // 失去 beta 声明,官方端点 400 `fallbacks: Extra inputs are not permitted`。+ headerOverride: { 'anthropic-version': '2023-06-01' },headerDelete: ['x-api-key'],},},