Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(agent): reserve native Apps name and enforce transport allowlist
Chris7665c610306c
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex 695610c878..b1e658a09d 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -3134,6 +3134,33 @@ describe('Bot canonical Session lifecycle', () => {}});+ // P1 integration: a quarantined persisted row used to duplicate the native+ // capability id, making selection operate on the wrong entry.+ it('lists and selects native Apps once despite a retained custom collision', async () => {+ h.customMcpConfigs.push({ id: 'codex_apps', name: 'Legacy custom Apps', transport: 'http',+ url: 'https://example.invalid/legacy', headers: {} });+ await refreshCustomMcpProviders();+ await invoke('local-db:bots:update', {+ id: 'bot-1', capabilities: { mcpServers: [], mcpMode: 'allowlist' },+ });+ const created = await invoke('local-db:bots:create-canonical-session', {+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 2,+ });+ const service = createBotCapabilityService({ ...capabilityDeps, resolveBotAgentKind: async () => 'codex' });+ h.validateCapabilityAdditions.mockImplementation(service.validateAdditions);+ const input = { callerSessionId: created.session.id, kind: 'mcp' as const, id: 'codex_apps' };+ const result = await service.list(input);+ expect(result.ok).toBe(true);+ if (!result.ok) throw new Error(result.message);+ expect(result.capabilities.filter((entry) => entry.id === 'codex_apps')).toEqual([+ expect.objectContaining({ name: 'codex_apps', available: true, joined: false }),+ ]);+ await expect(service.select({ ...input, joined: true })).resolves.toMatchObject({ ok: true });+ await expect(service.select({ ...input, joined: false })).resolves.toMatchObject({ ok: true });+ expect(h.mcpProviders.some((provider) => provider.name === 'codex_apps')).toBe(false);+ expect(h.customMcpConfigs.some((entry) => entry.id === 'codex_apps')).toBe(true);+ });+it('rejects unforwarded custom MCPs on SSH Codex while preserving saved references and supported routes', async () => {await invoke('local-db:bots:update', {id: 'bot-1', capabilities: { mcpServers: ['shared-docs'], mcpMode: 'allowlist' },diff --git a/apps/desktop/src/main/maker-host/__tests__/agentCapabilityCatalog.test.ts b/apps/desktop/src/main/maker-host/__tests__/agentCapabilityCatalog.test.tsindex fdc4d745b4..f7270e571d 100644--- a/apps/desktop/src/main/maker-host/__tests__/agentCapabilityCatalog.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/agentCapabilityCatalog.test.ts@@ -31,6 +31,20 @@ describe('shared runtime capability discovery', () => {expect(read).toHaveBeenCalledTimes(1);});+ // P1: a custom provider silently replaced native metadata in both catalogs.+ it('keeps native Apps authoritative when a provider has the same name', async () => {+ const runtime = { ...context, agentKind: 'codex' as const };+ const factory = vi.fn();+ const providers = [{ name: 'codex_apps', toClaudeSdkConfig: factory }];+ const catalog = buildBotMcpCatalog({ ...runtime, providers, builtinNames: [],+ customServers: [{ id: 'codex_apps', transport: 'http', updatedAt: 1 }] });+ expect(catalog).toEqual([expect.objectContaining({ name: 'codex_apps', source: 'harness' })]);+ expect(await readAgentCapabilityCatalog(providers, runtime, {})).toMatchObject({ capabilities: [+ { server: 'codex_apps', source: 'harness', status: 'engine-managed' },+ ] });+ expect(factory).not.toHaveBeenCalled();+ });+it.each(['claude-code', 'codex', 'pi'] as const)('does not advertise the retired simulator in the %s provider catalog', async (agentKind) => {const providers = createLiziMcpProviders({android: {} as never, browser: {} as never, computer: {} as never,diff --git a/apps/desktop/src/main/maker-host/__tests__/custom-mcp-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/custom-mcp-store.test.tsindex 4f3607996c..5277946d06 100644--- a/apps/desktop/src/main/maker-host/__tests__/custom-mcp-store.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/custom-mcp-store.test.ts@@ -148,13 +148,21 @@ describe('validateCustomMcpConfig', () => {expect(result.ok === false && result.message).toContain('reserved');});+ // Native names are reserved even before any transport provider is registered.+ it('rejects the native Apps id without rejecting a distinct custom id', () => {+ expect(validateCustomMcpConfig({ ...valid, id: 'codex_apps' })).toMatchObject({+ ok: false, code: 'INVALID_PARAMS', message: expect.stringContaining('reserved'),+ });+ expect(validateCustomMcpConfig({ ...valid, id: 'codex_apps_custom' })).toEqual({ ok: true });+ });+it('keeps accepting ids that only resemble a builtin name', () => {expect(validateCustomMcpConfig({ ...valid, id: 'cindy_browser_x' }, ['cindy_browser'])).toEqual({ok: true,});});- it('skips the reserved-id check when no reserved list is supplied', () => {+ it('does not infer dynamic builtin names when no reserved list is supplied', () => {expect(validateCustomMcpConfig({ ...valid, id: 'cindy_browser' })).toEqual({ ok: true });});diff --git a/apps/desktop/src/main/maker-host/agentCapabilityCatalog.ts b/apps/desktop/src/main/maker-host/agentCapabilityCatalog.tsindex 427e4aef6d..facd628964 100644--- a/apps/desktop/src/main/maker-host/agentCapabilityCatalog.ts+++ b/apps/desktop/src/main/maker-host/agentCapabilityCatalog.ts@@ -36,7 +36,8 @@ export async function readAgentCapabilityCatalog(availability: (provider: McpProvider) => string | null = () => null,readHarnessTools?: HarnessMcpToolsReader,) {- const declarations = [...providers.map((provider) => {+ const harness = getHarnessMcpCatalog(context);+ const declarations = [...providers.filter((provider) => !harness.some((entry) => entry.name === provider.name)).map((provider) => {let reason: string | null = null;try {const mounted = context.vendorOptions?.[RUNTIME_MCP_NAMES_KEY];@@ -53,8 +54,7 @@ export async function readAgentCapabilityCatalog(...(reason ? { reason } : {}),...(provider.capability?.discovery ? { discovery: provider.capability.discovery } : {}),};- }), ...getHarnessMcpCatalog(context)- .filter((entry) => !providers.some((provider) => provider.name === entry.name))+ }), ...harness.map((entry) => ({server: entry.name, title: entry.title, description: entry.description, source: entry.source,status: entry.available ? 'engine-managed' : 'unavailable',diff --git a/apps/desktop/src/main/maker-host/botMcpCatalog.ts b/apps/desktop/src/main/maker-host/botMcpCatalog.tsindex 318f6adb75..88470ec9c4 100644--- a/apps/desktop/src/main/maker-host/botMcpCatalog.ts+++ b/apps/desktop/src/main/maker-host/botMcpCatalog.ts@@ -53,6 +53,6 @@ export function buildBotMcpCatalog(input: {: custom ? `${custom.transport}:${custom.updatedAt}` : 'custom:unknown',}];})).values()];- return [...providers, ...getHarnessMcpCatalog(input).filter((entry) =>- !providers.some((provider) => provider.name === entry.name))];+ const harness = getHarnessMcpCatalog(input);+ return [...providers.filter((provider) => !harness.some((entry) => entry.name === provider.name)), ...harness];}diff --git a/apps/desktop/src/main/maker-host/custom-mcp-store.ts b/apps/desktop/src/main/maker-host/custom-mcp-store.tsindex 0021a1a3c1..97313cdf7d 100644--- a/apps/desktop/src/main/maker-host/custom-mcp-store.ts+++ b/apps/desktop/src/main/maker-host/custom-mcp-store.ts@@ -14,6 +14,7 @@import { asc, eq, sql } from 'drizzle-orm';+import { HARNESS_MCP_SERVER_NAMES } from './harnessMcpCatalog.js';import { getDbClient } from '../localDb/client/current.js';import { customMcpServers } from '../localDb/schema.js';import {@@ -75,7 +76,8 @@ function invalid(message: string): ValidationResult {** `reservedIds` 传内置 MCP server 名(生产由 getBuiltinMcpServerNames() 派生)。撞名的* 自定义 MCP 会在装配层按 key 顶替内置 server,还顺带继承审批策略里对该 server 名的- * 信任,所以这里直接拒收;装配层另有一道纵深防御会跳过它。+ * 信任,所以这里直接拒收;引擎保留名也在这里统一检查,不依赖 provider 注册时机。+ * 装配层复用校验隔离历史撞名配置,保留原有数据。*/export function validateCustomMcpConfig(config: unknown,@@ -90,8 +92,8 @@ export function validateCustomMcpConfig(if (UNSAFE_OBJECT_KEYS.has(c.id)) {return invalid(`id '${c.id}' is not allowed`);}- if (reservedIds.includes(c.id)) {- return invalid(`id '${c.id}' is reserved by a builtin MCP server; pick another id`);+ if (reservedIds.includes(c.id) || HARNESS_MCP_SERVER_NAMES.includes(c.id)) {+ return invalid(`id '${c.id}' is reserved by a builtin or engine MCP server; pick another id`);}if (typeof c.name !== 'string' || c.name.trim().length === 0) return invalid('name required');diff --git a/apps/desktop/src/main/maker-host/harnessMcpCatalog.ts b/apps/desktop/src/main/maker-host/harnessMcpCatalog.tsindex 27ae8f1499..3c660a793d 100644--- a/apps/desktop/src/main/maker-host/harnessMcpCatalog.ts+++ b/apps/desktop/src/main/maker-host/harnessMcpCatalog.ts@@ -1,10 +1,14 @@import type { McpProviderContext } from '@cindy/maker-core';+// Reserved across all engines: custom configs are shared and can outlive a route switch.+const CODEX_APPS_SERVER_NAME = 'codex_apps';+export const HARNESS_MCP_SERVER_NAMES: readonly string[] = [CODEX_APPS_SERVER_NAME];+/** Engine-owned surfaces have no Cindy transport. This is metadata, not a connection claim. */export function getHarnessMcpCatalog(context: { agentKind: McpProviderContext['agentKind']; remoteHostId?: string | null }) {if (context.agentKind !== 'codex') return [];return [{- name: 'codex_apps',+ name: CODEX_APPS_SERVER_NAME,title: 'Codex Apps',description: 'External service connectors supplied by Codex; availability and tools come from the current thread. These are not Cindy tasks, routines or plugins.',source: 'harness' as const,diff --git a/apps/desktop/src/main/maker-ipc/__tests__/mcpHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/mcpHandlers.test.tsindex 544cd27de2..df475fd632 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/mcpHandlers.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/mcpHandlers.test.ts@@ -211,6 +211,22 @@ describe('mcp:custom:* CRUD handlers', () => {expect(deps.invalidateCodex).toHaveBeenCalledOnce();});+ // P1 integration: both production write handlers reject the engine-owned id+ // before storing or refreshing it; the config validator is not mocked.+ it('rejects native Apps collisions on create and update before side effects', async () => {+ mountDb();+ const harness = new IpcHarness();+ const deps = makeDeps();+ registerMcpHandlers(harness, deps);+ for (const channel of [MAKER_INVOKE.MCP_CUSTOM_CREATE, MAKER_INVOKE.MCP_CUSTOM_UPDATE]) {+ await expect(harness.invoke(channel, { ...validConfig, id: 'codex_apps' })).rejects.toThrow(/reserved/);+ }+ expect(await listCustomMcpServers()).toEqual([]);+ expect(deps.refreshProviders).not.toHaveBeenCalled();+ expect(deps.broadcastChanged).not.toHaveBeenCalled();+ expect(deps.invalidateCodex).not.toHaveBeenCalled();+ });+it('a failing invalidateCodex does not fail the CRUD (best-effort)', async () => {mountDb();const harness = new IpcHarness();diff --git a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts b/apps/desktop/src/main/maker-ipc/botCapabilityService.tsindex 0344e43fe0..571ec0c630 100644--- a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts+++ b/apps/desktop/src/main/maker-ipc/botCapabilityService.ts@@ -143,14 +143,17 @@ async function catalog(input: Input, ctx: Pick<Awaited<ReturnType<typeof contextconst available = new Set(runtimeCatalog.filter((entry) => entry.source === 'custom' && entry.available !== false).map((entry) => entry.name));+ const harness = runtimeCatalog.filter((entry) => entry.source === 'harness');+ // Legacy collisions remain in custom settings, but cannot replace or duplicate+ // the engine-owned capability in this selection list.// Project only display metadata. URLs, headers and tokens never enter tool results.- items = (await listCustomMcpServers()).map((mcp) => ({+ items = (await listCustomMcpServers()).filter((mcp) => !harness.some((entry) => entry.name === mcp.id)).map((mcp) => ({id: mcp.id,name: mcp.name,description: mcp.transport,available: available.has(mcp.id),}));- items.push(...runtimeCatalog.filter((entry) => entry.source === 'harness').map((entry) => ({+ items.push(...harness.map((entry) => ({id: entry.name, name: entry.name,description: 'Engine-provided connectors; not Cindy tasks, routines or plugins.',available: entry.available !== false,diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/custom-mcp-registry.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/custom-mcp-registry.test.tsindex fec52dacbf..bb20fc274e 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/custom-mcp-registry.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/custom-mcp-registry.test.ts@@ -118,6 +118,19 @@ describe('refreshCustomMcpProviders', () => {expect(Object.getPrototypeOf({} as Record<string, unknown>)).toBe(Object.prototype);});+ // P1: stored native-name collisions bypassed provider-only reserved names.+ // Exercise refresh with the real validator, including repeated refresh.+ it('quarantines a persisted native Apps collision without mutating stored configs', async () => {+ const arr: McpProvider[] = [];+ registerCustomMcpArrays(arr);+ const saved = [config('codex_apps'), config('safe_one')];+ storeMock.listCustomMcpServers.mockResolvedValue(saved);+ await refreshCustomMcpProviders();+ await refreshCustomMcpProviders();+ expect(arr.map((p) => p.name)).toEqual(['safe_one']);+ expect(saved.map((entry) => entry.id)).toEqual(['codex_apps', 'safe_one']);+ });+it('quarantines persisted configs with invalid custom headers', async () => {const arr: McpProvider[] = [builtin('cindy_browser')];registerCustomMcpArrays(arr);diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex e6cfc6a8ac..3206de7424 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -450,6 +450,9 @@ Codex 原生 `codex_apps` 纳入伙伴 MCP 元数据目录,来源标为 `harne筛选与 `nextOffset` / `offset` 翻页,避免全量 Apps 工具灌满上下文。伙伴能力工具可发现、加入或移除该项;现有自定义MCP 设置列表仍只管理用户配置的 transport,不把原生 Apps 伪装成可编辑地址的自定义服务。SSH Codex 不提供这项本机原生能力,目录如实标为不可用。+`codex_apps` 是引擎保留名:自定义 MCP 新建/修改时拒收,历史同名配置保留但不装配;+能力目录只呈现原生项,避免同 id 串扰。引擎配置中若已有同名真实 transport,仍须按伙伴+白名单禁用,不能因名字与原生 Apps 相同而跳过。轻量不等于没有 Skill。伙伴启动时按以下优先级构造能力:diff --git a/packages/maker-core/src/agents/codex/bot-mcp-policy.integration.test.ts b/packages/maker-core/src/agents/codex/bot-mcp-policy.integration.test.tsindex e2e17fbd1b..a5b76276a4 100644--- a/packages/maker-core/src/agents/codex/bot-mcp-policy.integration.test.ts+++ b/packages/maker-core/src/agents/codex/bot-mcp-policy.integration.test.ts@@ -14,7 +14,9 @@ import type { Logger } from '../../interfaces/logger.js';const binaryPath = process.env.CINDY_TEST_CODEX_BINARY;const logger: Logger = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child: () => logger };-it.skipIf(!binaryPath).each([false, true])('enforces Bot MCP selection in a real native thread (external=%s)', async (external) => {+it.skipIf(!binaryPath).each([+ { external: false, collision: false }, { external: true, collision: false }, { external: false, collision: true },+])('enforces Bot MCP selection in a real native thread ($external, collision=$collision)', async ({ external, collision }) => {const root = await mkdtemp(path.join(tmpdir(), 'cindy-bot-mcp-native-'));const home = path.join(root, 'codex');const workingDir = path.join(root, 'work');@@ -24,7 +26,9 @@ it.skipIf(!binaryPath).each([false, true])('enforces Bot MCP selection in a reallet activeHandle: AgentSessionHandle | undefined;let duringToolReport: AgentMcpServerToolsReport | null | undefined;let duringToolError: unknown;+ let collisionConnections = 0;const server = createServer(async (req, res) => {+ if (req.url === '/collision') collisionConnections += 1;let body = '';for await (const chunk of req) body += chunk;if (req.method !== 'POST') { res.writeHead(405).end(); return; }@@ -72,6 +76,7 @@ it.skipIf(!binaryPath).each([false, true])('enforces Bot MCP selection in a real'-c', 'mcp_servers.cindy_memory={command="false",enabled=false}','-c', `mcp_servers.cindy_helper={url="${endpoint}/helper"}`,'-c', `mcp_servers.fixture_external={url="${endpoint}/external"}`,+ ...(collision ? ['-c', `mcp_servers.codex_apps={url="${endpoint}/collision"}`] : []),], extraEnv: {} }),auth: {getState: async () => ({ authenticated: true }), triggerLogin: async () => ({ authenticated: true }), logout: async () => {},@@ -121,6 +126,10 @@ it.skipIf(!binaryPath).each([false, true])('enforces Bot MCP selection in a realconst report = await handle.readMcpServerTools?.('fixture_external');if (external) expect(report).toMatchObject({ state: 'connected', tools: [{ name: 'external_echo' }] });else expect(report?.tools).toEqual([]);+ if (collision) {+ expect((await handle.readMcpServerTools?.('codex_apps'))?.tools).toEqual([]);+ expect(collisionConnections).toBe(0);+ }} finally { await handle.close(); }} finally {await agent?.dispose();diff --git a/packages/maker-core/src/agents/codex/capability-routing.test.ts b/packages/maker-core/src/agents/codex/capability-routing.test.tsindex 33599b7fde..4a8ee6e83b 100644--- a/packages/maker-core/src/agents/codex/capability-routing.test.ts+++ b/packages/maker-core/src/agents/codex/capability-routing.test.ts@@ -164,13 +164,26 @@ describe('Bot MCP config', () => {});});+ // P1 regression: only real transports enter this set; a colliding custom name+ // must not escape the restriction. Existing native-only cases had no transport.+ it('disables an unselected transport named codex_apps', () => {+ expect(buildCodexBotMcpConfigOverrides({+ mode: 'allowlist', configured: [],+ catalog: [{ name: 'codex_apps', source: 'custom' }, { name: 'other_service', source: 'custom' }],+ }, new Set(['codex_apps', 'other_service']))).toEqual({+ 'features.apps': false,+ 'mcp_servers.codex_apps.enabled': false,+ 'mcp_servers.other_service.enabled': false,+ });+ });+// Regression: native Apps has no transport and escaped explicit Bot restrictions.// Unit tier: inspect actual thread config; never synthesize or enable a transport/account.it.each([true, false])('preserves the native Apps selection (allowed=%s)', (allowed) => {expect(buildCodexBotMcpConfigOverrides({mode: 'allowlist', configured: allowed ? ['codex_apps'] : [],catalog: [{ name: 'codex_apps', source: 'harness', available: true }],- }, new Set(['codex_apps']))).toEqual(allowed ? {} : { 'features.apps': false });+ }, new Set())).toEqual(allowed ? {} : { 'features.apps': false });expect(buildCodexBotMcpConfigOverrides(undefined, new Set())).toEqual({});expect(buildCodexBotMcpConfigOverrides({ mode: 'inherit', configured: [], catalog: [] }, new Set())).toEqual({});});diff --git a/packages/maker-core/src/agents/codex/capability-routing.ts b/packages/maker-core/src/agents/codex/capability-routing.tsindex 6fe3a8d9b5..4d6d37a750 100644--- a/packages/maker-core/src/agents/codex/capability-routing.ts+++ b/packages/maker-core/src/agents/codex/capability-routing.ts@@ -93,7 +93,8 @@ export function buildCodexBotMcpConfigOverrides(// Codex parses transport before enabled. Never synthesize disabled-only// entries for absent servers: even `enabled=false` makes thread/start fail.for (const name of transportServerNames) {- if (name === 'codex_apps') continue;+ // Native Apps has no transport. A real transport with the same name must+ // still obey the allowlist (including configs inherited from CODEX_HOME).const restricted = ['cindy_group_history', 'cindy_orca'].includes(name);if (!restricted && isBotMcpServerAllowed(policy, name)) continue;result[`mcp_servers.${renderThreadConfigKeySegment(name)}.enabled`] = false;