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): catalog addition 以 list-models 为缺席证明,同路由先做网关协议预检

Dashf2ac9dae7def
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 0a60c6bc00..f284a49258 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
@@ -470,6 +470,7 @@ describe('buildPiNativeProvidersFromConfigs', () => {
new Map([
['xai', new Map([['grok-4.5', piBundledModel('grok-4.5', 'openai-completions')]])],
]),
+ new Map([['xai', new Set(['grok-4.5'])]]),
);
const xaiProvider = providers.find((provider) => provider.id === 'xai');
@@ -513,6 +514,22 @@ describe('buildPiNativeProvidersFromConfigs', () => {
expect(xaiProvider?.models.find((model) => model.id === 'grok-4.5')?.catalogAddition).toBeUndefined();
});
+ it('does not mark SuperGrok models as catalog additions when list-models still has the id', () => {
+ const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
+
+ const { providers } = buildPiSubscriptionNativeProviders(
+ catalog,
+ 'http://127.0.0.1:4567/',
+ new Map([
+ ['xai', new Map([['grok-4.5', piBundledModel('grok-4.5', 'openai-completions')]])],
+ ]),
+ new Map([['xai', new Set(['grok-4.5', 'grok-4.6'])]]),
+ );
+
+ const xaiProvider = providers.find((provider) => provider.id === 'xai');
+ expect(xaiProvider?.models.find((model) => model.id === 'grok-4.6')?.catalogAddition).toBeUndefined();
+ });
+
it('namespaces only colliding BYOM runtime ids and preserves their persisted source ids', () => {
const collisions: Array<[string, string]> = [];
const merged = mergePiNativeProviderResults(
diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.ts
index 00979b7405..ae4a1b59df 100644
--- a/apps/desktop/src/main/maker-host/pi-host.ts
+++ b/apps/desktop/src/main/maker-host/pi-host.ts
@@ -96,8 +96,16 @@ export interface PiBundledModelInfo {
}
export type PiBundledModelCatalog = ReadonlyMap<string, ReadonlyMap<string, PiBundledModelInfo>>;
+export type PiListedModelIds = ReadonlyMap<string, ReadonlySet<string>>;
const piBundledModelsByBinary = new Map<string, Promise<PiBundledModelCatalog | null>>();
+const listedIdsByCatalog = new WeakMap<PiBundledModelCatalog, PiListedModelIds>();
+
+export function listedPiModelIds(
+ catalog: PiBundledModelCatalog | undefined,
+): PiListedModelIds | undefined {
+ return catalog ? listedIdsByCatalog.get(catalog) : undefined;
+}
const PI_NATIVE_APIS = new Set<PiNativeApi>([
'anthropic-messages',
'openai-responses',
@@ -391,7 +399,9 @@ export async function readPiBundledModels(
initialProvider,
initialModel,
);
- return catalog.size > 0 ? catalog : null;
+ if (catalog.size === 0) return null;
+ listedIdsByCatalog.set(catalog, listed);
+ return catalog;
} catch (err) {
log.warn(
'readPiBundledModels: PI catalog probe failed; using daily PI annotations without bundled baseline',
@@ -443,6 +453,7 @@ export function buildPiSubscriptionNativeProviders(
catalog: Catalog,
endpoint: string,
bundledModelsByProvider?: PiBundledModelCatalog,
+ listedModelIdsByProvider?: PiListedModelIds,
): PiNativeProvidersResult {
const providers: PiNativeProviderSpec[] = [];
const env: Record<string, string> = {
@@ -495,14 +506,17 @@ export function buildPiSubscriptionNativeProviders(
? { catalogAddition: true }
: {}),
// SuperGrok 没有官方列模型通道,Cindy 目录是成员唯一来源。
- // PI 二进制常常跟不上新 Grok id(grok-4.6):inheritModels
- // 会把没有 piApi 的行从 models.json 滤掉,spawn 靠 custom
- // model id 能跑,set_model 却 fail-closed。只有探针成功且
- // 这份结果里真有 xAI 行,才能把缺 id 当成有效证明;总表
- // 非空但 xAI 被畸形数据整表跳过时,仍走 annotated-only。
- ...(sourceProviderId === 'xai' && bundledModels != null && !bundledModel
- ? { catalogAddition: true }
- : {}),
+ // 缺席证明必须来自未过滤的 --list-models id:解析后的
+ // bundled 表会丢掉未知 api 的行,不能把「解析失败」当成
+ // 「二进制没有这个模型」。
+ ...(() => {
+ if (sourceProviderId !== 'xai') return {};
+ const listedIds =
+ listedModelIdsByProvider?.get(piProviderId) ??
+ listedPiModelIds(bundledModelsByProvider)?.get(piProviderId);
+ if (!listedIds || listedIds.has(wireId)) return {};
+ return { catalogAddition: true };
+ })(),
...(sourceProviderId !== 'openai' &&
model.piApi &&
(isAnnotatedAddition || isProtocolCorrection)
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
index ba3b720dd7..a2db8237d0 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
@@ -689,6 +689,45 @@ describe('Pi provider-aware model routing', () => {
await handle.close();
});
+ it('rejects a same-route gateway heartbeat when the live session wire protocol is stale', async () => {
+ let gatewayApi: 'anthropic-messages' | 'openai-responses' = 'anthropic-messages';
+ const agent = new PiAgent({
+ auth: {
+ getState: async () => ({ authenticated: true, identity: 'test', authSource: 'oauth' as const }),
+ triggerLogin: async () => ({ authenticated: true }),
+ logout: async () => {},
+ getAuthEnv: async () => ({}),
+ },
+ runtimeConfig: { endpoint: 'http://127.0.0.1:9' },
+ binaryPath: path.join(agentHome, 'pi'),
+ logger: noopLogger,
+ capabilityAdditions: {
+ availableModels: [{
+ id: 'shared-model',
+ displayName: 'Shared',
+ contextWindow: 128_000,
+ efforts: [],
+ defaultEffort: null,
+ }],
+ },
+ resolvePiAgentHome: () => agentHome,
+ resolvePiGatewayModelApi: () => gatewayApi,
+ });
+ const handle = await agent.startSession({
+ sessionId: 'gateway-same-route-stale',
+ workingDir: cwd,
+ model: 'shared-model',
+ providerId: 'xd',
+ });
+ gatewayApi = 'openai-responses';
+ captured.requests.length = 0;
+ await expect(handle.setModel!('shared-model', { providerId: 'xd' })).rejects.toThrow(
+ /restart the Pi session to change provider wire protocol/,
+ );
+ expect(captured.requests.filter((request) => request.type === 'set_model')).toEqual([]);
+ await handle.close();
+ });
+
it('applies each native provider alias during provider-less compatibility routing', async () => {
const provider = (id: string, aliases?: Record<string, string>) => ({
id,
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 6300308c44..82c15b6e4a 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -2416,6 +2416,35 @@ export class PiAgent extends BaseAgent {
// 路由上(grok-4.6);重复 set_model 反而 fail-closed。
// 只对显式非 null 来源做 no-op:model-only 与 providerId=null
// (钉回网关)仍走 RPC。
+ const assertGatewayProtocolForModel = (
+ nextModel: string,
+ nextRequestedProviderId: string | null | undefined,
+ ): void => {
+ const nextProvider = resolveProviderForModel(nextModel, nextRequestedProviderId);
+ if (nextProvider !== PI_PROVIDER_ID) return;
+ const routeProviderId = nextRequestedProviderId !== undefined
+ ? nextRequestedProviderId
+ : mutableProviderId;
+ const resolvedApi = this.deps.resolvePiGatewayModelApi?.(routeProviderId, nextModel);
+ if (
+ resolvedApi === null ||
+ (resolvedApi !== undefined &&
+ resolvedApi !== 'anthropic-messages' &&
+ resolvedApi !== 'openai-responses')
+ ) {
+ throw new Error(
+ `Model Access v3 did not provide a Pi wire protocol for model: ${nextModel}`,
+ );
+ }
+ const desiredApi = resolvedApi ?? 'anthropic-messages';
+ const configuredApi = gatewayApiByModel.get(nextModel);
+ if (configuredApi && configuredApi !== desiredApi) {
+ throw new Error(
+ `pi: provider switch for model '${nextModel}' requires API '${desiredApi}', but this session ` +
+ `started with '${configuredApi}'; restart the Pi session to change provider wire protocol.`,
+ );
+ }
+ };
if (
model === mutableModel &&
requestedProviderId !== undefined &&
@@ -2425,6 +2454,7 @@ export class PiAgent extends BaseAgent {
if (setOpts?.effort) {
assertStartupEffortAllowed(activeEffortSnapshot, setOpts.effort);
}
+ assertGatewayProtocolForModel(model, requestedProviderId);
// 同路由不打 set_model,但仍要重试子代理快照:初始写失败或确认写失败
// 留下 pending 时,心跳复用活进程必须能把文件重建/清 pending,
// 否则扩展会一直 fail-closed。不带 pending,路由已确认。
@@ -2456,30 +2486,7 @@ export class PiAgent extends BaseAgent {
}
const provider = resolveProviderForModel(model, requestedProviderId);
const wireModel = resolveWireModel(provider, model);
- if (provider === PI_PROVIDER_ID) {
- const routeProviderId = requestedProviderId !== undefined
- ? requestedProviderId
- : mutableProviderId;
- const resolvedApi = this.deps.resolvePiGatewayModelApi?.(routeProviderId, model);
- if (
- resolvedApi === null ||
- (resolvedApi !== undefined &&
- resolvedApi !== 'anthropic-messages' &&
- resolvedApi !== 'openai-responses')
- ) {
- throw new Error(
- `Model Access v3 did not provide a Pi wire protocol for model: ${model}`,
- );
- }
- const desiredApi = resolvedApi ?? 'anthropic-messages';
- const configuredApi = gatewayApiByModel.get(model);
- if (configuredApi && configuredApi !== desiredApi) {
- throw new Error(
- `pi: provider switch for model '${model}' requires API '${desiredApi}', but this session ` +
- `started with '${configuredApi}'; restart the Pi session to change provider wire protocol.`,
- );
- }
- }
+ assertGatewayProtocolForModel(model, requestedProviderId);
// effort 能力校验必须排在写路由快照**之前**:它会抛错中止本次切换,而快照一旦落盘就
// 指向了新 provider —— 那正是父子路由分叉的形状(upstream #1451 与本 PR 的合并点)。
const nextEffortSnapshot = resolveStartupEffortSnapshot(provider, model);