Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(copilot): use account host for model discovery

Yash K8264a969bad6
diff --git a/apps/desktop/src/main/maker-host/__tests__/genericOAuth.test.ts b/apps/desktop/src/main/maker-host/__tests__/genericOAuth.test.ts
index b7e486a21b..8afc56e25c 100644
--- a/apps/desktop/src/main/maker-host/__tests__/genericOAuth.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/genericOAuth.test.ts
@@ -122,6 +122,52 @@ function seedBlob(providerId: string, blob: Record<string, unknown>): void {
resetGenericOAuthMemoryCache(); // 让下次读走注入 storage
}
+describe('Copilot account-specific model discovery (#6663)', () => {
+ it.each(['individual', 'business', 'enterprise'] as const)('uses the %s account host for automatic model discovery', async account => {
+ const oauth = providerPresetOAuth('github-copilot')!;
+ const token = `test-token;proxy-ep=proxy.${account}.githubcopilot.com;exp=9999999999`;
+ seedBlob('copilot-account', { access_token: token });
+ fetchResponder = () => new Response('{"data":[{"id":"test-model"}]}');
+ const original = 'https://api.individual.githubcopilot.com';
+ const expected = `https://api.${account}.githubcopilot.com/models`;
+ const automatic = await discoverGenericOAuthModels('copilot-account', oauth, `${original}/models`, 'pi');
+ expect(automatic).toMatchObject([{ id: 'test-model' }]);
+ expect(fetchCalls.map(call => call.url)).toEqual([expected]);
+ });
+
+ it.each(['individual', 'business', 'enterprise'] as const)('uses the %s account host when refreshing saved model lists', async account => {
+ const oauth = providerPresetOAuth('github-copilot')!;
+ const token = `test-token;proxy-ep=proxy.${account}.githubcopilot.com;exp=9999999999`;
+ seedBlob('copilot-account', { access_token: token });
+ const original = 'https://api.individual.githubcopilot.com';
+ const expected = `https://api.${account}.githubcopilot.com/models`;
+ const requests: string[] = [];
+ const provider: ProviderView = {
+ id: 'copilot-account', name: 'Copilot', source: 'user', connected: true,
+ auth: { method: 'oauth', oauth }, agents: ['pi'], models: {},
+ routing: { pi: { upstream: original, modelsUrl: `${original}/models`, authStrategy: 'oauth-token', wireProtocol: 'openai-chat' } },
+ };
+ const saved = await fetchSavedOAuthProviderModels(provider, 'pi', 'copilot-account', () => true,
+ async (url, init) => {
+ requests.push(String(url));
+ expect(init?.headers).toEqual({ authorization: `Bearer ${token}` });
+ return new Response('{"data":[{"id":"test-model"}]}');
+ });
+ expect(saved).toMatchObject({ ok: true, models: [{ id: 'test-model' }] });
+ expect(requests).toEqual([expected]);
+ });
+
+ it.each([
+ ['proxy-ep=proxy.business.githubcopilot.com.evil.test;', 'https://api.individual.githubcopilot.com/models'],
+ ['proxy-ep=proxy.business.githubcopilot.com;', 'https://custom.example/models'],
+ ])('preserves custom URLs and rejects untrusted token destinations', async (token, url) => {
+ seedBlob('copilot-account', { access_token: token });
+ fetchResponder = () => new Response('{"data":[{"id":"test-model"}]}');
+ await discoverGenericOAuthModels('copilot-account', providerPresetOAuth('github-copilot')!, url, 'pi');
+ expect(fetchCalls.map(call => call.url)).toEqual([url]);
+ });
+});
+
describe('manual model refresh for saved OAuth providers', () => {
function savedProvider(presetId = 'openrouter'): ProviderView {
const baseUrl = presetId === 'nous'
diff --git a/apps/desktop/src/main/maker-host/copilot-account-url.ts b/apps/desktop/src/main/maker-host/copilot-account-url.ts
new file mode 100644
index 0000000000..b97ecc1f1b
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/copilot-account-url.ts
@@ -0,0 +1,16 @@
+/** Copilot inference tokens assign one of three official account API hosts. */
+export function resolveCopilotAccountUrl(value: string, token: string): string {
+ try {
+ const url = new URL(value);
+ if (url.protocol === 'https:' && url.hostname === 'api.individual.githubcopilot.com') {
+ const host = token.match(/(?:^|;)proxy-ep=(proxy\.(?:individual|business|enterprise)\.githubcopilot\.com)(?:;|$)/)?.[1];
+ if (host) {
+ url.hostname = host.replace(/^proxy\./, 'api.');
+ return url.toString().replace(/\/$/, '');
+ }
+ }
+ } catch {
+ // Keep invalid endpoints for the caller's existing URL validation/error path.
+ }
+ return value;
+}
diff --git a/apps/desktop/src/main/maker-host/generic-oauth.ts b/apps/desktop/src/main/maker-host/generic-oauth.ts
index 387dd6fef6..30b0c8205f 100644
--- a/apps/desktop/src/main/maker-host/generic-oauth.ts
+++ b/apps/desktop/src/main/maker-host/generic-oauth.ts
@@ -1,3 +1,4 @@
+import { resolveCopilotAccountUrl } from './copilot-account-url.js';
import { collectModelDiscoveryPages } from './model-discovery-pages.js';
import { providerOAuthContract } from '@cindy/model-providers';
import { isOpenRouterModelsUrl, type DiscoveredModel } from '@cindy/model-providers';
@@ -851,10 +852,11 @@ export async function discoverGenericOAuthModels(
agent?: AgentKind,
isCurrent: () => boolean = () => true,
): Promise<DiscoveredModel[] | null> {
- const url = discoveryUrl ?? oauth.modelsDiscoveryUrl;
- if (!url || !isCurrent()) return null;
+ const configuredUrl = discoveryUrl ?? oauth.modelsDiscoveryUrl;
+ if (!configuredUrl || !isCurrent()) return null;
const token = readCachedGenericOAuthAccessToken(providerId, oauth);
if (!token) return null;
+ const url = resolveCopilotAccountUrl(configuredUrl, token);
const headers: Record<string, string> = { authorization: `Bearer ${token}` };
if (agent === 'claude-code' && !isOpenRouterModelsUrl(url)) headers['anthropic-version'] = '2023-06-01';
let res: Response;
diff --git a/apps/desktop/src/main/maker-host/provider-model-fetch.ts b/apps/desktop/src/main/maker-host/provider-model-fetch.ts
index 7d3cbfe8d0..08508f0e87 100644
--- a/apps/desktop/src/main/maker-host/provider-model-fetch.ts
+++ b/apps/desktop/src/main/maker-host/provider-model-fetch.ts
@@ -1,3 +1,4 @@
+import { resolveCopilotAccountUrl } from './copilot-account-url.js';
import { collectModelDiscoveryPages } from './model-discovery-pages.js';
import type { DiscoveredModel } from '@cindy/model-providers';
/**
@@ -99,10 +100,11 @@ export async function fetchSavedOAuthProviderModels(
if (!isCurrent()) return { ok: false, code: 'AUTH_INVALID' };
const token = readCachedGenericOAuthAccessToken(storageProviderId, oauth);
if (!token) return { ok: false, code: 'AUTH_INVALID' };
+ const modelsUrl = route.modelsUrl ?? oauth.modelsDiscoveryUrl;
const result = await fetchProviderModels({
agent,
- baseUrl: route.upstream,
- modelsUrl: route.modelsUrl ?? oauth.modelsDiscoveryUrl,
+ baseUrl: resolveCopilotAccountUrl(route.upstream, token),
+ modelsUrl: modelsUrl ? resolveCopilotAccountUrl(modelsUrl, token) : modelsUrl,
wireProtocol: route.wireProtocol,
authMethod: 'oauth',
apiKey: token,
diff --git a/apps/desktop/src/main/maker-host/provider-route.ts b/apps/desktop/src/main/maker-host/provider-route.ts
index 053a70e2fc..df997359e6 100644
--- a/apps/desktop/src/main/maker-host/provider-route.ts
+++ b/apps/desktop/src/main/maker-host/provider-route.ts
@@ -1,3 +1,4 @@
+import { resolveCopilotAccountUrl } from './copilot-account-url.js';
/**
* provider-route —— 把 catalog 的 `RoutingDescriptor` 翻译成 loopback proxy 的 `RoutingDecision`,
* 并据 per-session 选定的供应商解析本会话的路由。
@@ -393,14 +394,8 @@ function buildRouteDecisionBase(
};
const decision: RoutingDecision = { headerOverride };
if (routing.upstream) decision.upstreamOverride = routing.upstream;
- // Copilot assigns personal/business/enterprise API hosts in its inference token.
- // Follow that assignment only for the official preset and official Copilot hosts.
if (routing.upstream && oauthToken) {
- const upstream = new URL(routing.upstream);
- if (upstream.protocol === 'https:' && upstream.hostname === 'api.individual.githubcopilot.com') {
- const host = oauthToken.match(/(?:^|;)proxy-ep=(proxy\.(?:individual|business|enterprise)\.githubcopilot\.com)(?:;|$)/)?.[1];
- if (host) { upstream.hostname = host.replace(/^proxy\./, 'api.'); decision.upstreamOverride = upstream.toString().replace(/\/$/, ''); }
- }
+ decision.upstreamOverride = resolveCopilotAccountUrl(routing.upstream, oauthToken);
}
// cc 子进程可能带 x-api-key(gateway-spawn 的网关 key)——发往 OAuth 上游必须抹掉,
// 防泄漏 + 防按 x-api-key 优先鉴权的端点拿错钥匙。合并描述符自带的 headerDelete。