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(pi): isolate native protocol sources

Chrisa5b965ff3497
diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
index f64738fe7e..b50d3e9e2d 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
@@ -159,14 +159,6 @@ describe('buildPiNativeProvidersFromConfigs', () => {
});
expect(providers[1]?.models[0]?.api).toBeUndefined();
expect(providers[1]?.models[0]?.catalogAddition).toBeUndefined();
- const withoutProbe = buildPiSubscriptionNativeProviders(
- catalog,
- 'http://127.0.0.1:4567/',
- ).providers;
- expect(withoutProbe.find((provider) => provider.id === 'openai-codex')
- ?.models.every((model) => model.catalogAddition === undefined)).toBe(true);
- expect(withoutProbe.find((provider) => provider.id === 'xai')
- ?.models.every((model) => model.api === undefined)).toBe(true);
expect(providers[2]).toMatchObject({
sourceProviderId: 'xai',
baseUrl: 'http://127.0.0.1:4567/v1',
@@ -189,6 +181,67 @@ describe('buildPiNativeProvidersFromConfigs', () => {
}
});
+ it('preserves daily additions and protocol annotations when PI probing fails or is empty', () => {
+ const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
+ const anthropic = catalog.providers.find((provider) => provider.id === 'anthropic')!;
+ const openai = catalog.providers.find((provider) => provider.id === 'openai')!;
+ const xai = catalog.providers.find((provider) => provider.id === 'xai')!;
+ anthropic.models.pi = [{
+ id: 'claude-daily', name: 'Claude Daily', contextWindow: 200_000,
+ efforts: [], defaultEffort: null, piApi: 'anthropic-messages',
+ }];
+ openai.models.pi = [{
+ id: 'chatgpt/gpt-daily', name: 'GPT Daily', contextWindow: 200_000,
+ efforts: [], defaultEffort: null, piApi: 'openai-responses',
+ }];
+ xai.models.pi = [{
+ id: 'xai/grok-daily', name: 'Grok Daily', contextWindow: 200_000,
+ efforts: [], defaultEffort: null, piApi: 'openai-responses',
+ }];
+
+ for (const bundled of [undefined, new Map()] as const) {
+ const providers = buildPiSubscriptionNativeProviders(
+ catalog,
+ 'http://127.0.0.1:4567/',
+ bundled,
+ ).providers;
+ expect(providers.find((provider) => provider.id === 'anthropic')?.models[0])
+ .toMatchObject({ wireId: 'claude-daily', api: 'anthropic-messages' });
+ expect(providers.find((provider) => provider.id === 'openai-codex')?.models[0])
+ .toMatchObject({ wireId: 'gpt-daily', catalogAddition: true });
+ expect(providers.find((provider) => provider.id === 'xai')?.models[0])
+ .toMatchObject({ wireId: 'grok-daily', api: 'openai-responses' });
+ }
+ });
+
+ it('keeps missing daily rows while respecting models returned by a partial PI probe', () => {
+ const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
+ const xai = catalog.providers.find((provider) => provider.id === 'xai')!;
+ xai.models.pi = [
+ {
+ id: 'xai/grok-known', name: 'Grok Known', contextWindow: 200_000,
+ efforts: [], defaultEffort: null, piApi: 'openai-responses',
+ },
+ {
+ id: 'xai/grok-added', name: 'Grok Added', contextWindow: 200_000,
+ efforts: [], defaultEffort: null, piApi: 'openai-responses',
+ },
+ ];
+ const provider = buildPiSubscriptionNativeProviders(
+ catalog,
+ 'http://127.0.0.1:4567/',
+ new Map([['xai', new Map([
+ ['grok-known', piBundledModel('grok-known', 'openai-responses')],
+ ])]]),
+ ).providers.find((candidate) => candidate.id === 'xai');
+
+ expect(provider?.models).toEqual([
+ expect.objectContaining({ wireId: 'grok-known' }),
+ expect.objectContaining({ wireId: 'grok-added', api: 'openai-responses' }),
+ ]);
+ expect(provider?.models[0]?.api).toBeUndefined();
+ });
+
it('preserves PI bundled metadata when a daily annotation corrects an existing protocol', () => {
const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
const xai = catalog.providers.find((provider) => provider.id === 'xai')!;
@@ -275,6 +328,18 @@ describe('buildPiNativeProvidersFromConfigs', () => {
}
});
+ it('fails closed for an unknown custom-provider wire protocol', () => {
+ expect(() => buildPiNativeProvidersFromConfigs(
+ [{
+ id: 'future',
+ name: 'Future',
+ auth: { method: 'none' },
+ runtimes: { pi: piRuntime({ wireProtocol: 'future-protocol' as never }) },
+ }],
+ () => null,
+ )).toThrow('Unsupported PI wire protocol: future-protocol');
+ });
+
it('uses PI bundled protocol knowledge before the legacy unknown-BYOM default', () => {
const bundled = new Map([
['zai', new Map([
@@ -340,6 +405,109 @@ describe('buildPiNativeProvidersFromConfigs', () => {
expect(resolvePiBundledApiByModelId(bundled, 'same-id')).toBeUndefined();
});
+ it('does not copy a unique same-named PI model across BYOM origins', () => {
+ const bundledModel = piBundledModel('shared-model', 'anthropic-messages', {
+ baseUrl: 'https://official.example/v1/messages',
+ name: 'Official Name',
+ compat: { supportsStrictTools: true },
+ });
+ const { providers } = buildPiNativeProvidersFromConfigs(
+ [{
+ id: 'local-provider',
+ name: 'Local Provider',
+ auth: { method: 'none' },
+ runtimes: {
+ pi: piRuntime({
+ baseUrl: 'http://127.0.0.1:9000/v1',
+ models: [{ id: 'shared-model', name: 'Local Name' }],
+ }),
+ },
+ }],
+ () => null,
+ undefined,
+ new Map([['official-provider', new Map([['shared-model', bundledModel]])]]),
+ );
+
+ expect(providers[0]).toMatchObject({
+ baseUrl: 'http://127.0.0.1:9000/v1',
+ api: 'openai-completions',
+ models: [{ id: 'shared-model', name: 'Local Name' }],
+ });
+ expect(providers[0]?.models[0]?.baseUrl).toBeUndefined();
+ expect(providers[0]?.models[0]?.compat).toBeUndefined();
+ });
+
+ it('keeps an explicit BYOM protocol and endpoint isolated from bundled model metadata', () => {
+ const { providers } = buildPiNativeProvidersFromConfigs(
+ [{
+ id: 'explicit-provider',
+ name: 'Explicit Provider',
+ auth: { method: 'none' },
+ runtimes: {
+ pi: piRuntime({
+ baseUrl: 'https://custom.example/v1',
+ wireProtocol: 'openai-responses',
+ models: [{ id: 'same-id', name: 'Custom Name' }],
+ }),
+ },
+ }],
+ () => null,
+ undefined,
+ new Map([['bundled', new Map([
+ ['same-id', piBundledModel('same-id', 'anthropic-messages', {
+ baseUrl: 'https://other.example/v1',
+ name: 'Bundled Name',
+ })],
+ ])]]),
+ );
+
+ expect(providers[0]).toMatchObject({
+ baseUrl: 'https://custom.example/v1',
+ api: 'openai-responses',
+ models: [{ id: 'same-id', name: 'Custom Name' }],
+ });
+ expect(providers[0]?.models[0]?.baseUrl).toBeUndefined();
+ });
+
+ it('falls back to completions when no unique same-origin PI candidate exists', () => {
+ const bundled = new Map([
+ ['provider-a', new Map([
+ ['same-id', piBundledModel('same-id', 'anthropic-messages', {
+ baseUrl: 'https://same.example/anthropic',
+ })],
+ ])],
+ ['provider-b', new Map([
+ ['same-id', piBundledModel('same-id', 'openai-responses', {
+ baseUrl: 'https://same.example/openai',
+ })],
+ ])],
+ ]);
+ const { providers } = buildPiNativeProvidersFromConfigs(
+ [{
+ id: 'ambiguous-provider',
+ name: 'Ambiguous Provider',
+ auth: { method: 'none' },
+ runtimes: {
+ pi: piRuntime({
+ baseUrl: 'https://same.example/proxy',
+ models: [{ id: 'same-id', name: 'Configured Name' }],
+ }),
+ },
+ }],
+ () => null,
+ undefined,
+ bundled,
+ );
+
+ expect(resolvePiBundledModelById(bundled, 'same-id', 'https://same.example/proxy'))
+ .toBeUndefined();
+ expect(providers[0]).toMatchObject({
+ api: 'openai-completions',
+ models: [{ id: 'same-id', name: 'Configured Name' }],
+ });
+ expect(providers[0]?.models[0]?.baseUrl).toBeUndefined();
+ });
+
it('keyless (none) → no env, no apiKeyEnvVar (models.json writes dummy)', () => {
const { providers, env } = buildPiNativeProvidersFromConfigs(
[{ id: 'ollama', name: 'Ollama', auth: { method: 'none' }, runtimes: { pi: piRuntime() } }],
diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.ts
index d9f63483bd..bca1c7c18b 100644
--- a/apps/desktop/src/main/maker-host/pi-host.ts
+++ b/apps/desktop/src/main/maker-host/pi-host.ts
@@ -353,7 +353,7 @@ export async function readPiBundledModels(
);
return catalog.size > 0 ? catalog : null;
} catch (err) {
- log.warn('readPiBundledModels: PI catalog probe failed; daily PI annotations disabled', {
+ log.warn('readPiBundledModels: PI catalog probe failed; using daily PI annotations without bundled baseline', {
message: err instanceof Error ? err.message : String(err),
});
return null;
@@ -404,7 +404,10 @@ export function buildPiSubscriptionNativeProviders(
: model.id;
const bundledModels = bundledModelsByProvider?.get(piProviderId);
const bundledModel = bundledModels?.get(wireId);
- const isAnnotatedAddition = !!model.piApi && !!bundledModels && !bundledModel;
+ // A missing/empty/partial PI probe is not evidence that the daily
+ // catalog annotation is wrong. Keep annotated rows in the overlay so
+ // inheritModels cannot filter out a confirmed addition or correction.
+ const isAnnotatedAddition = !!model.piApi && !bundledModel;
const isProtocolCorrection = sourceProviderId !== 'openai'
&& !!model.piApi
&& !!bundledModel
@@ -646,17 +649,18 @@ function wireProtocolToPiApi(wp: ProviderWireProtocol | undefined): PiNativeApi
return 'openai-responses';
case 'openai-chat':
case undefined:
- default:
// 缺省 openai-completions:BYOM 本地端点(Ollama/vLLM 的 /v1/chat/completions)最常见。
return 'openai-completions';
+ default:
+ throw new Error(`Unsupported PI wire protocol: ${String(wp)}`);
}
}
/**
- * Resolve the protocol already known by the exact bundled PI build. Presets use
- * Cindy provider ids, which intentionally do not have to match PI provider ids,
- * so the stable join key here is the model id. Conflicting duplicate ids are
- * ambiguous and must fall through to an explicit catalog/runtime declaration.
+ * Inspect the protocol already known by the exact bundled PI build. This helper
+ * is intentionally global and therefore only suitable for diagnostics/tests;
+ * BYOM routing must additionally prove that the candidate belongs to the same
+ * upstream origin before inheriting any protocol or metadata.
*/
export function resolvePiBundledApiByModelId(
catalog: PiBundledModelCatalog | undefined,
@@ -698,16 +702,11 @@ export function resolvePiBundledModelById(
}
if (candidates.length === 0) return undefined;
const sourceOrigin = urlOrigin(sourceBaseUrl);
- if (sourceOrigin) {
- const sameOrigin = candidates.filter((model) => urlOrigin(model.baseUrl) === sourceOrigin);
- if (sameOrigin.length === 1) return sameOrigin[0];
- const exactBaseUrl = sameOrigin.filter((model) => model.baseUrl === sourceBaseUrl);
- if (exactBaseUrl.length === 1) return exactBaseUrl[0];
- }
- const first = candidates[0]!;
- return candidates.every((model) => model.api === first.api && model.baseUrl === first.baseUrl)
- ? first
- : undefined;
+ if (!sourceOrigin) return undefined;
+ const sameOrigin = candidates.filter((model) => urlOrigin(model.baseUrl) === sourceOrigin);
+ const exactBaseUrl = sameOrigin.filter((model) => model.baseUrl === sourceBaseUrl);
+ if (exactBaseUrl.length === 1) return exactBaseUrl[0];
+ return sameOrigin.length === 1 ? sameOrigin[0] : undefined;
}
/** env 变量名(该 provider 的 api key):CINDY_PI_KEY_<ID>,ID 规整成 [A-Z0-9_]。 */
@@ -800,14 +799,13 @@ export function buildPiNativeProvidersFromConfigs(
env[apiKeyEnvVar] = key;
}
}
- const runtimeApi = rt.wireProtocol
- ? wireProtocolToPiApi(rt.wireProtocol)
- : undefined;
+ const runtimeApi = rt.wireProtocol === undefined
+ ? undefined
+ : wireProtocolToPiApi(rt.wireProtocol);
// Protocol authority, in order: per-model daily correction/addition,
- // explicit endpoint protocol, exact PI bundled model knowledge, then the
- // legacy BYOM default for genuinely unknown hand-written models. This keeps
- // unannotated existing preset models on PI's own table instead of silently
- // absorbing them into OpenAI Chat Completions.
+ // explicit endpoint protocol, strictly same-origin PI bundled knowledge,
+ // then the legacy BYOM default. A same-named model from another provider is
+ // not evidence about this user endpoint and must never rewrite its route.
const bundledModels = rt.models.map((model) =>
!model.piApi && !runtimeApi
? resolvePiBundledModelById(bundledModelsByProvider, model.id, rt.baseUrl)
@@ -816,7 +814,6 @@ export function buildPiNativeProvidersFromConfigs(
model.piApi
?? runtimeApi
?? bundledModels[index]?.api
- ?? resolvePiBundledApiByModelId(bundledModelsByProvider, model.id)
?? 'openai-completions');
const providerApi = runtimeApi ?? modelApis[0] ?? 'openai-completions';
providers.push({
diff --git a/packages/anthropic-compat-proxy/src/server.test.ts b/packages/anthropic-compat-proxy/src/server.test.ts
index 29ba1ebd12..ce3d7024dc 100644
--- a/packages/anthropic-compat-proxy/src/server.test.ts
+++ b/packages/anthropic-compat-proxy/src/server.test.ts
@@ -1919,11 +1919,17 @@ describe('anthropic-compat-proxy localHandler(路由决策交本地 handler,不
if (reachTimeout) clearTimeout(reachTimeout);
}
- expect(seen).not.toBeNull();
- expect(seen?.url).toBe('/codex/responses');
- expect(seen?.encoding).toBe('zstd');
- expect(seen?.parsed).toBeUndefined();
- expect([...seen!.raw.subarray(0, 4)]).toEqual([0x28, 0xb5, 0x2f, 0xfd]);
+ const observed = seen as {
+ raw: Buffer;
+ encoding: string | undefined;
+ parsed: unknown;
+ url: string;
+ } | null;
+ expect(observed).not.toBeNull();
+ expect(observed?.url).toBe('/codex/responses');
+ expect(observed?.encoding).toBe('zstd');
+ expect(observed?.parsed).toBeUndefined();
+ expect([...observed!.raw.subarray(0, 4)]).toEqual([0x28, 0xb5, 0x2f, 0xfd]);
expect(gateway.bodies).toHaveLength(0);
} finally {
if (child && child.exitCode === null && child.signalCode === null) {