Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): guard gateway image input capability (#1900)
Chris Zhang7293ceee92ed
diff --git a/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts b/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.tsindex 24b1a9f842..096753bee8 100644--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts@@ -208,6 +208,32 @@ describe('XD 网关权威模型清单重建', () => {expect('icon' in (cc.find((m) => m.id === 'plain-model') ?? {})).toBe(false);});+ it('把网关图片输入 modalities 投影到 Pi 的 provider-model 能力', () => {+ setActiveCatalog(BUNDLED_CATALOG);+ setXdGatewayModels([+ {+ id: 'gateway-vision',+ modalities: { input: ['text', 'image'], output: ['text'] },+ },+ {+ id: 'gateway-text',+ modalities: { input: ['text'], output: ['text'] },+ },+ { id: 'gateway-unknown' },+ ]);++ const pi = deriveAvailableModels(getActiveCatalog(), 'pi');+ expect(pi.find((model) => model.id === 'gateway-vision')).toMatchObject({+ supportsImageInput: true,+ });+ expect(pi.find((model) => model.id === 'gateway-text')).toMatchObject({+ supportsImageInput: false,+ });+ expect(pi.find((model) => model.id === 'gateway-unknown')).not.toHaveProperty(+ 'supportsImageInput',+ );+ });+it('把标准 token 价投影为每百万 token 的折后展示价', () => {setActiveCatalog(BUNDLED_CATALOG);setXdGatewayModels([diff --git a/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts b/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.tsindex 537981ed16..d49b686dd5 100644--- a/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts@@ -177,6 +177,27 @@ describe('deriveAvailableModels — dynamic-first catalog contract', () => {});});+ it('projects explicit provider-model image modalities and leaves unknown capability unset', () => {+ const catalog = structuredClone(BUNDLED_CATALOG);+ const xd = catalog.providers.find((provider) => provider.id === 'xd');+ expect(xd).toBeDefined();+ xd!.models.pi = [+ model('gateway-vision', { modalities: { input: ['text', 'image'], output: ['text'] } }),+ model('gateway-text', { modalities: { input: ['text'], output: ['text'] } }),+ model('gateway-unknown'),+ ];++ expect(resolvePiRuntimeModelDescriptor(catalog, 'cindy', 'gateway-vision')).toMatchObject({+ supportsImageInput: true,+ });+ expect(resolvePiRuntimeModelDescriptor(catalog, 'cindy', 'gateway-text')).toMatchObject({+ supportsImageInput: false,+ });+ expect(resolvePiRuntimeModelDescriptor(catalog, 'cindy', 'gateway-unknown')).not.toHaveProperty(+ 'supportsImageInput',+ );+ });+it('bundled(未注入)派生 = 仅 xai 静态清单,动态供应商不贡献任何条目', () => {const cc = deriveAvailableModels(BUNDLED_CATALOG, 'claude-code');const codex = deriveAvailableModels(BUNDLED_CATALOG, 'codex');diff --git a/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts b/apps/desktop/src/main/maker-host/catalog-to-descriptors.tsindex beaf5838a7..cf1b0dc8ec 100644--- a/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts+++ b/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts@@ -82,6 +82,9 @@ function toDescriptor(if (m.defaultEnabled !== undefined) d.defaultEnabled = m.defaultEnabled;if (m.cost !== undefined) d.cost = m.cost;if (m.maxOutput !== undefined) d.maxOutputTokens = m.maxOutput;+ const supportsImageInput = m.supportsImageInput+ ?? (m.modalities !== undefined ? m.modalities.input.includes('image') : undefined);+ if (supportsImageInput !== undefined) d.supportsImageInput = supportsImageInput;return d;}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.tsindex fb5d849dbf..03b13e8dc6 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@@ -570,26 +570,64 @@ describe('Pi provider-aware model routing', () => {await handle.close();});- it('guards image prompts by the actual provider-model capability and follows model switches', async () => {- const agent = new PiAgent(byomDeps(async () => ({- providers: [- {- id: 'native-text',- name: 'Native Text',- baseUrl: 'http://text.test',- api: 'openai-completions',- models: [{ id: 'local-model', input: ['text'] }],- },- {- id: 'native-vision',- name: 'Native Vision',- baseUrl: 'http://vision.test',- api: 'openai-completions',- models: [{ id: 'local-model', input: ['text', 'image'] }],- },- ],- env: {},- })));+ it('guards image prompts by the startup provider-model capability and follows model switches', async () => {+ const gatewayModels: ModelDescriptor[] = [+ {+ id: 'gateway-text',+ displayName: 'Gateway Text',+ contextWindow: 200_000,+ efforts: [],+ defaultEffort: null,+ supportsImageInput: false,+ },+ {+ id: 'gateway-vision',+ displayName: 'Gateway Vision',+ contextWindow: 200_000,+ efforts: [],+ defaultEffort: null,+ supportsImageInput: true,+ },+ {+ id: 'gateway-unknown',+ displayName: 'Gateway Unknown',+ contextWindow: 200_000,+ efforts: [],+ defaultEffort: null,+ },+ {+ id: 'local-model',+ displayName: 'Local',+ contextWindow: 200_000,+ efforts: [],+ defaultEffort: null,+ },+ ];+ const resolveGatewayModel = vi.fn((modelId: string) =>+ gatewayModels.find((candidate) => candidate.id === modelId) ?? null,+ );+ const agent = new PiAgent({+ ...byomDeps(async () => ({+ providers: [+ {+ id: 'native-text',+ name: 'Native Text',+ baseUrl: 'http://text.test',+ api: 'openai-completions',+ models: [{ id: 'local-model', input: ['text'] }],+ },+ {+ id: 'native-vision',+ name: 'Native Vision',+ baseUrl: 'http://vision.test',+ api: 'openai-completions',+ models: [{ id: 'local-model', input: ['text', 'image'] }],+ },+ ],+ env: {},+ }), gatewayModels),+ resolvePiGatewayModelDescriptor: resolveGatewayModel,+ });const handle = await agent.startSession({sessionId: 'image-capability',workingDir: cwd,@@ -608,6 +646,37 @@ describe('Pi provider-aware model routing', () => {type: 'user' as const,content: [{ type: 'image' as const, path: imagePath }],};+ const mixedMessage = {+ type: 'user' as const,+ content: [+ { type: 'text' as const, text: 'describe this image' },+ { type: 'image' as const, path: imagePath },+ ],+ };+ const instructedMessage = {+ type: 'user' as const,+ content: [+ { type: 'text' as const, text: '$识图 请读取附件' },+ { type: 'image' as const, path: imagePath },+ ],+ };+ const multiImageMessage = {+ type: 'user' as const,+ content: [+ { type: 'image' as const, path: imagePath },+ { type: 'image' as const, path: imagePath },+ ],+ };+ const modelsJson = JSON.parse(+ readFileSync(path.join(captured.env.PI_CODING_AGENT_DIR as string, 'models.json'), 'utf8'),+ ) as {+ providers: Record<string, { models: Array<{ id: string; input: string[] }> }>;+ };+ expect(modelsJson.providers.cindy?.models).toEqual(expect.arrayContaining([+ expect.objectContaining({ id: 'gateway-text', input: ['text'] }),+ expect.objectContaining({ id: 'gateway-vision', input: ['text', 'image'] }),+ expect.objectContaining({ id: 'gateway-unknown', input: ['text'] }),+ ]));captured.requests.length = 0;await expect(handle.send(imageMessage)).rejects.toMatchObject({@@ -627,11 +696,42 @@ describe('Pi provider-aware model routing', () => {images: [expect.objectContaining({ type: 'image', mimeType: 'image/png' })],}));- // 显式清除来源后实际路由回到 cindy 网关;同名 BYOM 不能抢走能力判断。- await handle.setModel!('local-model', { providerId: null });+ // 网关纯文本模型在 Pi/provider 调用前拒绝所有带图形态;文本指令不能绕过能力门。+ await handle.setModel!('gateway-text', { providerId: null });captured.requests.length = 0;- await handle.send(imageMessage);- expect(captured.requests.some((request) => request.type === 'prompt')).toBe(true);+ for (const message of [imageMessage, mixedMessage, instructedMessage, multiImageMessage]) {+ await expect(handle.send(message)).rejects.toMatchObject({+ code: 'PI_IMAGE_INPUT_UNSUPPORTED',+ });+ }+ await expect(handle.steer!(mixedMessage)).rejects.toMatchObject({+ code: 'PI_IMAGE_INPUT_UNSUPPORTED',+ });+ expect(captured.requests.some((request) => request.type === 'prompt' || request.type === 'steer'))+ .toBe(false);++ // 能力未知同样 fail closed;活动会话只认启动时写入 models.json 的能力快照。+ await handle.setModel!('gateway-unknown', { providerId: null });+ await expect(handle.send(imageMessage)).rejects.toMatchObject({+ code: 'PI_IMAGE_INPUT_UNSUPPORTED',+ });+ gatewayModels[0]!.supportsImageInput = true;+ await handle.setModel!('gateway-text', { providerId: null });+ await expect(handle.send(imageMessage)).rejects.toMatchObject({+ code: 'PI_IMAGE_INPUT_UNSUPPORTED',+ });++ // 明确支持图片的网关模型保留全部图片块,多图不被剥离或改写。+ await handle.setModel!('gateway-vision', { providerId: null });+ captured.requests.length = 0;+ await handle.send(multiImageMessage);+ expect(captured.requests).toContainEqual(expect.objectContaining({+ type: 'prompt',+ images: [+ expect.objectContaining({ type: 'image', mimeType: 'image/png' }),+ expect.objectContaining({ type: 'image', mimeType: 'image/png' }),+ ],+ }));// 文件读失败不会生成 image block,仍保留既有的“图片不可读”文本语义。await handle.setModel!('local-model', { providerId: 'native-text' });diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 44d2352e15..0a60469388 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -435,7 +435,7 @@ export class PiAgent extends BaseAgent {agentHome: string,nativeProviders: PiNativeProviderSpec[] = [],retainedRuntimeModel?: ModelDescriptor,- ): Promise<void> {+ ): Promise<Map<string, boolean>> {const endpoint = this.deps.runtimeConfig.endpoint;if (!endpoint) {this.deps.logger.warn('pi: runtimeConfig.endpoint missing — models.json will have no usable provider');@@ -444,17 +444,20 @@ export class PiAgent extends BaseAgent {const runtimeModels = retainedRuntimeModel && !publicModels.some((m) => m.id === retainedRuntimeModel.id)? [...publicModels, retainedRuntimeModel]: publicModels;+ const gatewayImageInputByModel = new Map<string, boolean>();const models = runtimeModels.map((publicModel: ModelDescriptor) => {// availableModels 为跨 provider 拍平的公开能力;BYOM 同 id 冲突时 effort// 会按设计收敛成交集。cindy gateway 块则代表内置路由,必须回查其// provider-aware 描述符,不能被同名 non-reasoning BYOM 清空 reasoning。// host 未注入 resolver 或只有 BYOM 条目时保留旧 flat fallback。const m = this.deps.resolvePiGatewayModelDescriptor?.(publicModel.id) ?? publicModel;+ const supportsImageInput = m.supportsImageInput === true;+ gatewayImageInputByModel.set(m.id, supportsImageInput);return {id: m.id,name: m.displayName,reasoning: m.efforts.length > 0,- input: ['text', 'image'],+ input: supportsImageInput ? ['text', 'image'] : ['text'],contextWindow: m.contextWindow > 0 ? m.contextWindow : 200_000,maxTokens: m.maxOutputTokens && m.maxOutputTokens > 0 ? m.maxOutputTokens : 32_000,// 计费单位与目录一致($/1M tokens);pi 按此自行计价,usage 事件的 cost 才有真值。@@ -504,6 +507,7 @@ export class PiAgent extends BaseAgent {}await fs.mkdir(agentHome, { recursive: true });await fs.writeFile(path.join(agentHome, 'models.json'), JSON.stringify({ providers }, null, 2) + '\n');+ return gatewayImageInputByModel;}async startSession(opts: StartSessionOptions): Promise<AgentSessionHandle> {@@ -716,7 +720,11 @@ export class PiAgent extends BaseAgent {configHomeCleaned = true;void fs.rm(configHome, { recursive: true, force: true }).catch(() => {});};- await this.writeModelsJson(configHome, nativeProviders, retainedRuntimeModel);+ const gatewayImageInputByModel = await this.writeModelsJson(+ configHome,+ nativeProviders,+ retainedRuntimeModel,+ );const sessionDir = path.join(agentHome, 'sessions');await fs.mkdir(sessionDir, { recursive: true });@@ -1472,11 +1480,14 @@ export class PiAgent extends BaseAgent {};const assertImageInputSupported = (images: readonly PiPromptImage[]): void => {- if (images.length === 0 || mutablePiProviderId === PI_PROVIDER_ID) return;- const nativeModel = nativeProviderById- .get(mutablePiProviderId)- ?.models.find((candidate) => candidate.id === mutableModel);- if (nativeModel?.input?.includes('image')) return;+ if (images.length === 0) return;+ const supportsImageInput = mutablePiProviderId === PI_PROVIDER_ID+ ? gatewayImageInputByModel.get(mutableModel) === true+ : nativeProviderById+ .get(mutablePiProviderId)+ ?.models.find((candidate) => candidate.id === mutableModel)+ ?.input?.includes('image') === true;+ if (supportsImageInput) return;throw new PiImageInputUnsupportedError();};diff --git a/packages/maker-core/src/types/capabilities.ts b/packages/maker-core/src/types/capabilities.tsindex c73df2aaf4..017567e442 100644--- a/packages/maker-core/src/types/capabilities.ts+++ b/packages/maker-core/src/types/capabilities.ts@@ -270,6 +270,11 @@ export interface ModelDescriptor {cost?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number };/** 最大输出 tokens(源自目录 maxOutput)。缺省时各 agent 用自身默认值。 */maxOutputTokens?: number;+ /**+ * 当前实际 provider-model 路由是否明确支持图片输入。+ * 缺省表示能力未知;调用方必须 fail closed,不能据模型名或协议猜测。+ */+ supportsImageInput?: boolean;}/**