diff --git a/components/settings/tabs/ai/ModelSelector.tsx b/components/settings/tabs/ai/ModelSelector.tsx index e615107ef..0ce94c082 100644 --- a/components/settings/tabs/ai/ModelSelector.tsx +++ b/components/settings/tabs/ai/ModelSelector.tsx @@ -154,7 +154,7 @@ export const ModelSelector: React.FC<{ await bridge.aiAllowlistAddHost(baseURL); } const url = buildProviderProbeUrl(baseURL, effectiveModelsEndpoint); - const headers = buildModelDiscoveryHeaders(resolvedStyle, apiKey, customHeaders); + const headers = buildModelDiscoveryHeaders(resolvedStyle, apiKey, customHeaders, baseURL); const result = await bridge.aiFetch(url, "GET", headers, undefined, undefined, undefined, undefined, skipTLSVerify); if (!result.ok) { if (discoveryKeyRef.current !== requestKey) return; diff --git a/infrastructure/ai/agentPlanCompatibility.test.ts b/infrastructure/ai/agentPlanCompatibility.test.ts new file mode 100644 index 000000000..4a4431f02 --- /dev/null +++ b/infrastructure/ai/agentPlanCompatibility.test.ts @@ -0,0 +1,91 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { normalizeAnthropicSdkBaseURL } from './anthropicCompatBaseUrl'; +import { buildModelDiscoveryHeaders } from './modelDiscoveryHeaders'; +import { createModelFromConfig } from './sdk/providers'; + +const origin = 'https://ark.cn-beijing.volces.com'; +const bases = ['/api/plan', '/api/plan/', '/api/plan/v1', '/api/plan/v1/']; + +test('Agent Plan official Anthropic bases normalize and use Bearer discovery auth', () => { + for (const suffix of bases) { + const base = origin + suffix; + assert.equal(normalizeAnthropicSdkBaseURL(base), origin + '/api/plan/v1'); + assert.deepEqual(buildModelDiscoveryHeaders('anthropic', 'fake-key', {}, base), { + Authorization: 'Bearer fake-key', 'anthropic-version': '2023-06-01', + }); + } +}); + +test('Agent Plan special handling does not change other origins, paths or protocols', () => { + for (const base of [ + 'http://ark.cn-beijing.volces.com/api/plan', origin + ':444/api/plan', + 'https://ark.cn-beijing.volces.com.example/api/plan', 'https://proxy.example/api/plan', + origin + '/api/coding', origin + '/api/plan/v3', origin + '/api/planner', + origin + '/api/plan?route=other', origin + '/api/plan#other', + 'https://user@ark.cn-beijing.volces.com/api/plan', + ]) { + assert.equal(normalizeAnthropicSdkBaseURL(base), base); + assert.equal(buildModelDiscoveryHeaders('anthropic', 'fake-key', {}, base)['x-api-key'], 'fake-key'); + } + assert.equal(buildModelDiscoveryHeaders('openai', 'fake-key', {}, origin + '/api/plan').Authorization, 'Bearer fake-key'); + assert.deepEqual(buildModelDiscoveryHeaders('anthropic', 'fake-key', { authorization: 'custom', 'X-Tenant': 'tenant' }, origin + '/api/plan'), { + 'anthropic-version': '2023-06-01', authorization: 'custom', 'X-Tenant': 'tenant', + }); +}); + +test('Agent Plan SDK stream and nonstream use the placeholder and exact messages path', async t => { + const old = Reflect.get(globalThis, 'window'); + t.after(() => Reflect.set(globalThis, 'window', old)); + const requests: {url: string; headers: Headers}[] = []; + const capture = (url: string, headers: Record) => requests.push({ url, headers: new Headers(headers) }); + Reflect.set(globalThis, 'window', { netcatty: { + aiFetch: async (url: string, _method: string, headers: Record) => { + capture(url, headers); return { ok: false, status: 400, data: '{"error":{"message":"captured"}}' }; + }, + aiChatStream: async (_id: string, url: string, headers: Record) => { + capture(url, headers); return { ok: false, error: 'captured' }; + }, + onAiStreamData: () => () => {}, onAiStreamEnd: () => () => {}, onAiStreamError: () => () => {}, + }}); + for (const suffix of bases) { + for (const streaming of [false, true]) { + const model = createModelFromConfig({id:'p',providerId:'custom',name:'Test',enabled:true,style:'anthropic',apiKey:'not-a-real-secret',baseURL:origin+suffix,defaultModel:'test-model',customHeaders:{'X-Tenant':'tenant'}}); + const params = {prompt:[{role:'user' as const,content:[{type:'text' as const,text:'hello'}]}]}; + if (streaming) { + try { const result = await model.doStream(params); await result.stream.pipeTo(new WritableStream()); } catch { /* deliberately rejected at IPC boundary */ } + } else await assert.rejects(Promise.resolve(model.doGenerate(params))); + const request = requests.at(-1)!; + assert.equal(request.url, origin + '/api/plan/v1/messages'); + assert.equal(request.headers.get('authorization'), 'Bearer __IPC_SECURED__'); + assert.equal(request.headers.get('x-api-key'), null); + assert.equal(request.headers.get('x-tenant'), 'tenant'); + assert.ok(!JSON.stringify([...request.headers]).includes('not-a-real-secret')); + } + } + assert.equal(requests.length, 8); +}); + +test('Agent Plan Detect sends Bearer on the same origin without treating missing model listing as valid auth', async () => { + const { probeProviderConnection } = await import('./providerConnectionProbe'); + const requests: {url: string; headers?: Record}[] = []; + for (const suffix of bases) { + const result = await probeProviderConnection({ + baseURL: origin + suffix, apiKey: 'fake-key', providerId: 'custom', style: 'anthropic', + customHeaders: { 'X-Tenant': 'tenant' }, + bridge: { aiFetch: async (url, _method, headers) => { + requests.push({url, headers}); + return {ok:false,status:404,data:'not found'}; + } }, + }); + assert.equal(result.ok, true, 'probe ran, not an assertion that authentication succeeded'); + if (result.ok) { + assert.equal(result.classification.statusCode, 404); + assert.equal(result.classification.health, 'error'); + } + assert.equal(requests.at(-1)?.url, origin + '/api/plan/v1/models'); + assert.equal(requests.at(-1)?.headers?.Authorization, 'Bearer fake-key'); + assert.equal(requests.at(-1)?.headers?.['x-api-key'], undefined); + assert.equal(requests.at(-1)?.headers?.['X-Tenant'], 'tenant'); + } +}); diff --git a/infrastructure/ai/anthropicCompatBaseUrl.ts b/infrastructure/ai/anthropicCompatBaseUrl.ts index 26c780a8d..9ef773cb1 100644 --- a/infrastructure/ai/anthropicCompatBaseUrl.ts +++ b/infrastructure/ai/anthropicCompatBaseUrl.ts @@ -9,6 +9,22 @@ * working proxy bases keep working. */ +/** Official Agent Plan accepts Claude Code's /api/plan base and Bearer auth. + * Keep this exact-origin/path exception separate from arbitrary custom proxies. + */ +export function isAnthropicAgentPlanEndpoint(baseURL: string | undefined): boolean { + if (!baseURL) return false; + try { + const url = new URL(baseURL.trim()); + return url.protocol === "https:" + && url.hostname === "ark.cn-beijing.volces.com" + && !url.port && !url.username && !url.password && !url.search && !url.hash + && /^\/api\/plan(?:\/v1)?\/?$/.test(url.pathname); + } catch { + return false; + } +} + /** Strip trailing slashes; empty input stays empty. */ export function stripTrailingSlashes(url: string): string { return url.trim().replace(/\/+$/, ""); @@ -46,6 +62,7 @@ export function normalizeAnthropicSdkBaseURL(baseURL: string): string { const trimmed = stripTrailingSlashes(baseURL); if (!trimmed) return trimmed; if (anthropicBaseIncludesV1(trimmed)) return trimmed; + if (isAnthropicAgentPlanEndpoint(trimmed)) return `${trimmed}/v1`; if (!isBareOriginBaseURL(trimmed)) return trimmed; return `${trimmed}/v1`; } diff --git a/infrastructure/ai/cattyProviderModels.ts b/infrastructure/ai/cattyProviderModels.ts index 1e2b15ca5..8f67940e1 100644 --- a/infrastructure/ai/cattyProviderModels.ts +++ b/infrastructure/ai/cattyProviderModels.ts @@ -142,7 +142,7 @@ export async function fetchProviderModelCatalog( await bridge.aiAllowlistAddHost(baseURL); } const url = buildProviderProbeUrl(baseURL, endpoint); - const headers = buildModelDiscoveryHeaders(style, apiKey, await decryptProviderHeaders(provider.customHeaders)); + const headers = buildModelDiscoveryHeaders(style, apiKey, await decryptProviderHeaders(provider.customHeaders), baseURL); const result = await bridge.aiFetch( url, 'GET', diff --git a/infrastructure/ai/modelDiscoveryHeaders.ts b/infrastructure/ai/modelDiscoveryHeaders.ts index 096d83ec7..909e2385a 100644 --- a/infrastructure/ai/modelDiscoveryHeaders.ts +++ b/infrastructure/ai/modelDiscoveryHeaders.ts @@ -1,3 +1,4 @@ +import { isAnthropicAgentPlanEndpoint } from "./anthropicCompatBaseUrl"; import type { ProviderStyle } from "./types"; /** @@ -41,12 +42,15 @@ export function resolveModelsDiscoveryEndpoint( function buildDefaultModelDiscoveryHeaders( style: ProviderStyle, apiKey: string | undefined, + baseURL?: string, ): Record { if (!apiKey) return {}; switch (style) { case "anthropic": return { - "x-api-key": apiKey, + ...(isAnthropicAgentPlanEndpoint(baseURL) + ? { Authorization: `Bearer ${apiKey}` } + : { "x-api-key": apiKey }), "anthropic-version": "2023-06-01", }; case "google": @@ -61,8 +65,9 @@ export function buildModelDiscoveryHeaders( style: ProviderStyle, apiKey: string | undefined, customHeaders: Record = {}, + baseURL?: string, ): Record { - const headers = buildDefaultModelDiscoveryHeaders(style, apiKey); + const headers = buildDefaultModelDiscoveryHeaders(style, apiKey, baseURL); const overridden = new Set(Object.keys(customHeaders).map((name) => name.toLowerCase())); return Object.fromEntries([ ...Object.entries(headers).filter(([name]) => !overridden.has(name.toLowerCase())), diff --git a/infrastructure/ai/providerConnectionProbe.ts b/infrastructure/ai/providerConnectionProbe.ts index b4dfdfc5c..cfccad50d 100644 --- a/infrastructure/ai/providerConnectionProbe.ts +++ b/infrastructure/ai/providerConnectionProbe.ts @@ -182,7 +182,7 @@ export async function probeProviderConnection(input: { await bridge.aiAllowlistAddHost(baseURL); } const url = buildProviderProbeUrl(baseURL, endpoint); - const headers = buildModelDiscoveryHeaders(input.style, input.apiKey, input.customHeaders); + const headers = buildModelDiscoveryHeaders(input.style, input.apiKey, input.customHeaders, baseURL); const result = await bridge.aiFetch( url, "GET", diff --git a/infrastructure/ai/sdk/providers.ts b/infrastructure/ai/sdk/providers.ts index ba08615ab..3013ad635 100644 --- a/infrastructure/ai/sdk/providers.ts +++ b/infrastructure/ai/sdk/providers.ts @@ -1,4 +1,5 @@ import { createOpenAI } from '@ai-sdk/openai'; +import { isAnthropicAgentPlanEndpoint } from '../anthropicCompatBaseUrl'; import { createAnthropic } from '@ai-sdk/anthropic'; import { createGoogle } from '@ai-sdk/google'; import { wrapLanguageModel, type LanguageModelMiddleware } from 'ai'; @@ -776,7 +777,7 @@ function createProviderModel( case 'anthropic': return createAnthropic({ - apiKey, + ...(isAnthropicAgentPlanEndpoint(baseURL) ? { authToken: apiKey } : { apiKey }), baseURL, fetch: customFetch, headers: sdkHeaders,