Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(agent): preserve Cindy business ownership across native tools
Chris573eefc62c21
diff --git a/apps/desktop/src/main/maker-host/__tests__/agentCapabilityCatalog.test.ts b/apps/desktop/src/main/maker-host/__tests__/agentCapabilityCatalog.test.tsindex b7fa3956c6..fdc4d745b4 100644--- a/apps/desktop/src/main/maker-host/__tests__/agentCapabilityCatalog.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/agentCapabilityCatalog.test.ts@@ -3,10 +3,34 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';import { createLiziMcpProviders } from '@cindy/mcps';import { readAgentCapabilityCatalog, RUNTIME_MCP_NAMES_KEY } from '../agentCapabilityCatalog';+import { buildBotMcpCatalog } from '../botMcpCatalog';const context = { agentKind: 'pi' as const, workingDir: '/repo', sessionId: 'task' };describe('shared runtime capability discovery', () => {+ // Incident regression: visible native Apps returned UNKNOWN_CAPABILITY and+ // disappeared from the default Bot catalog. Existing tests only cover providers.+ // Unit tier, real catalog entry points with a read-only engine status fixture.+ it('discovers native Apps without pretending Cindy registered its transport', async () => {+ const runtime = { ...context, agentKind: 'codex' as const,+ vendorOptions: { [RUNTIME_MCP_NAMES_KEY]: [] } };+ const catalog = buildBotMcpCatalog({ ...runtime, providers: [], builtinNames: [], customServers: [] });+ expect(catalog).toContainEqual(expect.objectContaining({ name: 'codex_apps', source: 'harness', available: true }));+ expect(await readAgentCapabilityCatalog([], runtime, {})).toMatchObject({ capabilities: [+ { server: 'codex_apps', source: 'harness', status: 'engine-managed' },+ ] });+ const read = vi.fn(async () => ({ state: 'connected' as const, tools: [{ name: 'github_get_user_login' }] }));+ expect(await readAgentCapabilityCatalog([], runtime, { server: 'codex_apps' }, undefined, read))+ .toMatchObject({ ok: true, tools: [{ name: 'github_get_user_login' }] });+ expect(read).toHaveBeenCalledWith('codex_apps');+ expect(await readAgentCapabilityCatalog([], runtime, { server: 'codex_apps' }, undefined,+ async () => ({ state: 'not-mounted', tools: [] })))+ .toMatchObject({ ok: false, engineState: 'not-mounted' });+ expect(await readAgentCapabilityCatalog([], { ...runtime, remoteHostId: 'ssh-fixture' }, { server: 'codex_apps' }, undefined, read))+ .toMatchObject({ ok: false, capability: { status: 'unavailable' } });+ expect(read).toHaveBeenCalledTimes(1);+ });+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,@@ -74,6 +98,21 @@ describe('shared runtime capability discovery', () => {describe('servers the engine connects itself', () => {const custom = [{ name: 'custom_omc', toClaudeSdkConfig: vi.fn() }];+ // Live Apps discovery produced ~60K tokens. Page/filter the actual engine+ // result so discovery stays bounded without hiding the remaining tools.+ it('pages and searches large engine catalogs without dropping access to the tail', async () => {+ const read = async () => ({ state: 'connected' as const, tools: Array.from({ length: 51 }, (_, index) => ({ name: `tool_${index}` })) });+ const first = await readAgentCapabilityCatalog(custom, context, { server: 'custom_omc' }, undefined, read);+ expect(first).toMatchObject({ totalTools: 51, matchedTools: 51, nextOffset: 50 });+ expect('tools' in first && first.tools).toHaveLength(50);+ expect(await readAgentCapabilityCatalog(custom, context, { server: 'custom_omc', offset: 50 }, undefined, read))+ .toMatchObject({ tools: [{ name: 'tool_50' }], nextOffset: null });+ expect(await readAgentCapabilityCatalog(custom, context, { server: 'custom_omc', toolQuery: 'TOOL_50' }, undefined, read))+ .toMatchObject({ tools: [{ name: 'tool_50' }], matchedTools: 1, nextOffset: null });+ expect(await readAgentCapabilityCatalog(custom, context, { server: 'custom_omc', toolQuery: 'absent' }, undefined, read))+ .toMatchObject({ ok: true, tools: [], matchedTools: 0, nextOffset: null });+ });+it('lists the tools the caller engine actually holds for the server', async () => {const read = vi.fn(async () => ({ state: 'connected' as const, tools: [{ name: 'search', description: 'x'.repeat(400) }, { name: 'open' },diff --git a/apps/desktop/src/main/maker-host/agentCapabilityCatalog.ts b/apps/desktop/src/main/maker-host/agentCapabilityCatalog.tsindex c89a1b1ca4..427e4aef6d 100644--- a/apps/desktop/src/main/maker-host/agentCapabilityCatalog.ts+++ b/apps/desktop/src/main/maker-host/agentCapabilityCatalog.ts@@ -1,6 +1,7 @@import { Client } from '@modelcontextprotocol/sdk/client/index.js';import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import { getHarnessMcpCatalog } from './harnessMcpCatalog.js';import type {AgentMcpServerToolsReport,AgentMcpServerToolsState,@@ -10,7 +11,7 @@ import type {export const RUNTIME_MCP_NAMES_KEY = 'cindyRuntimeMcpServerNames';-export interface AgentCapabilityQuery { server?: string; category?: string; }+export interface AgentCapabilityQuery { server?: string; category?: string; toolQuery?: string; offset?: number; }/** The caller session's engine view of one MCP server; null = engine has no such entry. */export type HarnessMcpToolsReader = (server: string) => Promise<AgentMcpServerToolsReport | null>;@@ -30,12 +31,12 @@ const HARNESS_STATE_MESSAGES: Record<Exclude<AgentMcpServerToolsState, 'connecte/** Read the actual provider registrations. This catalog never grants permissions or starts tools. */export async function readAgentCapabilityCatalog(providers: readonly McpProvider[],- context: McpProviderContext,+ context: McpProviderContext & { remoteHostId?: string | null },query: AgentCapabilityQuery,availability: (provider: McpProvider) => string | null = () => null,readHarnessTools?: HarnessMcpToolsReader,) {- const declarations = providers.map((provider) => {+ const declarations = [...providers.map((provider) => {let reason: string | null = null;try {const mounted = context.vendorOptions?.[RUNTIME_MCP_NAMES_KEY];@@ -52,24 +53,30 @@ export async function readAgentCapabilityCatalog(...(reason ? { reason } : {}),...(provider.capability?.discovery ? { discovery: provider.capability.discovery } : {}),};- });+ }), ...getHarnessMcpCatalog(context)+ .filter((entry) => !providers.some((provider) => provider.name === entry.name))+ .map((entry) => ({+ server: entry.name, title: entry.title, description: entry.description, source: entry.source,+ status: entry.available ? 'engine-managed' : 'unavailable',+ ...(!entry.available ? { reason: 'transport-unavailable-for-current-runtime' } : {}),+ }))];if (!query.server) return {ok: true, agent: context.agentKind, capabilities: declarations,- hint: 'registered 表示已注册且入口条件满足,连接、设备与具体操作仍以发现和执行回执为准。指定 server 查询实际工具;插件沿其 discovery 入口展开。原生文件、命令行与子 Agent 工具由当前引擎提供,不属于 MCP 工具计数。',+ hint: 'registered 表示已注册且入口条件满足;engine-managed 表示由引擎管理,不代表已连接或已授权。连接、设备与具体操作仍以发现和执行回执为准。指定 server 查询实际工具;插件沿其 discovery 入口展开。原生文件、命令行与子 Agent 工具由当前引擎提供,不属于 MCP 工具计数。',};const declaration = declarations.find((item) => item.server === query.server);if (!declaration) return { ok: false, errorCode: 'UNKNOWN_CAPABILITY', available: declarations.map((item) => item.server) };if (declaration.status === 'unavailable') return { ok: false, capability: declaration };- const provider = providers.find((item) => item.name === query.server)!;// External connections are owned by the harness; never start another process,// inspect its credentials or execute a custom server's business operations.- if (declaration.source !== 'builtin') return readHarnessCapability(declaration, readHarnessTools);+ if (declaration.source !== 'builtin') return readHarnessCapability(declaration, readHarnessTools, query);+ const provider = providers.find((item) => item.name === query.server)!;let instance: McpServer | undefined;let client: Client | undefined;try {const config = provider.toClaudeSdkConfig?.({ ...context, getSessionContext: () => context });const candidate = config && typeof config === 'object' && 'instance' in config ? config.instance : undefined;- if (!(candidate instanceof McpServer)) return await readHarnessCapability(declaration, readHarnessTools);+ if (!(candidate instanceof McpServer)) return await readHarnessCapability(declaration, readHarnessTools, query);instance = candidate;client = new Client({ name: 'cindy-capability-catalog', version: '1.0.0' });const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();@@ -106,6 +113,7 @@ export async function readAgentCapabilityCatalog(async function readHarnessCapability<T extends { server: string }>(declaration: T,readHarnessTools: HarnessMcpToolsReader | undefined,+ query: AgentCapabilityQuery,) {const base = { capability: declaration, discovery: 'harness-mcp' as const };if (!readHarnessTools) return {@@ -121,9 +129,11 @@ async function readHarnessCapability<T extends { server: string }>(timer = setTimeout(() => reject(new Error('timeout')), HARNESS_READ_TIMEOUT_MS);}),]);- } catch {+ } catch (error) {+ const timedOut = error instanceof Error && (error.name === 'AppServerRequestTimeoutError' || error.message === 'timeout');return {ok: false, ...base, errorCode: 'HARNESS_DISCOVERY_FAILED',+ reason: timedOut ? 'timeout' : 'engine-read-failed',message: '读取当前引擎的 MCP 工具目录失败,暂时无法确认此服务的工具;稍后重试。',};} finally {@@ -137,13 +147,19 @@ async function readHarnessCapability<T extends { server: string }>(ok: false, ...base, errorCode: 'HARNESS_MCP_NOT_READY', engineState: report.state,message: HARNESS_STATE_MESSAGES[report.state],};+ const term = query.toolQuery?.trim().toLocaleLowerCase();+ const matching = term ? report.tools.filter((tool) => `${tool.name}\n${tool.description ?? ''}`.toLocaleLowerCase().includes(term)) : report.tools;+ const offset = Math.max(0, Math.floor(query.offset ?? 0));+ const page = matching.slice(offset, offset + 50);return {ok: true, ...base, engineState: report.state,- tools: report.tools.map((tool) => tool.description && tool.description.length > TOOL_DESCRIPTION_MAX_CHARS+ totalTools: report.tools.length, matchedTools: matching.length,+ nextOffset: offset + page.length < matching.length ? offset + page.length : null,+ tools: page.map((tool) => tool.description && tool.description.length > TOOL_DESCRIPTION_MAX_CHARS? { ...tool, description: `${tool.description.slice(0, TOOL_DESCRIPTION_MAX_CHARS)}…` }: tool),hint: report.tools.length > 0- ? '以上是当前引擎在本任务中为此服务实际持有的工具(服务端原始名称),引擎会按自身规则命名后提供(通常带服务名前缀)。'+ ? '以上是当前引擎在本任务中实际持有的工具(服务端原始名称)。可用 toolQuery 缩小范围;有 nextOffset 时沿用同一 server 和 toolQuery 查询下一页。引擎会按自身规则命名后提供工具(通常带服务名前缀)。': '此服务已连接,但没有提供任何工具。',};}diff --git a/apps/desktop/src/main/maker-host/botMcpCatalog.ts b/apps/desktop/src/main/maker-host/botMcpCatalog.tsindex 9237bf42ea..318f6adb75 100644--- a/apps/desktop/src/main/maker-host/botMcpCatalog.ts+++ b/apps/desktop/src/main/maker-host/botMcpCatalog.ts@@ -2,6 +2,7 @@ import type { McpProvider, McpProviderContext } from '@cindy/maker-core';import type { McpTransport } from '../../shared/customMcp.js';import { isPiCustomMcpProviderAvailable } from '../mcp-integrations/piMcpTransport.js';import { CustomMcpProvider } from '../mcp-integrations/custom-mcp-provider.js';+import { getHarnessMcpCatalog } from './harnessMcpCatalog.js';function isCustomMcpAvailable(input: {agentKind: McpProviderContext['agentKind'];@@ -34,7 +35,7 @@ export function buildBotMcpCatalog(input: {}) {const builtinNames = new Set(input.builtinNames);const customServers = new Map(input.customServers.map((entry) => [entry.id, entry]));- return [...new Map(input.providers.map((provider) => {+ const providers = [...new Map(input.providers.map((provider) => {const builtin = builtinNames.has(provider.name) && provider.name !== 'companion_connections';const custom = customServers.get(provider.name);// Builtins retain their SDK bridge path and are not instantiated by catalog queries.@@ -52,4 +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))];}diff --git a/apps/desktop/src/main/maker-host/business-ownership-prompt.md b/apps/desktop/src/main/maker-host/business-ownership-prompt.mdnew file mode 100644index 0000000000..2592ed820a--- /dev/null+++ b/apps/desktop/src/main/maker-host/business-ownership-prompt.md@@ -0,0 +1 @@+The user is working inside Cindy. Keep Cindy tasks, teammate routines, automations, plugins, model settings and sign-in flows in Cindy unless the user explicitly selects another application. The execution engine, subscription, native Skill or connector provider does not determine where this work belongs. “Your automation” alone does not select ChatGPT or Codex automation. Use the relevant Cindy capability directly when available; before claiming it is missing, check the relevant host discovery entry (cindy_helper get_capabilities or list_tools). If the intended application remains ambiguous, clarify that choice once. When choosing another tool or using desktop/browser control, preserve the intended application, account, execution owner and result destination. Verify those from the operation's receipt before reporting success. Explicitly requested external work, native CLI use and extension management remain available; do not ask again when the destination is already clear.diff --git a/apps/desktop/src/main/maker-host/harnessMcpCatalog.ts b/apps/desktop/src/main/maker-host/harnessMcpCatalog.tsnew file mode 100644index 0000000000..27ae8f1499--- /dev/null+++ b/apps/desktop/src/main/maker-host/harnessMcpCatalog.ts@@ -0,0 +1,14 @@+import type { McpProviderContext } from '@cindy/maker-core';++/** 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',+ 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,+ available: !context.remoteHostId,+ generation: 'codex-apps:1',+ }];+}diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.tsindex 4e44a56bbd..064b47ff32 100644--- a/apps/desktop/src/main/maker-host/pi-host.ts+++ b/apps/desktop/src/main/maker-host/pi-host.ts@@ -100,6 +100,7 @@ import { hostCredentialEndpointAllowed } from './pi-provider-transport.js';import { hasGrokOAuthLogin } from './grok-oauth-login.js';import { isOpenAiSubscriptionProviderId } from './codex-account-auth.js';import hostSystemPrompt from './host-system-prompt.md?raw';+import businessOwnershipPrompt from './business-ownership-prompt.md?raw';import piSystemPrompt from './pi-system-prompt.md?raw';import { createLogger } from '../logger.js';import { readMemorySettings } from './memory-settings-store.js';@@ -867,7 +868,7 @@ function buildDesktopPiRuntimeConfig(): AgentRuntimeConfig {// 代输入: sudo / ssh / git password prompts of this task go to the owner.taskShellEnv: inputHandoffTaskShellEnv,// 保留 host 共用身份段,再追加 Pi 专属行为段;maker-core 会整体追加到 Pi 原生 prompt。- systemPrompt: composePiSystemPrompt(hostSystemPrompt, piSystemPrompt),+ systemPrompt: composePiSystemPrompt(`${hostSystemPrompt.trim()}\n\n${businessOwnershipPrompt.trim()}`, piSystemPrompt),answerDeliveryPrompt: ANSWER_DELIVERY_PROMPT,// Pi 的 grep 以及 Cindy 覆盖的 find 都固定复用随 Desktop 校验、打包的 rg。// 下发绝对路径而非 PATH,避免 Windows 从不受信工作目录优先命中同名 rg.exe。diff --git a/apps/desktop/src/main/maker-host/runtime-configs.ts b/apps/desktop/src/main/maker-host/runtime-configs.tsindex df799d91d3..2777eaa5fc 100644--- a/apps/desktop/src/main/maker-host/runtime-configs.ts+++ b/apps/desktop/src/main/maker-host/runtime-configs.ts@@ -24,6 +24,7 @@ import { hasClaudeNativeLogin } from './claude-native-auth.js';import claudeSystemPrompt from './claude-system-prompt.md?raw';import codexSystemPrompt from './codex-system-prompt.md?raw';import hostSystemPrompt from './host-system-prompt.md?raw';+import businessOwnershipPrompt from './business-ownership-prompt.md?raw';import skillSourcePrecedencePrompt from './skill-source-precedence-prompt.md?raw';import { readCompactionPct } from './compaction-settings-store.js';import { readMemorySettings } from './memory-settings-store.js';@@ -39,7 +40,7 @@ import {// Claude / Codex 的 host system prompt:产品身份 → Skill 来源优先级 → agent 专属段。// Skill 优先级不放 host-system-prompt.md,避免把 #1645 的 Claude/Codex 行为扩到 Pi。function composeHostPrompt(agentSpecific: string): string {- return [hostSystemPrompt, skillSourcePrecedencePrompt, agentSpecific]+ return [hostSystemPrompt, businessOwnershipPrompt, skillSourcePrecedencePrompt, agentSpecific].map(s => s.trim()).filter(s => s.length > 0).join('\n\n');diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botProfileRuntime.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botProfileRuntime.test.tsindex 80f34b2f21..087241710a 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botProfileRuntime.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botProfileRuntime.test.ts@@ -11,6 +11,16 @@ import {withBotHomeAccess,} from '../botProfileRuntime';import { buildDefaultBotIdentity } from '../../../shared/botProfileDefaults';+import { buildBotMcpCatalog } from '../../maker-host/botMcpCatalog';++// Unit regression: default inheritance must retain engine connectors while an+// explicit allowlist can exclude them. Previously Apps was absent from the catalog.+it('resolves native Apps through the same Bot inheritance and selection rules', () => {+ const catalog = buildBotMcpCatalog({ agentKind: 'codex', providers: [], builtinNames: [], customServers: [] });+ expect(resolveBotMcpReferences({ configured: [], mode: 'inherit', catalog })).toEqual({ resolved: ['codex_apps'], unavailable: [] });+ expect(resolveBotMcpReferences({ configured: [], mode: 'allowlist', catalog })).toEqual({ resolved: [], unavailable: [] });+ expect(resolveBotMcpReferences({ configured: ['codex_apps'], mode: 'allowlist', catalog })).toEqual({ resolved: ['codex_apps'], unavailable: [] });+});describe('Bot Profile runtime prompt', () => {it('uses the SOUL source verbatim as the complete identity slot', () => {diff --git a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts b/apps/desktop/src/main/maker-ipc/botCapabilityService.tsindex 043d5f268b..0344e43fe0 100644--- a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts+++ b/apps/desktop/src/main/maker-ipc/botCapabilityService.ts@@ -150,6 +150,11 @@ async function catalog(input: Input, ctx: Pick<Awaited<ReturnType<typeof contextdescription: mcp.transport,available: available.has(mcp.id),}));+ items.push(...runtimeCatalog.filter((entry) => entry.source === 'harness').map((entry) => ({+ id: entry.name, name: entry.name,+ description: 'Engine-provided connectors; not Cindy tasks, routines or plugins.',+ available: entry.available !== false,+ })));} else {const registry = getPluginRegistry();items = await Promise.all(diff --git a/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts b/apps/desktop/src/main/maker-ipc/botProfileRuntime.tsindex ffde6d4205..d95a13f3f4 100644--- a/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts+++ b/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts@@ -28,6 +28,7 @@ import { PROVIDER_NAME_TO_PLUGIN_ID } from '../maker-host/plugins/builtin-pluginimport { normalizeBotToolCapabilities } from '../../shared/botCapabilitySelection.js';import { BOT_BASELINE_PLUGIN_IDS } from '../maker-host/plugins/types.js';import { BOT_IM_CHANNELS_VENDOR_KEY, type BotImChannel } from '../../shared/botImConnection.js';+import businessOwnershipPrompt from '../maker-host/business-ownership-prompt.md?raw';const log = createLogger('maker-ipc:bot-profile-runtime');@@ -43,7 +44,7 @@ interface BotSkillCatalogItem {interface BotMcpCatalogItem {name: string;- source: 'builtin' | 'custom';+ source: 'builtin' | 'custom' | 'harness';available?: boolean;generation?: string;}@@ -295,6 +296,7 @@ export function buildBotProfileContextPrompt(displayName: string): string {`Active Cindy Bot profile: ${name}.`,'Your name is the active profile name; your personality, role, and relationship with the user come from the current SOUL and user profile. Keep them consistent across replies, context compaction, restarts, and model changes. Do not reverse who is the boss or invent a relationship from habitual forms of address. Correct earlier replies that conflict with the current profile instead of treating them as identity facts.','The user is talking to this named teammate inside Cindy. Pi, Claude Code, and Codex are execution engines, not your personal identity or the user-facing application. Their native coding instructions describe how to use tools; they do not replace your profile. If asked about the engine or model, distinguish it from your identity and only state runtime facts you can verify.',+ businessOwnershipPrompt.trim(),'Use available host tools for model changes and verify their results before claiming a change. Connecting a new model or signing in to a provider is managed in Cindy settings. Do not present terminal-only slash commands such as /login or /model as commands available in this chat or assume the user is in a Pi terminal. When the exact Cindy entry is unknown, say so rather than inventing steps. When the user asks about a native CLI, explain which instructions belong to that terminal. This distinction does not restrict native tools, Pi package management, extensions, or self-repair.',].join('\n');}@@ -434,7 +436,7 @@ export function resolveBotMcpReferences(input: {}): { resolved: string[]; unavailable: string[] } {const available = new Set(input.catalog- .filter((item) => item.source === 'custom' && item.available !== false)+ .filter((item) => item.source !== 'builtin' && item.available !== false).map((item) => item.name),);if (input.mode === 'inherit') {diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/runtimePrompt.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/runtimePrompt.test.tsindex 3552c770c8..f25f1d8228 100644--- a/apps/desktop/src/main/plugin-oauth/__tests__/runtimePrompt.test.ts+++ b/apps/desktop/src/main/plugin-oauth/__tests__/runtimePrompt.test.ts@@ -1,6 +1,7 @@import { expect, it } from 'vitest';import { buildDesktopClaudeRuntimeConfig, desktopCodexRuntimeConfig } from '../../maker-host/runtime-configs.js';import hostPrompt from '../../maker-host/host-system-prompt.md?raw';+import ownership from '../../maker-host/business-ownership-prompt.md?raw';import precedence from '../../maker-host/skill-source-precedence-prompt.md?raw';import claudePrompt from '../../maker-host/claude-system-prompt.md?raw';import codexPrompt from '../../maker-host/codex-system-prompt.md?raw';@@ -11,7 +12,7 @@ it('keeps the upstream Desktop system prompt unchanged by remote authorization',[desktopCodexRuntimeConfig, codexPrompt],] as const;for (const [config, harnessPrompt] of cases) {- expect(config.systemPrompt).toBe([hostPrompt, precedence, harnessPrompt]+ expect(config.systemPrompt).toBe([hostPrompt, ownership, precedence, harnessPrompt].map(section => section.trim()).filter(Boolean).join('\n\n'));expect(config.systemPrompt).not.toContain('Plugin accounts and remote authorization');}diff --git a/docs/product-rules/agent-user-parity.md b/docs/product-rules/agent-user-parity.mdindex 2cac268502..c4025962d9 100644--- a/docs/product-rules/agent-user-parity.md+++ b/docs/product-rules/agent-user-parity.md@@ -59,6 +59,7 @@| 伙伴 | 发现伙伴、伙伴间消息 | 有 | 有 || 伙伴 | 自身关联项目:列出、添加与移除(原有文件工具按需读资料) | 有 | 无(远程设置界面可管理) || 伙伴 | 资料、能力、待办、后台任务 | 有 | 无 |+| 伙伴 | 发现与选择 Codex Apps 连接器(继承默认保留,显式 MCP 白名单可收窄) | 有(能力工具) | 无(SSH Codex 不提供) || 伙伴 | 按已证实归属搜索跨渠道聊天、按最近活动列出旧任务 | 有 | 有(历史查询,两端需支持筛选参数) || 伙伴 | 查看自己的本机 IM 连接分配与状态 | 有 | 无 || 伙伴 | 「一眼」投影(等你 / 在做;用户界面已改为近况,2026-10-21) | 有 | 无 |diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 503ca72db7..e704f0c27d 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -437,6 +437,20 @@ Mobile 使用电脑端已连接的模型目录;目录为空时保持创建禁## 6. Skill、工具与 MCP+Cindy 的任务、例行任务、自动化、插件与模型设置默认仍在 Cindy 中完成。执行引擎、订阅或+连接器来源不改变业务归属;只有用户明确指定其它应用时才转到该应用。工具切换及桌面/浏览器+操作应保留已选的应用、账号、执行主体和结果去向,并按回执核实。普通任务与伙伴复用+`business-ownership-prompt.md`,不把业务归属说明写进用户的 SOUL;这属于模型行为指引,+不是新增逐次审批或桌面应用封锁。++Codex 原生 `codex_apps` 纳入伙伴 MCP 元数据目录,来源标为 `harness`。默认继承时保留原生+开关,不强制开启连接或授权;显式白名单未选择时只在该线程设置 `features.apps=false`,+不构造无 transport 的 MCP 配置。当前任务通过 `get_capabilities(scope=runtime)` 发现它,+指定 server 后读取该线程的真实工具状态;引擎工具目录每页最多 50 项,支持 `toolQuery`+筛选与 `nextOffset` / `offset` 翻页,避免全量 Apps 工具灌满上下文。伙伴能力工具可发现、加入或移除该项;现有自定义+MCP 设置列表仍只管理用户配置的 transport,不把原生 Apps 伪装成可编辑地址的自定义服务。+SSH Codex 不提供这项本机原生能力,目录如实标为不可用。+轻量不等于没有 Skill。伙伴启动时按以下优先级构造能力:1. 伙伴家目录中的自有 / 后学 Skill;diff --git a/packages/lizi-mcps/src/__tests__/getCapabilitiesTool.test.ts b/packages/lizi-mcps/src/__tests__/getCapabilitiesTool.test.tsindex ad0695a38c..71e542bc67 100644--- a/packages/lizi-mcps/src/__tests__/getCapabilitiesTool.test.ts+++ b/packages/lizi-mcps/src/__tests__/getCapabilitiesTool.test.ts@@ -115,6 +115,19 @@ describe('capabilities data source', () => {});describe('get_capabilities tool', () => {+ // Unit protocol regression: the public MCP schema must forward the page/filter+ // rather than silently stripping them and returning the same oversized page.+ it('forwards runtime tool search and pagination through the actual MCP entry', async () => {+ const read = vi.fn(async (_ctx: unknown, query: unknown) => ({ ok: true, query, tools: [{ name: 'matching_tool' }] }));+ const h = await connect(createXdtHelperMcpServer({ logger: makeLogger(), runtimeCapabilities: read }, sessionCtx));+ try {+ const result = parsePayload(await h.client.callTool({ name: 'call_tool', arguments: {+ name: 'get_capabilities', args: { scope: 'runtime', server: 'codex_apps', toolQuery: 'github', offset: 50 },+ } }));+ expect(result).toMatchObject({ ok: true, query: { server: 'codex_apps', toolQuery: 'github', offset: 50 }, tools: [{ name: 'matching_tool' }] });+ } finally { await h.cleanup(); }+ });+it('不传 key 时返回包含 about-cindy 的索引', async () => {const h = await connect(createXdtHelperMcpServer({ logger: makeLogger() }, sessionCtx));try {diff --git a/packages/lizi-mcps/src/xdt-helper/get_capabilities.ts b/packages/lizi-mcps/src/xdt-helper/get_capabilities.tsindex 292e023ab5..dba42e2b66 100644--- a/packages/lizi-mcps/src/xdt-helper/get_capabilities.ts+++ b/packages/lizi-mcps/src/xdt-helper/get_capabilities.ts@@ -15,7 +15,7 @@ import { z } from 'zod';import { findCapability, listCapabilityIndex } from './capabilities.js';import type { XdtHelperToolRegistry } from '../lizi_xdtHelperToolRegistry.js';-export interface RuntimeCapabilityQuery { server?: string; category?: string; }+export interface RuntimeCapabilityQuery { server?: string; category?: string; toolQuery?: string; offset?: number; }export type RuntimeCapabilityReader = (query: RuntimeCapabilityQuery) => Promise<unknown>;export function registerGetCapabilitiesTool(registry: XdtHelperToolRegistry, readRuntime?: RuntimeCapabilityReader): void {@@ -32,14 +32,16 @@ export function registerGetCapabilitiesTool(registry: XdtHelperToolRegistry, reascope: z.enum(['product', 'runtime']).optional().describe('product 查询产品介绍;runtime 查询实际注册与启用状态。'),server: z.string().optional().describe('从 runtime 目录返回的 server 标识。'),category: z.string().optional().describe('该 server 的 list_tools 返回的类目。'),+ toolQuery: z.string().trim().max(200).optional().describe('引擎管理的 MCP 工具按名称或说明筛选;每页最多 50 项。'),+ offset: z.number().int().min(0).max(100_000).optional().describe('引擎工具目录的分页起点,沿用同一 server 和 toolQuery,传上页 nextOffset。'),key: z.string().optional().describe('能力 key(从不传参的索引返回中获取)。不传 = 返回索引列表。'),},- handler: async ({ key, scope, server, category }) => {+ handler: async ({ key, scope, server, category, toolQuery, offset }) => {if (scope === 'runtime') {- const result = readRuntime ? await readRuntime({ server, category })+ const result = readRuntime ? await readRuntime({ server, category, ...(toolQuery !== undefined ? { toolQuery } : {}), ...(offset !== undefined ? { offset } : {}) }): { ok: false, errorCode: 'RUNTIME_CATALOG_UNAVAILABLE', message: '当前宿主尚未提供运行能力目录。' };return { content: [{ type: 'text' as const, text: JSON.stringify(result) }] };}diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex 28b0be7cbb..bd53522066 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -1728,7 +1728,7 @@ export interface BotRuntimeSkillPolicy {export interface BotRuntimeMcpEntry {name: string;- source: 'builtin' | 'custom';+ source: 'builtin' | 'custom' | 'harness';available?: boolean;}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.tsnew file mode 100644index 0000000000..e2e17fbd1b--- /dev/null+++ b/packages/maker-core/src/agents/codex/bot-mcp-policy.integration.test.ts@@ -0,0 +1,131 @@+import { mkdtemp, mkdir, rm } from 'node:fs/promises';+import { createServer } from 'node:http';+import type { AddressInfo } from 'node:net';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { expect, it } from 'vitest';+import { CodexAgent } from './index.js';+import type { AgentSessionHandle, AgentMcpServerToolsReport } from '../base-agent.js';+import type { Logger } from '../../interfaces/logger.js';++// Integration tier: real native process and loopback MCP/Responses fixtures, no account.+// Units cannot prove that Codex accepts the feature-only Apps restriction or that+// the thread actually exposes only the selected external transport.+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) => {+ const root = await mkdtemp(path.join(tmpdir(), 'cindy-bot-mcp-native-'));+ const home = path.join(root, 'codex');+ const workingDir = path.join(root, 'work');+ await mkdir(home);+ await mkdir(workingDir);+ const requests: Record<string, unknown>[] = [];+ let activeHandle: AgentSessionHandle | undefined;+ let duringToolReport: AgentMcpServerToolsReport | null | undefined;+ let duringToolError: unknown;+ const server = createServer(async (req, res) => {+ let body = '';+ for await (const chunk of req) body += chunk;+ if (req.method !== 'POST') { res.writeHead(405).end(); return; }+ const message = JSON.parse(body);+ if (req.url === '/responses') {+ requests.push(message);+ const item = requests.length === 1+ ? { type: 'custom_tool_call', id: 'fc', call_id: 'call', name: 'exec', input: 'text(await tools.mcp__cindy_helper__routine_list({}));' }+ : { type: 'message', role: 'assistant', id: 'msg', content: [{ type: 'output_text', text: 'fixture complete' }] };+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'close' });+ res.end([+ { type: 'response.created', response: { id: 'resp' } },+ { type: 'response.output_item.done', item },+ { type: 'response.completed', response: { id: 'resp', usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 } } },+ ].map(event => `data: ${JSON.stringify(event)}\n\n`).join(''));+ return;+ }+ if (message.id === undefined) { res.writeHead(202).end(); return; }+ if (message.method === 'tools/call') {+ try { duringToolReport = await activeHandle?.readMcpServerTools?.('fixture_external'); }+ catch (error) { duringToolError = error; }+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: { content: [{ type: 'text', text: 'local read complete' }] } }));+ return;+ }+ const result = message.method === 'initialize'+ ? { protocolVersion: '2024-11-05', capabilities: { tools: {} }, serverInfo: { name: 'local-fixture', version: '1' } }+ : message.method === 'tools/list'+ ? { tools: [{ name: req.url === '/helper' ? 'routine_list' : 'external_echo', description: 'Read-only local fixture', inputSchema: { type: 'object', properties: {} } }] }+ : {};+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ jsonrpc: '2.0', id: message.id, result }));+ });+ let agent: CodexAgent | undefined;+ try {+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));+ const endpoint = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+ agent = new CodexAgent({+ binaryPath: binaryPath!, logger, runtimeConfig: {},+ prepareCodexExtraSpawnConfig: async () => ({ extraArgs: [+ '-c', 'model_provider="fixture"',+ '-c', `model_providers.fixture={name="Local validation",base_url="${endpoint}",wire_api="responses",requires_openai_auth=false,supports_websockets=false}`,+ '-c', 'check_for_update_on_startup=false', '-c', 'analytics.enabled=false',+ '-c', 'features.plugins=false', '-c', 'features.remote_plugin=false',+ '-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"}`,+ ], extraEnv: {} }),+ auth: {+ getState: async () => ({ authenticated: true }), triggerLogin: async () => ({ authenticated: true }), logout: async () => {},+ getAuthEnv: async () => ({ HOME: root, USERPROFILE: root, CODEX_HOME: home, OPENAI_API_KEY: '', CODEX_API_KEY: '', NO_PROXY: '127.0.0.1,localhost' }),+ },+ });+ const handle = await agent.startSession({+ sessionId: `mcp-fixture-${external}`, model: 'gpt-6-astra', workingDir,+ permissionMode: 'bypassPermissions', makerMemoryEnabled: false,+ botProfilePrompt: 'You are a test teammate inside Cindy.',+ botRuntimeProfile: {+ botId: 'fixture', profileVersion: 1,+ skillPolicy: { mode: 'allowlist', configured: [], catalog: [] },+ toolsetPolicy: { mode: 'allowlist', configured: [], catalog: [] },+ mcpPolicy: { mode: 'allowlist', configured: external ? ['fixture_external', 'codex_apps'] : [], catalog: [+ { name: 'cindy_helper', source: 'builtin' },+ { name: 'fixture_external', source: 'custom' },+ { name: 'codex_apps', source: 'harness' },+ ] },+ },+ });+ activeHandle = handle;+ try {+ const events = (async () => {+ for await (const event of handle.events()) {+ if (event.type === 'error') throw new Error(JSON.stringify(event));+ if (event.type === 'done') return;+ }+ })();+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ await Promise.race([+ (async () => {+ await handle.send({ type: 'user', content: 'Inspect the available tools; do not create automation.' }, { throwOnStartFailure: true });+ await events;+ })(),+ new Promise<never>((_, reject) => {+ // real-wait: native process failure deadline; cleanup must run before Vitest times out.+ timer = setTimeout(() => reject(new Error('Native fixture turn timed out')), 20_000);+ }),+ ]);+ } finally { clearTimeout(timer); }+ expect(requests).toHaveLength(2);+ expect(duringToolError).toBeUndefined();+ expect(duringToolReport?.tools.map(tool => tool.name)).toEqual(external ? ['external_echo'] : []);+ expect(await handle.readMcpServerTools?.('cindy_helper')).toMatchObject({ state: 'connected', tools: [{ name: 'routine_list' }] });+ const report = await handle.readMcpServerTools?.('fixture_external');+ if (external) expect(report).toMatchObject({ state: 'connected', tools: [{ name: 'external_echo' }] });+ else expect(report?.tools).toEqual([]);+ } finally { await handle.close(); }+ } finally {+ await agent?.dispose();+ server.closeAllConnections();+ await new Promise<void>(resolve => server.close(() => resolve()));+ await rm(root, { recursive: true, force: true });+ }+}, 30_000);diff --git a/packages/maker-core/src/agents/codex/capability-routing.test.ts b/packages/maker-core/src/agents/codex/capability-routing.test.tsindex b3c1bf299d..33599b7fde 100644--- a/packages/maker-core/src/agents/codex/capability-routing.test.ts+++ b/packages/maker-core/src/agents/codex/capability-routing.test.ts@@ -133,6 +133,7 @@ describe('Bot MCP config', () => {{ name: 'custom.with.dot', source: 'custom' },],}, new Set(['cindy_memory', 'cindy_helper', 'cindy', 'cindy_group_history', 'cindy_orca', 'custom-a', 'custom.with.dot']))).toEqual({+ 'features.apps': false,'mcp_servers.cindy_group_history.enabled': false,'mcp_servers.cindy_orca.enabled': false,'mcp_servers."custom.with.dot".enabled': false,@@ -140,7 +141,7 @@ describe('Bot MCP config', () => {});it('does not manufacture invalid disabled-only transport entries', () => {- expect(buildCodexBotMcpConfigOverrides({ mode: 'allowlist', configured: [], catalog: [{ name: 'cindy_contacts', source: 'builtin' }] }, new Set())).toEqual({});+ expect(buildCodexBotMcpConfigOverrides({ mode: 'allowlist', configured: [], catalog: [{ name: 'cindy_contacts', source: 'builtin' }] }, new Set())).toEqual({ 'features.apps': false });});it('keeps an explicitly configured builtin capability server enabled', () => {@@ -156,11 +157,23 @@ describe('Bot MCP config', () => {{ name: 'cindy_scheduler', source: 'builtin' },],}, new Set(['cindy_memory', 'cindy_helper', 'cindy_docs', 'cindy_scheduler', 'cindy', 'cindy_group_history', 'cindy_orca', 'cindy_docs']))).toEqual({+ 'features.apps': false,'mcp_servers.cindy_scheduler.enabled': false,'mcp_servers.cindy_group_history.enabled': false,'mcp_servers.cindy_orca.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 });+ expect(buildCodexBotMcpConfigOverrides(undefined, new Set())).toEqual({});+ expect(buildCodexBotMcpConfigOverrides({ mode: 'inherit', configured: [], catalog: [] }, new Set())).toEqual({});+ });});describe('buildCodexSessionCapabilityRoutingPolicy', () => {diff --git a/packages/maker-core/src/agents/codex/capability-routing.ts b/packages/maker-core/src/agents/codex/capability-routing.tsindex de9fe45758..6fe3a8d9b5 100644--- a/packages/maker-core/src/agents/codex/capability-routing.ts+++ b/packages/maker-core/src/agents/codex/capability-routing.ts@@ -87,9 +87,13 @@ export function buildCodexBotMcpConfigOverrides(): Record<string, unknown> {if (!policy || policy.mode !== 'allowlist') return {};const result: Record<string, unknown> = {};+ // Apps is a native server without command/url. A disabled-only MCP entry is+ // invalid in Codex; use its feature switch, and never force-enable an account feature.+ if (!isBotMcpServerAllowed(policy, 'codex_apps')) result['features.apps'] = false;// 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;const restricted = ['cindy_group_history', 'cindy_orca'].includes(name);if (!restricted && isBotMcpServerAllowed(policy, name)) continue;result[`mcp_servers.${renderThreadConfigKeySegment(name)}.enabled`] = false;diff --git a/packages/maker-core/src/interfaces/mcp-provider.ts b/packages/maker-core/src/interfaces/mcp-provider.tsindex a7e94dbf35..766ea69284 100644--- a/packages/maker-core/src/interfaces/mcp-provider.ts+++ b/packages/maker-core/src/interfaces/mcp-provider.ts@@ -70,7 +70,7 @@ export interface McpProvider {capability?: {title: string;description: string;- source: 'builtin' | 'plugin' | 'custom';+ source: 'builtin' | 'plugin' | 'custom' | 'harness';discovery?: { tool: string; args?: Record<string, unknown> };};/** 按 session 上下文决定是否启用,例如飞书 bot MCP 只给 source='feishu' 会话。 */