Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
refactor(agent): 统一能力声明与权限,伙伴默认继承全部可用工具 (#5382)
Chris Zhangfaeedf0dc772
diff --git a/apps/desktop/src/main/bot-import/host.ts b/apps/desktop/src/main/bot-import/host.tsindex ae4c425227..0fc07779a1 100644--- a/apps/desktop/src/main/bot-import/host.ts+++ b/apps/desktop/src/main/bot-import/host.ts@@ -1,3 +1,4 @@+import { normalizeBotToolCapabilities } from '../../shared/botCapabilitySelection.js';import { companionImportReasonKey } from '@cindy/maker-shared/companion-import';import { createMessage } from '../localDb/ipc/messages.js';import { t } from '../i18n.js';@@ -586,7 +587,7 @@ export async function startCompanionImport(selection: CompanionImportSelection,}if (!baseline || Object.keys(patch).length) {await writeBotProfileFolder(scope.root, botId, {- config: baseline ? folder.config : { ...folder.config, mcpMode: 'allowlist', mcpServers: [...new Set([+ config: baseline ? folder.config : { ...normalizeBotToolCapabilities(folder.config), mcpServers: [...new Set([...(Array.isArray(folder.config.mcpServers) ? folder.config.mcpServers : []), 'companion_connections',])] }, ...patch,}); scope.assert();diff --git a/apps/desktop/src/main/bot-import/importProvider.ts b/apps/desktop/src/main/bot-import/importProvider.tsindex c1ceee7f58..0d552ca984 100644--- a/apps/desktop/src/main/bot-import/importProvider.ts+++ b/apps/desktop/src/main/bot-import/importProvider.ts@@ -25,7 +25,7 @@ export function createCompanionImportProvider(): McpProvider {const [shared] = await db.select({ id: sharedTaskEvents.id }).from(sharedTaskEvents).where(eq(sharedTaskEvents.sessionId, session.sessionId)).limit(1);// Local account migration is an owner operation. Guest/IM/SSH tasks cannot// use an ambient desktop login to discover or import this computer's credentials.- if (!task || task.source !== 'desktop' || task.status !== 'active' || task.remoteHostId || shared || isAppSessionBoundaryPending() || owner !== activeOwnerScopeKey()) throw new CompanionImportError('IMPORT_CALLER_UNAVAILABLE');+ if (!task || !['desktop', 'bot'].includes(task.source ?? '') || task.status !== 'active' || task.remoteHostId || shared || isAppSessionBoundaryPending() || owner !== activeOwnerScopeKey()) throw new CompanionImportError('IMPORT_CALLER_UNAVAILABLE');const result = input.operation === 'sources' ? await listCompanionImportSources(controller): input.operation === 'preview' && input.sourceId ? await previewCompanionImport(input.sourceId, controller)// Length-2 arrays are re-checked as [first, last] pairs by validateImportSelection.diff --git a/apps/desktop/src/main/localDb/__tests__/taskTags.test.ts b/apps/desktop/src/main/localDb/__tests__/taskTags.test.tsindex 211aa29b77..de1df7fd05 100644--- a/apps/desktop/src/main/localDb/__tests__/taskTags.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/taskTags.test.ts@@ -159,23 +159,12 @@ describe('task labels transactions', () => {run({ action: 'update', tagId: 'default:red', revision: 1, color: 'blue' }),).toThrow('CONFLICT');});- it('denies missing and bot callers at the write transaction boundary', () => {- expect(() =>- run({ action: 'create', newId: 'x', name: 'Work', color: 'red', callerSessionId: 'missing' }),- ).toThrow('NOT_FOUND');- db.exec("INSERT INTO bot_session_links VALUES('a')");- expect(() => run({ action: 'list', callerSessionId: 'a' })).toThrow('NOT_FOUND');- });- it('accepts a trusted Bot caller only from an active canonical Bot main task', () => {- db.exec(- "ALTER TABLE bot_session_links ADD COLUMN role TEXT; ALTER TABLE bot_session_links ADD COLUMN archived_at INTEGER;"- + " INSERT INTO sessions(id,source) VALUES('bot-main','bot'),('bot-lane','bot');"- + " INSERT INTO bot_session_links(session_id,role) VALUES('bot-main','canonical'),('bot-lane','group');",- );- expect(() => run({ action: 'list', callerSessionId: 'bot-main' })).toThrow('NOT_FOUND');- expect(run({ action: 'list', callerSessionId: 'bot-main', callerIsTrustedBot: true }).tags.length).toBeGreaterThan(0);- expect(() => run({ action: 'list', callerSessionId: 'bot-lane', callerIsTrustedBot: true })).toThrow('NOT_FOUND');- expect(() => run({ action: 'list', callerSessionId: 'a', callerIsTrustedBot: true })).toThrow('NOT_FOUND');+ it('rejects missing callers and accepts ordinary and companion callers equally', () => {+ expect(() => run({ action: 'list', callerSessionId: 'missing' })).toThrow('NOT_FOUND');+ db.exec("INSERT INTO sessions(id,source) VALUES('bot-main','bot'),('bot-lane','bot')");+ for (const callerSessionId of ['a', 'bot-main', 'bot-lane']) {+ expect(run({ action: 'list', callerSessionId }).tags.length).toBeGreaterThan(0);+ }});it('persists order across edits and projects it onto task associations', () => {const expectedOrder = run({ action: 'list' }).tags.map((t) => t.id);diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex 2cac404782..bfbe82785e 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -667,11 +667,22 @@ describe('Bot canonical Session lifecycle', () => {providerId: 'xd',effort: 'high',});+ expect(capabilities).toMatchObject({ toolCapabilityVersion: 1, toolsetMode: 'inherit', mcpMode: 'inherit' });expect(capabilities.skills).toEqual([]);expect(capabilities.toolsets).toEqual([]);expect(capabilities.mcpServers).toEqual([]);});+ it('preserves explicit creation selections under the new capability contract', async () => {+ const created = await invoke('local-db:bots:create', {+ id: 'selected-bot', name: 'Selected Bot',+ capabilities: { toolsetMode: 'allowlist', toolsets: [], permissions: 'ask' },+ });+ expect(created.capabilities).toMatchObject({ toolsetMode: 'allowlist', toolsets: [], mcpMode: 'inherit', permissions: 'ask' });+ const row = h.sqlite!.prepare('SELECT capabilities_json FROM bot_profile_versions WHERE bot_id = ? AND version = 1').get('selected-bot') as { capabilities_json: string };+ expect(JSON.parse(row.capabilities_json)).toMatchObject({ toolCapabilityVersion: 1, toolsetMode: 'allowlist' });+ });+it('persists only bounded welcome hints, not caller-supplied progress or profile identity', async () => {const created = await invoke('local-db:bots:create', {id: 'bot-context', name: 'Context Bot', prepareInvitation: true,@@ -1822,7 +1833,7 @@ describe('Bot canonical Session lifecycle', () => {expect(opts.botProfileContextPrompt).toContain('ghost_call');});- it('keeps ambient catalogs only as explicit disabled rows under legacy inherit', async () => {+ it('inherits MCP and tools while preserving the companion Skill selection', async () => {const created = await invoke('local-db:bots:create-canonical-session', {botId: 'bot-1',expectedCanonicalSessionId: null,@@ -1869,8 +1880,44 @@ describe('Bot canonical Session lifecycle', () => {configured: [],catalog: [expect.objectContaining({ name: 'research' })],},- mcpPolicy: { mode: 'allowlist', configured: [] },- toolsetPolicy: { mode: 'allowlist', configured: [] },+ mcpPolicy: { mode: 'allowlist', configured: ['docs'] },+ toolsetPolicy: { mode: 'allowlist', configured: ['browser'] },+ });+ });++ it.each([+ { versioned: false, selected: true, mode: 'inherit', expectedMcp: ['docs', 'mail'], expectedTools: ['browser', 'contacts'] },+ { versioned: false, selected: false, mode: 'inherit', expectedMcp: ['docs', 'mail'], expectedTools: ['browser', 'contacts'] },+ { versioned: true, selected: false, mode: 'allowlist', expectedMcp: [], expectedTools: [] },+ { versioned: true, selected: true, mode: 'allowlist', expectedMcp: ['docs'], expectedTools: ['browser'] },+ ])('keeps stored capability selections consistent in settings and runtime: %j', async (entry) => {+ const row = h.sqlite!.prepare('SELECT capabilities_json FROM bot_profile_versions WHERE bot_id = ? AND version = 1')+ .get('bot-1') as { capabilities_json: string };+ const config = { ...JSON.parse(row.capabilities_json),+ toolsetMode: 'allowlist', toolsets: entry.selected ? ['browser'] : [],+ mcpMode: 'allowlist', mcpServers: entry.selected ? ['docs'] : [],+ };+ if (entry.versioned) config.toolCapabilityVersion = 1;+ else delete config.toolCapabilityVersion;+ h.sqlite!.prepare('UPDATE bot_profile_versions SET capabilities_json = ? WHERE bot_id = ? AND version = 1')+ .run(JSON.stringify(config), 'bot-1');+ const loaded = await invoke('local-db:bots:get', 'bot-1');+ expect(loaded.capabilities).toMatchObject({ toolsetMode: entry.mode, mcpMode: entry.mode });+ const created = await invoke('local-db:bots:create-canonical-session', {+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1,+ });+ const opts: MakerSessionCreateOpts = {+ id: created.session.id, agentKind: 'pi', workingDir: created.session.workingDir,+ workspaceKind: 'dialogue', model: 'grok-4.5', permissionMode: 'ask',+ };+ await hydrateBotProfileRuntime(opts, {+ listSkills: async () => [],+ listMcpServers: async () => ['docs', 'mail'].map(name => ({ name, source: 'custom', available: true })),+ listToolsets: async () => ['browser', 'contacts'].map(id => ({ id, name: id, available: true })),+ });+ expect(opts.botRuntimeProfile).toMatchObject({+ mcpPolicy: { mode: 'allowlist', configured: entry.expectedMcp },+ toolsetPolicy: { mode: 'allowlist', configured: entry.expectedTools },});});@@ -2225,7 +2272,7 @@ describe('Bot canonical Session lifecycle', () => {const created = await invoke('local-db:bots:create-canonical-session', { botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1 });const callerSessionId = created.session.id;const discovered = await findBotCapabilities({ callerSessionId, kind: 'mcp' });- expect(discovered).toMatchObject({ ok: true, capabilities: [{ id: 'shared-docs', joined: false, available: true }] });+ expect(discovered).toMatchObject({ ok: true, capabilities: [{ id: 'shared-docs', joined: true, available: true }] });expect(JSON.stringify(discovered)).not.toMatch(/FAKE_SECRET|example.invalid|Authorization/);await expect(selectBotCapability({ callerSessionId, kind: 'mcp', id: 'shared-docs', joined: true })).resolves.toMatchObject({ ok: true, effective: 'next-turn' });await expect(findBotCapabilities({ callerSessionId, kind: 'mcp' })).resolves.toMatchObject({ capabilities: [{ id: 'shared-docs', joined: true }] });@@ -2414,7 +2461,7 @@ describe('Bot canonical Session lifecycle', () => {});it.each(['missing', 'error', 'owner-change'])('does not use the current route when next-turn preview fails: %s', async (reason) => {- await invoke('local-db:bots:update', { id: 'bot-1', capabilities: { mcpServers: ['shared-docs'] } });+ await invoke('local-db:bots:update', { id: 'bot-1', capabilities: { mcpServers: ['shared-docs'], mcpMode: 'allowlist' } });const created = await invoke('local-db:bots:create-canonical-session', {botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 2,});@@ -2598,7 +2645,7 @@ describe('Bot canonical Session lifecycle', () => {.resolves.toMatchObject({ ok: true, joined: false });});- it.each(['contacts', 'lsp'])('rejects gated %s despite registry enablement and keeps joined references removable', async (id) => {+ it.each(['contacts'])('rejects gated %s despite registry enablement and keeps joined references removable', async (id) => {const created = await invoke('local-db:bots:create-canonical-session', { botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1 });const input = { callerSessionId: created.session.id, kind: 'toolset' as const, id };await expect(findBotCapabilities(input)).resolves.toMatchObject({diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botProfileVersioning.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botProfileVersioning.test.tsindex 2cbac61be8..d042cbd101 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botProfileVersioning.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botProfileVersioning.test.ts@@ -41,6 +41,7 @@ describe('Bot Profile versioning', () => {).toEqual({model: 'new-model',memory: false,+ toolCapabilityVersion: 1, toolsetMode: 'inherit', mcpMode: 'inherit',skills: ['new-skill', 'second-skill'],});});@@ -130,3 +131,38 @@ describe('independent task model configuration', () => {expect(() => normalizeBotProfileModelChain({ taskModelOverride })).toThrow();});});+++describe('shared tools migration', () => {+ it.each(['ask', 'auto', 'trusted'])('opens legacy lists without changing %s permissions', (permissions) => {+ const previous = { permissions, toolsetMode: 'allowlist', toolsets: [], mcpMode: 'allowlist', mcpServers: ['imported'], memory: false };+ const next = mergeBotProfileCapabilities({ previous, hasSkills: false });+ expect(next).toMatchObject({ toolCapabilityVersion: 1, toolsetMode: 'inherit', mcpMode: 'inherit', permissions, memory: false, mcpServers: ['imported'] });+ expect(mergeBotProfileCapabilities({ previous: next, hasSkills: false })).toEqual(next);+ });++ it.each([+ [{ toolsetMode: 'allowlist', toolsets: ['browser'], mcpMode: 'allowlist', mcpServers: [] }, 'inherit', 'inherit'],+ [{ toolsetMode: 'allowlist', toolsets: ['docs'], mcpMode: 'allowlist', mcpServers: ['private'] }, 'inherit', 'inherit'],+ [{ toolsets: ['docs'], mcpServers: ['private'] }, 'inherit', 'inherit'],+ [{ toolsetMode: 'inherit', toolsets: ['docs'], mcpMode: 'inherit', mcpServers: ['private'] }, 'inherit', 'inherit'],+ [{ tools: ['files', 'browser', 'mcp'] }, 'inherit', 'inherit'],+ [{ mcpMode: 'allowlist', mcpServers: ['companion_connections'] }, 'inherit', 'inherit'],+ [{ toolCapabilityVersion: 1, toolsetMode: 'allowlist', toolsets: [], mcpMode: 'allowlist', mcpServers: [] }, 'allowlist', 'allowlist'],+ [{ toolCapabilityVersion: 1, toolsetMode: 'allowlist', toolsets: ['docs'], mcpMode: 'allowlist', mcpServers: ['private'] }, 'allowlist', 'allowlist'],+ ] as const)('migrates legacy lists and preserves versioned choices: %j', (previous, toolsetMode, mcpMode) => {+ const next = mergeBotProfileCapabilities({ previous, hasSkills: false });+ expect(next).toEqual({ ...previous, toolCapabilityVersion: 1, toolsetMode, mcpMode });+ expect(mergeBotProfileCapabilities({ previous: next, hasSkills: false })).toEqual(next);+ });++ it('persists an explicit selection after migration and preserves concurrent selections', () => {+ const next = mergeBotProfileCapabilities({+ previous: { toolCapabilityVersion: 1, toolsetMode: 'inherit', toolsets: [] },+ capabilities: { toolsetMode: 'allowlist', toolsets: ['docs'] },+ capabilityBaseline: { toolsets: [] }, hasSkills: false,+ });+ expect(mergeBotProfileCapabilities({ previous: next, hasSkills: false }))+ .toMatchObject({ toolsetMode: 'allowlist', toolsets: ['docs'], mcpMode: 'inherit' });+ });+});diff --git a/apps/desktop/src/main/localDb/ipc/botProfileVersioning.ts b/apps/desktop/src/main/localDb/ipc/botProfileVersioning.tsindex 2a9d92fb63..45d6d939cb 100644--- a/apps/desktop/src/main/localDb/ipc/botProfileVersioning.ts+++ b/apps/desktop/src/main/localDb/ipc/botProfileVersioning.ts@@ -1,5 +1,5 @@import { normalizeBotModelChain, readBotTaskModelOverride } from '../../../shared/botModelChain.js';-import { reconcileBotCapabilityList } from '../../../shared/botCapabilitySelection.js';+import { normalizeBotToolCapabilities, reconcileBotCapabilityList } from '../../../shared/botCapabilitySelection.js';import { throwIpcError } from '../../utils/ipcValidate.js';export function botProfileContentChanged(input: {@@ -27,9 +27,10 @@ export function mergeBotProfileCapabilities(input: {hasSkills: boolean;capabilityBaseline?: unknown;}): Record<string, unknown> {+ const previous = normalizeBotToolCapabilities(input.previous);const next = input.capabilities- ? { ...input.previous, ...input.capabilities }- : { ...input.previous };+ ? { ...previous, ...input.capabilities }+ : { ...previous };if (input.hasSkills) {next.skills = Array.isArray(input.skills)? input.skillsdiff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.tsindex 4ddf1e6e90..b02a0c63cd 100644--- a/apps/desktop/src/main/localDb/ipc/bots.ts+++ b/apps/desktop/src/main/localDb/ipc/bots.ts@@ -44,6 +44,7 @@ import {writeBotModelChainSettings,} from '../../maker-host/bot-model-chain-settings-store.js';import { extractMessagePreview, sessionCreateToRow, sessionToCamel } from '../mapper.js';+import { normalizeBotToolCapabilities } from '../../../shared/botCapabilitySelection.js';import {botProfileContentChanged,botProfileModelSelectionChanged,@@ -886,11 +887,11 @@ async function readProfile(skillsExcluded: Array.isArray(config.skillsExcluded)? config.skillsExcluded.filter((item): item is string => typeof item === 'string'): [],- toolsetMode: 'allowlist',+ toolsetMode: normalizeBotToolCapabilities(config).toolsetMode,toolsets: Array.isArray(config.toolsets)? config.toolsets.filter((item): item is string => typeof item === 'string'): [],- mcpMode: 'allowlist',+ mcpMode: normalizeBotToolCapabilities(config).mcpMode,mcpServers: Array.isArray(config.mcpServers)? config.mcpServers.filter((item): item is string => typeof item === 'string'): [],@@ -1184,9 +1185,10 @@ async function defaultNewBotCapabilities(): Promise<Record<string, unknown>> {modelChainOverride: null,skillMode: 'allowlist',skillsExcluded: [],- toolsetMode: 'allowlist',+ toolCapabilityVersion: 1,+ toolsetMode: 'inherit',toolsets: [],- mcpMode: 'allowlist',+ mcpMode: 'inherit',mcpServers: [],memory: true,permissions: 'auto',@@ -1336,10 +1338,13 @@ export async function createBotProfile(raw: unknown) {}const persistedCapabilities = normalizeBotModelCapabilitiesOrThrow({permissions: 'auto',+ toolsetMode: 'inherit',+ mcpMode: 'inherit',...(hasRequestedCapabilities ? {} : await defaultNewBotCapabilities()),...requestedCapabilities,+ toolCapabilityVersion: 1,skills,- ...(draftEntry ? { skillMode: 'allowlist', mcpMode: 'allowlist', mcpServers: draftEntry.draft.mcpRefs, toolsetMode: 'allowlist', toolsets: draftEntry.draft.toolsetRefs } : {}),+ ...(draftEntry ? { skillMode: 'allowlist', mcpMode: 'inherit', mcpServers: draftEntry.draft.mcpRefs, toolsetMode: 'inherit', toolsets: draftEntry.draft.toolsetRefs } : {}),userContextSource,...(gender ? { gender } : {}),});diff --git a/apps/desktop/src/main/localDb/ipc/taskTags.ts b/apps/desktop/src/main/localDb/ipc/taskTags.tsindex 0f957f9205..7549d0c1c8 100644--- a/apps/desktop/src/main/localDb/ipc/taskTags.ts+++ b/apps/desktop/src/main/localDb/ipc/taskTags.ts@@ -18,14 +18,10 @@ const log = createLogger('taskTags');export const TASK_TAG_CHANNEL = 'local-db:task-tags:execute';/*** All surfaces share validation, transactions and owner-scoped task patches.- * `trustedBotOwnerTurn`: the caller is a Bot main task on its owner's own turn- * (decided by the host, maker-ipc/botTurnAuthority.ts); Bot sessions themselves- * still cannot be tagged.*/export async function executeTaskTags(request: TaskTagRequest,callerSessionId?: string,- options: { trustedBotOwnerTurn?: boolean } = {},): Promise<TaskTagResult> {const scope = captureDataOwnerBroadcastScope();const assertCurrent = () => {@@ -50,7 +46,6 @@ export async function executeTaskTags(...request,newId: preset?.id ?? randomUUID(),callerSessionId,- ...(callerSessionId && options.trustedBotOwnerTurn ? { callerIsTrustedBot: true } : {}),});assertCurrent();if (['create', 'update', 'delete', 'attach', 'detach'].includes(request.action)) {diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/taskTagsTx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/taskTagsTx.tsindex a8581bc2eb..e30ebfe6a8 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/taskTagsTx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/taskTagsTx.ts@@ -6,7 +6,7 @@ export function runTaskTagsTransaction(db: Database.Database, raw: unknown): Tasconst fail = (code: string): never => {throw new Error(`[${code}] Task tag operation failed`);};- const body = raw as TaskTagRequest & { newId?: string; callerSessionId?: string; callerIsTrustedBot?: boolean };+ const body = raw as TaskTagRequest & { newId?: string; callerSessionId?: string };const text = (value: unknown, max = 128): string => {if (typeof value !== 'string' || !value.trim() || value.trim().length > max)return fail('INVALID_PARAMS');@@ -76,26 +76,9 @@ export function runTaskTagsTransaction(db: Database.Database, raw: unknown): Tas}));return db.transaction(() => {if (!body || typeof body !== 'object') return fail('INVALID_PARAMS');- if (body.callerSessionId && body.callerIsTrustedBot) {- // The host already decided this is a Bot main task on its owner's own turn.- if (- !db- .prepare(- "SELECT s.id FROM sessions s JOIN bot_session_links b ON b.session_id=s.id WHERE s.id=? AND s.status='active' AND s.source='bot' AND b.role='canonical' AND b.archived_at IS NULL",- )- .get(body.callerSessionId)- )- return fail('NOT_FOUND');- } else if (body.callerSessionId) {- if (- !db- .prepare(- "SELECT id FROM sessions WHERE id=? AND status <> 'deleted' AND coalesce(source,'') <> 'bot' AND NOT EXISTS (SELECT 1 FROM bot_session_links b WHERE b.session_id=sessions.id)",- )- .get(body.callerSessionId)- )- return fail('NOT_FOUND');- }+ if (body.callerSessionId && !db.prepare(+ "SELECT id FROM sessions WHERE id=? AND status <> 'deleted'",+ ).get(body.callerSessionId)) return fail('NOT_FOUND');let affected: string[] = [];let deletion: TaskTagResult['deletion'];let hasMore: boolean | undefined;diff --git a/apps/desktop/src/main/maker-host/__tests__/agentCapabilityCatalog.test.ts b/apps/desktop/src/main/maker-host/__tests__/agentCapabilityCatalog.test.tsnew file mode 100644index 0000000000..1b783ea151--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/agentCapabilityCatalog.test.ts@@ -0,0 +1,61 @@+import { describe, expect, it, vi } from 'vitest';+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import { z } from 'zod';+import { readAgentCapabilityCatalog, RUNTIME_MCP_NAMES_KEY } from '../agentCapabilityCatalog';++const context = { agentKind: 'pi' as const, workingDir: '/repo', sessionId: 'task' };++describe('shared runtime capability discovery', () => {+ it('uses registrations, includes future providers and does not construct servers for the index', async () => {+ const factory = vi.fn();+ const result = await readAgentCapabilityCatalog([+ { name: 'future', toClaudeSdkConfig: factory },+ { name: 'disabled', isEnabled: () => false, toClaudeSdkConfig: factory },+ ], context, {});+ expect(result).toMatchObject({ capabilities: [+ { server: 'future', status: 'registered' },+ { server: 'disabled', status: 'unavailable', reason: 'provider-not-enabled-for-session' },+ ] });+ expect(factory).not.toHaveBeenCalled();+ });++ it('reads real schemas and builtin progressive metadata without executing business tools', async () => {+ const execute = vi.fn();+ const factory = () => {+ const server = new McpServer({ name: 'fixture', version: '1' });+ server.registerTool('write_file', { inputSchema: { path: z.string() } }, execute);+ server.registerTool('list_tools', { inputSchema: { category: z.string().optional() } }, async ({ category }) => ({+ content: [{ type: 'text', text: JSON.stringify({ category, tools: ['write_file'] }) }],+ }));+ return { instance: server };+ };+ const result = await readAgentCapabilityCatalog([{ name: 'fixture',+ capability: { title: 'Fixture', description: 'Test', source: 'builtin' },+ toClaudeSdkConfig: factory,+ }], context, { server: 'fixture', category: 'files' });+ expect(result).toMatchObject({ ok: true, tools: expect.arrayContaining([+ expect.objectContaining({ name: 'write_file', inputSchema: expect.objectContaining({ type: 'object', properties: { path: { type: 'string' } }, required: ['path'] }) }),+ ]), discovery: { content: [{ type: 'text', text: JSON.stringify({ category: 'files', tools: ['write_file'] }) }] } });+ expect(execute).not.toHaveBeenCalled();+ });++ it('reports an explicitly unmounted capability and never starts custom transports', async () => {+ const factory = vi.fn(() => { throw new Error('secret'); });+ const providers = [{ name: 'custom', toClaudeSdkConfig: factory }];+ expect(await readAgentCapabilityCatalog(providers, {+ ...context, vendorOptions: { [RUNTIME_MCP_NAMES_KEY]: [] },+ }, { server: 'custom' })).toMatchObject({ ok: false, capability: { reason: 'not-mounted-in-current-runtime' } });+ expect(await readAgentCapabilityCatalog(providers, context, { server: 'custom' }))+ .toMatchObject({ ok: true, discovery: 'harness-mcp' });+ expect(factory).not.toHaveBeenCalled();+ });++ it('returns an explicit discovery failure without leaking factory errors', async () => {+ const result = await readAgentCapabilityCatalog([{ name: 'broken',+ capability: { title: 'Broken', description: '', source: 'builtin' },+ toClaudeSdkConfig: () => { throw new Error('secret'); },+ }], context, { server: 'broken' });+ expect(result).toMatchObject({ ok: false, errorCode: 'CAPABILITY_DISCOVERY_FAILED' });+ expect(JSON.stringify(result)).not.toContain('secret');+ });+});diff --git a/apps/desktop/src/main/maker-host/agentCapabilityCatalog.ts b/apps/desktop/src/main/maker-host/agentCapabilityCatalog.tsnew file mode 100644index 0000000000..1c9706d213--- /dev/null+++ b/apps/desktop/src/main/maker-host/agentCapabilityCatalog.ts@@ -0,0 +1,83 @@+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import type { McpProvider, McpProviderContext } from '@cindy/maker-core';++export const RUNTIME_MCP_NAMES_KEY = 'cindyRuntimeMcpServerNames';++export interface AgentCapabilityQuery { server?: string; category?: string; }++/** Read the actual provider registrations. This catalog never grants permissions or starts tools. */+export async function readAgentCapabilityCatalog(+ providers: readonly McpProvider[],+ context: McpProviderContext,+ query: AgentCapabilityQuery,+ availability: (provider: McpProvider) => string | null = () => null,+) {+ const declarations = providers.map((provider) => {+ let reason: string | null = null;+ try {+ const mounted = context.vendorOptions?.[RUNTIME_MCP_NAMES_KEY];+ reason = Array.isArray(mounted) && !mounted.includes(provider.name)+ ? 'not-mounted-in-current-runtime' : availability(provider);+ if (!reason && provider.isEnabled?.(context) === false) reason = 'provider-not-enabled-for-session';+ } catch { reason = 'provider-status-unavailable'; }+ return {+ server: provider.name,+ title: provider.capability?.title ?? provider.name,+ description: provider.capability?.description ?? '',+ source: provider.capability?.source ?? 'custom',+ status: reason ? 'unavailable' : 'registered',+ ...(reason ? { reason } : {}),+ ...(provider.capability?.discovery ? { discovery: provider.capability.discovery } : {}),+ };+ });+ if (!query.server) return {+ ok: true, agent: context.agentKind, capabilities: declarations,+ hint: 'registered 表示已注册且入口条件满足,连接、设备与具体操作仍以发现和执行回执为准。指定 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 {+ ok: true, capability: declaration, discovery: 'harness-mcp',+ hint: '通过当前引擎已有的 MCP 发现入口查询此连接的工具。',+ };+ 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 {+ ok: true, capability: declaration, discovery: 'harness-mcp',+ };+ instance = candidate;+ client = new Client({ name: 'cindy-capability-catalog', version: '1.0.0' });+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await instance.connect(serverTransport);+ await client.connect(clientTransport);+ const tools = [];+ let cursor: string | undefined;+ const cursors = new Set<string>();+ do {+ const page = await client.listTools(cursor ? { cursor } : {});+ tools.push(...page.tools);+ cursor = page.nextCursor;+ if (cursor && cursors.has(cursor)) throw new Error('Repeated tools cursor');+ if (cursor) cursors.add(cursor);+ } while (cursor);+ // Only first-party progressive metadata is expanded here. Custom servers+ // may name arbitrary business operations list_tools; never execute those.+ const discovery = declaration.source === 'builtin' && tools.some((tool) => tool.name === 'list_tools')+ ? await client.callTool({ name: 'list_tools', arguments: query.category ? { category: query.category } : {} })+ : undefined;+ return { ok: true, capability: declaration, tools, ...(discovery ? { discovery } : {}) };+ } catch {+ return { ok: false, capability: declaration, errorCode: 'CAPABILITY_DISCOVERY_FAILED', message: '工具目录读取失败;请通过原工具入口重试。' };+ } finally {+ await Promise.allSettled([client?.close(), instance?.close()]);+ }+}diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex ccb5383b51..9a43e79fc9 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -1,3 +1,4 @@+import { readAgentCapabilityCatalog, RUNTIME_MCP_NAMES_KEY, type AgentCapabilityQuery } from './agentCapabilityCatalog.js';import { listCindyManagedSkills, prepareCindyCodexSkills } from './managed-skills.js';import { createCompanionImportProvider } from '../bot-import/importProvider.js';import { createCompanionConnectionsProvider } from '../bot-import/connectionProvider.js';@@ -39,6 +40,7 @@ import path from 'node:path';import {Maker,+ isBotMcpServerAllowed,ClaudeCodeAgent,CodexAgent,configureDefaultImageResizer,@@ -285,7 +287,7 @@ import {setCodexEnvironmentShutdownHook,unregisterCodexMcpThreadContext,} from '../mcp-integrations/codexEnvironment.js';-import type { CodexHttpBridge } from '../mcp-integrations/codexHttpBridge.js';+import { REMOTE_ALLOWED_SERVER_NAMES, type CodexHttpBridge } from '../mcp-integrations/codexHttpBridge.js';import { setRemoteMcpBridgeTokenRotatedHook } from '../mcp-integrations/remoteMcpBridgeToken.js';import type { BotToolsetContext } from '../../shared/botRemoteCapabilities.js';import { isBotToolsetProviderAvailable } from './botToolsetAvailability.js';@@ -780,7 +782,7 @@ function getLspPool(): LspServerPool {/** Same Desktop provider instances used by the runtimes, evaluated for this Bot. */export function isBotToolsetAvailable(input: BotToolsetContext & { toolsetId: string }): boolean {- return isBotToolsetProviderAvailable(_mcpProviders.codex ?? [], input);+ return isBotToolsetProviderAvailable(_mcpProviders[input.agentKind] ?? [], input);}/** Shared by Bot tools, settings and hydration; never infer registration from raw DB rows. */@@ -932,6 +934,36 @@ export function getMaker(): Maker {};const makerMemoryProviderDeps = {+ runtimeCapabilities: async (context: import('@cindy/mcps').LiziMcpSessionContext, query: AgentCapabilityQuery) => {+ const session = context.sessionId ? _maker?.getSession(context.sessionId) : undefined;+ if (!session || (context.sessionInstanceId && session.instanceId !== context.sessionInstanceId))+ return { ok: false, errorCode: 'CALLER_UNAVAILABLE' };+ const agentKind = context.agentKind;+ if (agentKind !== 'claude-code' && agentKind !== 'codex' && agentKind !== 'pi')+ return { ok: false, errorCode: 'UNKNOWN_AGENT' };+ const catalog = await listBotRuntimeMcpServers({ agentKind, remoteHostId: context.remoteHostId });+ const providers = (_mcpProviders[agentKind] ?? []).map((provider) => ({+ ...provider,+ capability: provider.capability ?? {+ title: provider.name, description: '',+ source: catalog.find((entry) => entry.name === provider.name)?.source ?? 'custom',+ },+ }));+ const result = await readAgentCapabilityCatalog(providers,+ { ...context, agentKind, getSessionContext: undefined }, query,+ (provider) => {+ const entry = catalog.find((item) => item.name === provider.name);+ const remoteBridgeMissing = context.remoteHostId && agentKind !== 'pi'+ && entry?.source === 'builtin' && !REMOTE_ALLOWED_SERVER_NAMES.has(provider.name);+ return entry?.available === false || remoteBridgeMissing+ ? 'transport-unavailable-for-current-runtime' : null;+ });+ if (_maker?.getSession(session.id) !== session) return { ok: false, errorCode: 'CALLER_UNAVAILABLE' };+ return { ...result, permission: session.stablePermissionModeState,+ hostCapabilities: Object.fromEntries(Object.entries(session.capabilities)+ .filter(([, value]) => value && typeof value === 'object' && 'supported' in value)),+ hostCapabilitiesNote: '宿主支持的交互能力,不等于有同名 Agent 工具。Cindy 应用安装更新和重启须通过内置更新界面;check_app_update 仅检查更新。' };+ },botCapabilities: createDesktopBotCapabilityService(),createMediaDownloadContext: (sessionId: string, sessionInstanceId: string) => {const session = _maker?.getSession(sessionId);@@ -2714,6 +2746,9 @@ export function getMaker(): Maker {[CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY]: disabledPluginIds,...(botRuntimeSnapshot? {+ [RUNTIME_MCP_NAMES_KEY]: (_mcpProviders[createOpts.agentKind] ?? [])+ .filter((provider) => isBotMcpServerAllowed(createOpts.botRuntimeProfile?.mcpPolicy, provider.name))+ .map((provider) => provider.name),[CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY]: [...resolveBotAllowedBuiltinPluginIds(createOpts.botRuntimeProfile?.toolsetPolicy.catalog ?? [],diff --git a/apps/desktop/src/main/maker-host/plugins/__tests__/botBuiltinToolPolicy.test.ts b/apps/desktop/src/main/maker-host/plugins/__tests__/botBuiltinToolPolicy.test.tsindex ef8ab8ba50..e7cf184b78 100644--- a/apps/desktop/src/main/maker-host/plugins/__tests__/botBuiltinToolPolicy.test.ts+++ b/apps/desktop/src/main/maker-host/plugins/__tests__/botBuiltinToolPolicy.test.ts@@ -12,11 +12,12 @@ describe('Bot built-in tool baseline', () => {{ id: 'browser', available: false },];- it('keeps memory, the Bot helper and automations by default', () => {+ it('keeps memory, the helper, automations and LSP like ordinary tasks', () => {expect(resolveBotAllowedBuiltinPluginIds(catalog, [])).toEqual(['memory','xdt_helper','scheduler',+ 'lsp',]);});@@ -25,6 +26,7 @@ describe('Bot built-in tool baseline', () => {'memory','xdt_helper','scheduler',+ 'lsp','docs',]);});diff --git a/apps/desktop/src/main/maker-host/plugins/types.ts b/apps/desktop/src/main/maker-host/plugins/types.tsindex 40e4b365d6..5d57fc6139 100644--- a/apps/desktop/src/main/maker-host/plugins/types.ts+++ b/apps/desktop/src/main/maker-host/plugins/types.ts@@ -67,16 +67,8 @@ export const ESSENTIAL_PLUGIN_IDS: ReadonlySet<string> = new Set(['lsp',]);-/**- * Built-ins every Bot needs; ordinary Cindy Sessions keep all essentials.- * `scheduler`: a Bot main task can create ordinary automations on its owner's- * own turn (calls are judged per turn, maker-ipc/botTurnAuthority.ts).- */-export const BOT_BASELINE_PLUGIN_IDS: ReadonlySet<string> = new Set([- 'memory',- 'xdt_helper',- 'scheduler',-]);+/** Companions share the ordinary task's infrastructure; no separate permission tier. */+export const BOT_BASELINE_PLUGIN_IDS = ESSENTIAL_PLUGIN_IDS;export function resolveBotAllowedBuiltinPluginIds(catalog: readonly { id: string; available?: boolean }[],diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botProfileRuntime.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botProfileRuntime.test.tsindex bc3e3eafc1..b3de794d6d 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botProfileRuntime.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botProfileRuntime.test.ts@@ -186,21 +186,21 @@ describe('Bot Profile runtime prompt', () => {});});- it('treats legacy inherit as no ambient MCP or toolset grants', () => {+ it('inherits available MCPs and toolsets without a companion-specific opt-in', () => {expect(resolveBotMcpReferences({mode: 'inherit',configured: [],catalog: [{ name: 'global-search', source: 'custom', available: true }],}),- ).toEqual({ resolved: [], unavailable: [] });+ ).toEqual({ resolved: ['global-search'], unavailable: [] });expect(resolveBotToolsetReferences({mode: 'inherit',configured: [],catalog: [{ id: 'browser', name: 'Browser', available: true }],}),- ).toEqual({ resolved: [], unavailable: [], disabled: ['browser'] });+ ).toEqual({ resolved: ['browser'], unavailable: [], disabled: [] });});it('combines Bot toolset policy with project availability', () => {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botSystemPrompt.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botSystemPrompt.test.tsindex b7ccd682bf..6392ad8415 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botSystemPrompt.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botSystemPrompt.test.ts@@ -50,7 +50,9 @@ describe('稳定层:能力必须写进提示词', () => {main.capabilities.sessionControlEnabled = true;const stable = buildBotStableTier(main);expect(stable).toContain('你能看、能管主人的任务');- expect(stable).toContain('OWNER_TURN_REQUIRED');+ expect(stable).toContain('沿用当前任务的权限档与用户授权');+ expect(stable).not.toContain('OWNER_TURN_REQUIRED');+ expect(stable).not.toContain('TASK_OUT_OF_SCOPE');expect(stable).toContain('add_workbench_project');expect(stable).not.toContain('你能建普通自动化');main.capabilities.automationEnabled = true;diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botTurnAuthority.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botTurnAuthority.test.tsdeleted file mode 100644index 4e06ebe32a..0000000000--- a/apps/desktop/src/main/maker-ipc/__tests__/botTurnAuthority.test.ts+++ /dev/null@@ -1,298 +0,0 @@-import Database from 'better-sqlite3';-import { drizzle } from 'drizzle-orm/better-sqlite3';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import type { DbClient } from '../../localDb/client/DbClient.js';-import { createBotToolCallAuthorizer, resolveBotCallerAuthority } from '../botToolCallAuthorizer.js';-import {- decideBotToolCall,- resolveBotTurnAuthority,- type BotTurnAuthority,- type BotTurnExecution,-} from '../botTurnAuthority.js';--const OWNER_INPUT: BotTurnExecution = {- executing: true,- input: { clientId: 'owner-msg', authoredText: '帮我把旧任务都归档' },-};-const input = (clientId: string, originKind?: string): BotTurnExecution => ({- executing: true,- input: { clientId, ...(originKind ? { originKind } : {}) },-});--describe('decideBotToolCall', () => {- it('lets the owner own turn use everything, including tools not registered here', () => {- for (const [server, tool] of [- ['cindy_helper', 'archive_sessions'],- ['cindy_helper', 'some_future_tool'],- ['cindy_scheduler', 'schedule_create'],- ] as const) {- expect(decideBotToolCall(server, tool, {}, 'owner')).toEqual({ kind: 'allow' });- }- });-- it.each<[string, BotTurnAuthority]>([- ['start_session_task', 'other'],- ['send_to_agent', 'other'],- ['list_sessions', 'other'],- ['search_chat_history', 'other'],- ['routine_history', 'other'],- ['get_workbench', 'arranged'],- ['continue_workbench_task', 'arranged'],- ['create_project', 'arranged'],- ['routine_save', 'arranged'],- ['find_teammate_capabilities', 'other'],- ])('allows %s in a %s turn', (tool, authority) => {- expect(decideBotToolCall('cindy_helper', tool, {}, authority)).toEqual({ kind: 'allow' });- });-- it.each<[string, BotTurnAuthority]>([- ['add_task_tags', 'arranged'],- ['set_app_default_model', 'arranged'],- ['add_workbench_project', 'arranged'],- ['remove_workbench_project', 'arranged'],- ['move_session', 'arranged'],- ['some_future_tool', 'arranged'],- ['get_workbench', 'other'],- ['continue_workbench_task', 'other'],- ['routine_save', 'other'],- ['create_project', 'other'],- ['create_teammate', 'other'],- ['create_teammate', 'arranged'],- ['set_teammate_capability', 'arranged'],- ['update_teammate_profile', 'arranged'],- ['update_teammate_profile', 'other'],- ['set_teammate_capability', 'other'],- ['update_bot_profile', 'other'],- ['set_bot_capability', 'other'],- ])('keeps %s for the owner in a %s turn', (tool, authority) => {- expect(decideBotToolCall('cindy_helper', tool, {}, authority)).toMatchObject({- kind: 'deny',- errorCode: 'OWNER_TURN_REQUIRED',- });- });-- it('checks the target of session control by tier, reads freely only when arranged', () => {- const args = { session_id: 'task-1' };- expect(decideBotToolCall('cindy_helper', 'get_session_runtime', args, 'arranged')).toEqual({ kind: 'allow' });- expect(decideBotToolCall('cindy_helper', 'get_session_runtime', args, 'other'))- .toEqual({ kind: 'targets', sessionIds: ['task-1'], scope: 'own' });- expect(decideBotToolCall('cindy_helper', 'stop_session_turn', args, 'arranged'))- .toEqual({ kind: 'targets', sessionIds: ['task-1'], scope: 'own-or-handed' });- expect(decideBotToolCall('cindy_helper', 'steer_session', args, 'other'))- .toEqual({ kind: 'targets', sessionIds: ['task-1'], scope: 'own' });- expect(decideBotToolCall('cindy_helper', 'stop_session_turn', {}, 'other'))- .toMatchObject({ kind: 'deny', errorCode: 'INVALID_ARGS' });- // Omitted session_id means the caller's own current task.- expect(decideBotToolCall('cindy_helper', 'get_session_runtime', {}, 'other')).toEqual({ kind: 'allow' });- expect(decideBotToolCall('cindy_helper', 'set_session_runtime', { effort: 'high' }, 'other')).toEqual({ kind: 'allow' });- });-- it('checks every target of rename and archive batches by tier', () => {- expect(decideBotToolCall('cindy_helper', 'rename_sessions', {- changes: [{ session_id: 'a', title: 'x' }, { session_id: 'b', title: 'y' }, { session_id: 'a', title: 'z' }],- }, 'arranged')).toEqual({ kind: 'targets', sessionIds: ['a', 'b'], scope: 'own-or-handed' });- expect(decideBotToolCall('cindy_helper', 'archive_sessions', { session_ids: ['a'] }, 'other'))- .toEqual({ kind: 'targets', sessionIds: ['a'], scope: 'own' });- expect(decideBotToolCall('cindy_helper', 'unarchive_sessions', { session_ids: [] }, 'other'))- .toMatchObject({ kind: 'deny', errorCode: 'INVALID_ARGS' });- expect(decideBotToolCall('cindy_helper', 'rename_sessions', { changes: [{ title: 'x' }] }, 'arranged'))- .toMatchObject({ kind: 'deny', errorCode: 'INVALID_ARGS' });- });-- it('opens a new ordinary task only on the owner turn, but can message an allowed one', () => {- expect(decideBotToolCall('cindy_helper', 'send_to_session', { message: 'go' }, 'arranged'))- .toMatchObject({ kind: 'deny', errorCode: 'OWNER_TURN_REQUIRED' });- expect(decideBotToolCall('cindy_helper', 'send_to_session', { target_session_id: 't', message: 'go' }, 'arranged'))- .toEqual({ kind: 'targets', sessionIds: ['t'], scope: 'own-or-handed' });- });-- it('creates or changes automations only on the owner turn', () => {- expect(decideBotToolCall('cindy_scheduler', 'schedule_list', {}, 'arranged')).toEqual({ kind: 'allow' });- expect(decideBotToolCall('cindy_scheduler', 'schedule_notify_current_run', {}, 'other')).toEqual({ kind: 'allow' });- for (const authority of ['arranged', 'other'] as const) {- for (const tool of ['schedule_create', 'schedule_update', 'schedule_delete', 'schedule_run_now']) {- expect(decideBotToolCall('cindy_scheduler', tool, {}, authority)).toMatchObject({ kind: 'deny' });- }- }- expect(decideBotToolCall('cindy_scheduler', 'schedule_list', {}, 'other')).toMatchObject({ kind: 'deny' });- });-});--let sqlite: Database.Database;-let db: Pick<DbClient, 'drizzle'>;-let clock = 1_000;--function message(sessionId: string, clientId: string, meta: object) {- sqlite.prepare('INSERT INTO messages (session_id, client_id, role, agent_meta, created_at) VALUES (?, ?, ?, ?, ?)')- .run(sessionId, clientId, 'user', JSON.stringify(meta), ++clock);-}-function delegation(id: string, parentSessionId: string, childSessionId: string | null = null) {- sqlite.prepare('INSERT INTO bot_delegations (id, requesting_bot_id, parent_session_id, child_session_id, created_at) VALUES (?, ?, ?, ?, ?)')- .run(id, 'bot-1', parentSessionId, childSessionId, ++clock);-}-const ownerMeta = { delivery: 'turn', autoReviewUserText: '帮我把这个项目跑起来' };-const botDmMeta = { delivery: 'turn', origin: { kind: 'bot-dm' } };--beforeEach(() => {- clock = 1_000;- sqlite = new Database(':memory:');- sqlite.exec(`- CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT, status TEXT, remote_host_id TEXT, cleared_at INTEGER);- CREATE TABLE bot_session_links (id TEXT PRIMARY KEY, bot_id TEXT, session_id TEXT, role TEXT, archived_at INTEGER);- CREATE TABLE bot_delegations (id TEXT PRIMARY KEY, requesting_bot_id TEXT, parent_session_id TEXT, child_session_id TEXT, created_at INTEGER);- CREATE TABLE messages (session_id TEXT, client_id TEXT, role TEXT, agent_meta TEXT, created_at INTEGER, rewind_at INTEGER);- INSERT INTO sessions VALUES ('bot-main', 'bot', 'active', NULL, NULL);- INSERT INTO sessions VALUES ('bot-lane', 'bot', 'active', NULL, NULL);- INSERT INTO sessions VALUES ('bot-remote', 'bot', 'active', 'ssh-1', NULL);- INSERT INTO sessions VALUES ('child-1', 'desktop', 'active', NULL, NULL);- INSERT INTO sessions VALUES ('owner-task', 'desktop', 'active', NULL, NULL);- INSERT INTO sessions VALUES ('handed-task', 'desktop', 'active', NULL, NULL);- INSERT INTO bot_session_links VALUES ('l1', 'bot-1', 'bot-main', 'canonical', NULL);- INSERT INTO bot_session_links VALUES ('l2', 'bot-1', 'bot-lane', 'group', NULL);- INSERT INTO bot_session_links VALUES ('l3', 'bot-2', 'bot-remote', 'canonical', NULL);- `);- db = { drizzle: drizzle(sqlite) as unknown as DbClient['drizzle'] };-});-afterEach(() => sqlite.close());--describe('resolveBotTurnAuthority', () => {- it('reads the owner, automation and unknown sources from the host input', async () => {- expect(await resolveBotTurnAuthority(db, 'bot-main', OWNER_INPUT)).toBe('owner');- expect(await resolveBotTurnAuthority(db, 'bot-main', input('schedule-run:1', 'scheduler'))).toBe('arranged');- expect(await resolveBotTurnAuthority(db, 'bot-main', input('bot-dm:abc'))).toBe('other');- });-- it('treats a background-task report as arranged only when the owner or an automation started that task', async () => {- message('bot-main', 'owner-msg', ownerMeta);- delegation('d-owner', 'bot-main');- message('bot-main', 'bot-dm:1', botDmMeta);- delegation('d-dm', 'bot-main');- expect(await resolveBotTurnAuthority(db, 'bot-main', input('bot-delegation-completion:d-owner'))).toBe('arranged');- expect(await resolveBotTurnAuthority(db, 'bot-main', input('bot-delegation-interaction:d-owner:req-1'))).toBe('arranged');- // Started while another Bot was talking: its report must not lift the tier.- expect(await resolveBotTurnAuthority(db, 'bot-main', input('bot-delegation-completion:d-dm:2'))).toBe('other');- expect(await resolveBotTurnAuthority(db, 'bot-main', input('bot-delegation-completion:missing'))).toBe('other');- });-- it('follows a chain of reports back to the turn that started it', async () => {- message('bot-main', 'owner-msg', ownerMeta);- delegation('d1', 'bot-main');- message('bot-main', 'bot-delegation-completion:d1', {});- delegation('d2', 'bot-main');- expect(await resolveBotTurnAuthority(db, 'bot-main', input('bot-delegation-completion:d2'))).toBe('arranged');-- message('bot-main', 'bot-dm:2', botDmMeta);- delegation('d3', 'bot-main');- message('bot-main', 'bot-delegation-completion:d3', {});- delegation('d4', 'bot-main');- expect(await resolveBotTurnAuthority(db, 'bot-main', input('bot-delegation-completion:d4'))).toBe('other');- });-- it('caps an authorization resume at the turn that asked for it', async () => {- message('bot-main', 'owner-msg', ownerMeta);- message('bot-main', 'bot-authorization-resume:r1', {});- expect(await resolveBotTurnAuthority(db, 'bot-main', input('bot-authorization-resume:r1'))).toBe('arranged');- message('bot-main', 'bot-dm:3', botDmMeta);- message('bot-main', 'bot-authorization-resume:r2', {});- expect(await resolveBotTurnAuthority(db, 'bot-main', input('bot-authorization-resume:r2'))).toBe('other');- });-- it('drops to the lowest tier once another task or Bot steers into the turn', async () => {- message('bot-main', 'owner-msg', ownerMeta);- expect(await resolveBotTurnAuthority(db, 'bot-main', OWNER_INPUT)).toBe('owner');- // The owner's own composer steer carries no origin and keeps the tier.- message('bot-main', 'owner-steer', { delivery: 'steer', autoReviewUserText: '再加一句' });- expect(await resolveBotTurnAuthority(db, 'bot-main', OWNER_INPUT)).toBe('owner');- message('bot-main', 'foreign-steer', { delivery: 'steer', origin: { kind: 'session' } });- expect(await resolveBotTurnAuthority(db, 'bot-main', OWNER_INPUT)).toBe('other');- });-- it('falls back to the latest root input when the coordinator has none', async () => {- message('bot-main', 'schedule-run:9', { origin: { kind: 'scheduler' } });- expect(await resolveBotTurnAuthority(db, 'bot-main', { executing: false, input: null })).toBe('arranged');- });-});--describe('createBotToolCallAuthorizer', () => {- function authorizer(execution: BotTurnExecution, handed: string[] = []) {- return createBotToolCallAuthorizer({- getDb: () => db,- readExecution: () => execution,- isWorkbenchProjectSession: vi.fn(async (_botId: string, sessionId: string) => handed.includes(sessionId)),- });- }- const call = (tool: string, args: unknown = {}, sessionId = 'bot-main', server: 'cindy_helper' | 'cindy_scheduler' = 'cindy_helper') =>- ({ sessionId, server, tool, args });-- it('leaves ordinary tasks alone', async () => {- expect(await authorizer(input('bot-dm:1'))(call('archive_sessions', {}, 'owner-task'))).toEqual({ ok: true });- });-- it('gives the owner turn the whole surface', async () => {- expect(await authorizer(OWNER_INPUT)(call('archive_sessions'))).toEqual({ ok: true });- expect(await authorizer(OWNER_INPUT)(call('schedule_create', {}, 'bot-main', 'cindy_scheduler'))).toEqual({ ok: true });- });-- it('lets other turns act only on the Bot own tasks', async () => {- delegation('d1', 'bot-main', 'child-1');- const auth = authorizer(input('bot-dm:1'), ['handed-task']);- expect(await auth(call('stop_session_turn', { session_id: 'child-1' }))).toEqual({ ok: true });- expect(await auth(call('stop_session_turn', { session_id: 'handed-task' })))- .toMatchObject({ ok: false, errorCode: 'TASK_OUT_OF_SCOPE' });- expect(await auth(call('stop_session_turn', { session_id: 'owner-task' })))- .toMatchObject({ ok: false, errorCode: 'TASK_OUT_OF_SCOPE' });- });-- it('lets arranged turns also act on tasks in handed-over projects', async () => {- const auth = authorizer(input('schedule-run:1', 'scheduler'), ['handed-task']);- expect(await auth(call('steer_session', { session_id: 'handed-task' }))).toEqual({ ok: true });- expect(await auth(call('steer_session', { session_id: 'owner-task' })))- .toMatchObject({ ok: false, errorCode: 'TASK_OUT_OF_SCOPE' });- });-- it('judges a non-main Bot session at the lowest tier even if the owner typed', async () => {- expect(await resolveBotCallerAuthority(db, 'bot-lane', () => OWNER_INPUT))- .toEqual({ kind: 'bot', botId: 'bot-1', main: false, authority: 'other' });- expect(await authorizer(OWNER_INPUT)(call('set_app_default_model', {}, 'bot-lane')))- .toMatchObject({ ok: false, errorCode: 'OWNER_TURN_REQUIRED' });- expect(await authorizer(OWNER_INPUT)(call('archive_sessions', { session_ids: ['owner-task'] }, 'bot-lane')))- .toMatchObject({ ok: false, errorCode: 'TASK_OUT_OF_SCOPE' });- });-- it('lets a non-owner turn archive only tasks the Bot owns', async () => {- delegation('d1', 'bot-main', 'child-1');- const auth = authorizer(input('bot-delegation-completion:missing'));- expect(await auth(call('archive_sessions', { session_ids: ['child-1'] }))).toEqual({ ok: true });- expect(await auth(call('archive_sessions', { session_ids: ['child-1', 'owner-task'] })))- .toMatchObject({ ok: false, errorCode: 'TASK_OUT_OF_SCOPE' });- });-- it('keeps remote Bots on their old helper behavior, judging only local automations by turn', async () => {- expect(await authorizer(input('bot-dm:1'))(call('set_app_default_model', {}, 'bot-remote'))).toEqual({ ok: true });- expect(await authorizer(OWNER_INPUT)(call('schedule_create', {}, 'bot-remote', 'cindy_scheduler'))).toEqual({ ok: true });- expect(await authorizer(input('bot-dm:1'))(call('schedule_create', {}, 'bot-remote', 'cindy_scheduler')))- .toMatchObject({ ok: false, errorCode: 'OWNER_TURN_REQUIRED' });- });-- it('refuses a call it cannot attribute to a task', async () => {- expect(await authorizer(OWNER_INPUT)({ sessionId: undefined, server: 'cindy_scheduler', tool: 'schedule_list', args: {} }))- .toMatchObject({ ok: false, errorCode: 'CAPABILITY_NOT_AVAILABLE' });- });-- it('refuses while the account database is unavailable or switching', async () => {- const noDb = createBotToolCallAuthorizer({- getDb: () => null,- readExecution: () => OWNER_INPUT,- isWorkbenchProjectSession: async () => false,- });- expect(await noDb(call('archive_sessions'))).toMatchObject({ ok: false, errorCode: 'HOST_NOT_READY' });- const switching = createBotToolCallAuthorizer({- getDb: () => db,- readExecution: () => OWNER_INPUT,- isWorkbenchProjectSession: async () => false,- isScopeCurrent: () => false,- });- expect(await switching(call('archive_sessions'))).toMatchObject({ ok: false, errorCode: 'OWNER_SCOPE_CHANGED' });- });-});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/taskToolCallAuthorizer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/taskToolCallAuthorizer.test.tsnew file mode 100644index 0000000000..50dde1702f--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/taskToolCallAuthorizer.test.ts@@ -0,0 +1,48 @@+import Database from 'better-sqlite3';+import { drizzle } from 'drizzle-orm/better-sqlite3';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import type { DbClient } from '../../localDb/client/DbClient.js';+import { createTaskToolCallAuthorizer } from '../taskToolCallAuthorizer.js';++describe('shared task tool admission', () => {+ let sqlite: Database.Database;+ let db: Pick<DbClient, 'drizzle'>;+ let current: boolean;+ beforeEach(() => {+ sqlite = new Database(':memory:');+ sqlite.exec("CREATE TABLE sessions (id TEXT PRIMARY KEY, status TEXT, source TEXT); INSERT INTO sessions VALUES ('companion','active','bot'),('ordinary','active','desktop'),('automation','active','scheduler'),('hook','active','hook');");+ db = { drizzle: drizzle(sqlite) } as unknown as Pick<DbClient, 'drizzle'>;+ current = true;+ });+ afterEach(() => sqlite.close());+ const commands = [+ ['cindy_helper', 'archive_sessions'], ['cindy_helper', 'some_future_tool'],+ ['cindy_helper', 'set_teammate_capability'], ['cindy_scheduler', 'schedule_create'],+ ] as const;+ it('uses the same admission for ordinary tasks and companions, including future tools', async () => {+ const authorize = createTaskToolCallAuthorizer({ getDb: () => db, isScopeCurrent: () => current });+ for (const sessionId of ['ordinary', 'companion']) for (const [server, tool] of commands)+ expect(await authorize({ sessionId, server, tool, args: {} })).toEqual({ ok: true });+ });+ it.each(['companion', 'ordinary', 'automation', 'hook'])('allows the next tool call after archiving %s, but rejects deletion', async (sessionId) => {+ const authorize = createTaskToolCallAuthorizer({ getDb: () => db, isScopeCurrent: () => current });+ for (const status of ['active', 'archived', 'deleted']) {+ sqlite.prepare('UPDATE sessions SET status = ? WHERE id = ?').run(status, sessionId);+ for (const [server, tool] of commands) {+ expect(await authorize({ sessionId, server, tool, args: {} })).toMatchObject(status === 'deleted'+ ? { ok: false, errorCode: 'TASK_UNAVAILABLE' } : { ok: true });+ }+ }+ });+ it('retains missing caller and account-change checks', async () => {+ const authorize = createTaskToolCallAuthorizer({ getDb: () => db, isScopeCurrent: () => current });+ for (const sessionId of [undefined, 'missing'])+ expect((await authorize({ sessionId, server: 'cindy_helper', tool: 'list_sessions', args: {} })).ok).toBe(false);+ current = false;+ expect(await authorize({ sessionId: 'companion', server: 'cindy_helper', tool: 'list_sessions', args: {} }))+ .toMatchObject({ ok: false, errorCode: 'OWNER_SCOPE_CHANGED' });+ expect(await createTaskToolCallAuthorizer({ getDb: () => null, isScopeCurrent: () => true })({+ sessionId: 'companion', server: 'cindy_helper', tool: 'list_sessions', args: {},+ })).toMatchObject({ ok: false, errorCode: 'HOST_NOT_READY' });+ });+});diff --git a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts b/apps/desktop/src/main/maker-ipc/botCapabilityService.tsindex 563bb8b901..889b6e9a7e 100644--- a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts+++ b/apps/desktop/src/main/maker-ipc/botCapabilityService.ts@@ -6,6 +6,7 @@ import { getDbClient } from '../localDb/client/current.js';import { updateBotProfile } from '../localDb/ipc/bots.js';import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';import { listCustomMcpServers } from '../maker-host/custom-mcp-store.js';+import { normalizeBotToolCapabilities } from '../../shared/botCapabilitySelection.js';import { BOT_BASELINE_PLUGIN_IDS } from '../maker-host/plugins/types.js';import type { AgentKind, Maker } from '@cindy/maker-core';import type { PluginRegistry } from '../maker-host/plugins/plugin-registry.js';@@ -97,7 +98,7 @@ async function context(callerSessionId: string, opts?: { allowPaused?: boolean }parsed && typeof parsed === 'object' && !Array.isArray(parsed)? (parsed as Record<string, unknown>): {};- return { ...row, config, assertOwner };+ return { ...row, config: normalizeBotToolCapabilities(config), assertOwner };}async function catalog(input: Input, ctx: Pick<Awaited<ReturnType<typeof context>>, 'config' | 'workingDir' | 'remoteHostId' | 'botId' | 'assertOwner'>, deps: BotCapabilityServiceDeps,@@ -143,7 +144,7 @@ async function catalog(input: Input, ctx: Pick<Awaited<ReturnType<typeof contextitems = await Promise.all(registry.getPlugins()- .filter((plugin) => plugin.id !== 'collab' && !BOT_BASELINE_PLUGIN_IDS.has(plugin.id))+ .filter((plugin) => !BOT_BASELINE_PLUGIN_IDS.has(plugin.id)).map(async (plugin) => ({id: plugin.id,name: plugin.name,@@ -161,7 +162,8 @@ async function catalog(input: Input, ctx: Pick<Awaited<ReturnType<typeof context);}ctx.assertOwner();- const result = items.map((item) => ({ ...item, joined: joined.has(item.id) }));+ const inherit = input.kind !== 'skill' && ctx.config[fields[input.kind].mode] === 'inherit';+ const result = items.map((item) => ({ ...item, joined: joined.has(item.id) || (inherit && item.available) }));// Uninstalled references remain removable, instead of silently disappearing.for (const id of joined)if (!result.some((item) => item.id === id))@@ -198,7 +200,9 @@ async function selectBotCapability(input: Input & { id: string; joined: boolean};}const field = fields[input.kind];- const previous = strings(ctx.config[field.list]);+ const previous = input.kind !== 'skill' && ctx.config[field.mode] === 'inherit'+ ? (await catalog(input, ctx, deps)).filter((item) => item.joined).map((item) => item.id)+ : strings(ctx.config[field.list]);if (input.joined) {const item = (await catalog(input, ctx, deps, { forceReload: true })).find((entry) => entry.id === input.id);if (!item?.available)@@ -314,7 +318,7 @@ export function createBotCapabilityService(deps: BotCapabilityServiceDeps) {},/** Read the same metadata before a profile exists; this never joins or executes a capability. */async forCreation(input: { botId: string; workingDir: string; agentKind: AgentKind; assertOwner: () => void }) {- const ctx = { ...input, remoteHostId: null, config: {} };+ const ctx = { ...input, remoteHostId: null, config: normalizeBotToolCapabilities({}) };const result = {} as Record<Kind, Entry[]>;for (const kind of ['skill', 'mcp', 'toolset'] as const)result[kind] = (await catalog({ callerSessionId: '', kind }, ctx, deps, { agentKind: input.agentKind })).filter(entry => entry.available);diff --git a/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts b/apps/desktop/src/main/maker-ipc/botProfileRuntime.tsindex 73a861a73b..1666cec63e 100644--- a/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts+++ b/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts@@ -24,6 +24,7 @@ import {import { clearBotAttention, noteBotAttention } from './botAttentionService.js';import { createLogger } from '../logger.js';import { PROVIDER_NAME_TO_PLUGIN_ID } from '../maker-host/plugins/builtin-plugins.js';+import { normalizeBotToolCapabilities } from '../../shared/botCapabilitySelection.js';import { BOT_BASELINE_PLUGIN_IDS } from '../maker-host/plugins/types.js';const log = createLogger('maker-ipc:bot-profile-runtime');@@ -427,9 +428,7 @@ export function resolveBotMcpReferences(input: {.map((item) => item.name),);if (input.mode === 'inherit') {- // "Follow Cindy" means available for progressive discovery, not eagerly- // mounting every custom server into every Bot context.- return { resolved: [], unavailable: [] };+ return { resolved: input.catalog.filter((item) => item.available !== false).map((item) => item.name), unavailable: [] };}return {resolved: input.configured.filter((name) => available.has(name)),@@ -446,19 +445,17 @@ export function resolveBotToolsetReferences(input: {unavailable: string[];disabled: string[];} {- // Host essentials (for example scheduler) are not necessarily Bot baseline- // tools. An explicit per-Bot selection must remain mountable.- const configurable = input.catalog.filter((item) => !item.essential || input.configured.includes(item.id));+ // Essential infrastructure is shared with ordinary tasks; optional selections+ // only control the remaining entries.+ const configurable = input.catalog;const available = new Set(configurable.filter((item) => item.available !== false).map((item) => item.id),);if (input.mode === 'inherit') {return {- // Essential Bot runtime tools are mounted separately. Optional Cindy- // toolsets stay discoverable but do not flood the Bot by default.- resolved: [],+ resolved: [...available],unavailable: [],- disabled: configurable.map((item) => item.id),+ disabled: [],};}const resolved = input.configured.filter((id) => available.has(id));@@ -466,7 +463,7 @@ export function resolveBotToolsetReferences(input: {return {resolved,unavailable: input.configured.filter((id) => !available.has(id)),- disabled: configurable.filter((item) => !resolvedSet.has(item.id)).map((item) => item.id),+ disabled: configurable.filter((item) => !item.essential && !resolvedSet.has(item.id)).map((item) => item.id),};}@@ -514,7 +511,7 @@ export async function hydrateBotProfileRuntime().limit(1);if (!version) return null;- const config = parseObject(version.capabilitiesJson);+ const config = normalizeBotToolCapabilities(parseObject(version.capabilitiesJson));const configuredSkills = Array.isArray(config.skills)? config.skills.filter((item): item is string => typeof item === 'string'): [];@@ -731,9 +728,7 @@ export async function hydrateBotProfileRuntime(resolvedMcpServers = resolvedMcp.resolved;unavailableMcpServers = resolvedMcp.unavailable;} catch {- mcpCatalog = [];- resolvedMcpServers = [];- unavailableMcpServers = mcpMode === 'allowlist' ? configuredMcpServers : [];+ throw new Error('无法读取伙伴的 MCP 能力目录,请重试;不会以空能力列表启动。');}} else if (mcpMode === 'allowlist') {unavailableMcpServers = configuredMcpServers;@@ -763,10 +758,7 @@ export async function hydrateBotProfileRuntime(unavailableToolsets = resolvedToolsetsResult.unavailable;disabledToolsets = resolvedToolsetsResult.disabled;} catch {- toolsetCatalog = [];- resolvedToolsets = [];- unavailableToolsets = toolsetMode === 'allowlist' ? configuredToolsets : [];- disabledToolsets = [];+ throw new Error('无法读取伙伴的工具能力目录,请重试;不会以空能力列表启动。');}} else if (toolsetMode === 'allowlist') {unavailableToolsets = configuredToolsets;@@ -784,7 +776,7 @@ export async function hydrateBotProfileRuntime(.map((item) => item.id),]);for (const [serverName, toolsetId] of Object.entries(PROVIDER_NAME_TO_PLUGIN_ID)) {- if (toolsetId === 'collab' || !mountedToolsets.has(toolsetId) || runtimeConfiguredMcpServers.includes(serverName)) continue;+ if (!mountedToolsets.has(toolsetId) || runtimeConfiguredMcpServers.includes(serverName)) continue;if (mcpCatalog.some((item) => item.name === serverName && item.available !== false)) {runtimeConfiguredMcpServers.push(serverName);}@@ -816,11 +808,10 @@ export async function hydrateBotProfileRuntime(// index must not hide the instructions for learning the first reusable method.ownSkillsEnabled: row.role === 'canonical' && helperAvailable && !opts.remoteHostId,botModeEnabled: row.role === 'canonical',- // Same condition as the `bot-main` helper surface (mcp-integrations/helperSurface.ts).- sessionControlEnabled: row.role === 'canonical' && helperAvailable && !opts.remoteHostId,+ // Match the ordinary helper surface on this engine and transport.+ sessionControlEnabled: helperAvailable && (!opts.remoteHostId || opts.agentKind === 'pi'),// scheduler 是伙伴基线工具(maker-host/plugins/types.ts),与挂载 allowlist 同一份目录判定。- automationEnabled: row.role === 'canonical' && !opts.remoteHostId- && toolsetCatalog.some((item) => item.id === 'scheduler' && item.available !== false),+ automationEnabled: toolsetCatalog.some((item) => item.id === 'scheduler' && item.available !== false),};/*伙伴的家。读失败一律当"没有" —— 一次读不动不该让整个伙伴起不来,只是这一轮diff --git a/apps/desktop/src/main/maker-ipc/botSystemPrompt.ts b/apps/desktop/src/main/maker-ipc/botSystemPrompt.tsindex 0484f60d5d..fe4e1aa145 100644--- a/apps/desktop/src/main/maker-ipc/botSystemPrompt.ts+++ b/apps/desktop/src/main/maker-ipc/botSystemPrompt.ts@@ -35,11 +35,10 @@ export interface BotPromptCapabilitySignals {/** 是否为 Bot 的 canonical Chat;Bot Mode 协议只在这里生效。 */botModeEnabled?: boolean;/**- * 本机伙伴主任务拿到普通任务那一套 session 工具(宿主按本轮来源逐次判定,见 botTurnAuthority.ts)。- * 远程伙伴与群专线等非主任务没有。+ * 是否已挂载普通任务的 session 工具。权限与同环境的普通 Agent 一致。*/sessionControlEnabled?: boolean;- /** 伙伴基线挂载了 cindy_scheduler(本机主任务);宿主仍按轮判定写操作。 */+ /** 是否已挂载 cindy_scheduler;操作沿用当前 Agent 权限。 */automationEnabled?: boolean;}@@ -149,20 +148,19 @@ const TASK_AND_TEAMMATE_GUIDANCE = [].join('\n');/**- * 和普通任务同一套 session 能力,以及「这一轮是谁触发的」决定能做多少(宿主逐次核对,- * 提示词只负责让伙伴知道有这些能力、被拒时怎么办)。+ * 与普通任务共用 session 能力及权限档;提示词说明能力与实际回执的关系。*/const SESSION_CONTROL_GUIDANCE = ['## 你能看、能管主人的任务','你和主人开的普通任务用同一套工具(cindy_helper,先 `list_tools` 看类目再 `call_tool`):history 类的 `list_sessions` / `get_chat_history` / `search_chat_history` 看有哪些任务、它们在说什么;control 类的 `steer_session`、`stop_session_turn`、`set_session_runtime`、`rename_sessions`、`archive_sessions`、标签与项目工具管理任务;handoff 类的 `send_to_session` 给已有任务发话或开一条新的普通任务。',- '能做多少取决于这一轮是谁触发的,宿主每次调用都会核对:主人本人在这里发话的那一轮,这些都能用;自动化、例行任务、你开的后台任务回报这类主人事先安排的,能看全部,只能动交给你的项目里的任务和你自己开的任务;群聊、其他伙伴或别的任务转来的消息,只能动你自己开的任务。被拒(`OWNER_TURN_REQUIRED` / `TASK_OUT_OF_SCOPE`)就照实告诉主人,等主人自己说;不要换个工具、开后台任务、用命令行或请别的伙伴去做被拒的事。新建伙伴、改你自己的资料与能力只在主人本人发话的那一轮做。',+ '这些工具沿用当前任务的权限档与用户授权,不再按伙伴的消息来源另设工具权限分档。工具回执决定实际结果;账号、连接或平台未就绪时如实说明。','停止、归档、改名、给正在跑的任务插话这类会影响主人工作的事,主人没开口就不做;做之前用一句话说清要动哪件、做什么。',- '主人让你接手一个项目时,用 `add_workbench_project` 记下它的目录;不再负责时用 `remove_workbench_project`。这两个只在主人本人发话的那一轮可用。',+ '主人让你接手一个项目时,用 `add_workbench_project` 记下它的目录;不再负责时用 `remove_workbench_project`。',].join('\n');const AUTOMATION_GUIDANCE = ['## 你能建普通自动化',- '主人要你给某个项目或任务设定时执行时,用 cindy_scheduler 建普通自动化(先 `list_tools`,再 `call_tool` 调 `schedule_create` 等);只和你自己有关的提醒仍用例行任务。新建、修改、暂停、立即运行和删除只在主人本人发话的那一轮可用,其余时候只能查看。建完读回核实名称、时间和是否启用,成功才说已安排。',+ '主人要你给某个项目或任务设定时执行时,用 cindy_scheduler 建普通自动化(先 `list_tools`,再 `call_tool` 调 `schedule_create` 等);只和你自己有关的提醒仍用例行任务。操作沿用当前任务的权限档。建完读回核实名称、时间和是否启用,成功才说已安排。',].join('\n');const BOT_CREATION_GUIDANCE = [diff --git a/apps/desktop/src/main/maker-ipc/botToolCallAuthorizer.ts b/apps/desktop/src/main/maker-ipc/botToolCallAuthorizer.tsdeleted file mode 100644index a76758a338..0000000000--- a/apps/desktop/src/main/maker-ipc/botToolCallAuthorizer.ts+++ /dev/null@@ -1,118 +0,0 @@-/**- * 伙伴工具调用的宿主判定入口:把 `botTurnAuthority.ts` 的分档与规则接到真实数据上。- *- * - 不是伙伴的任务一律放行(普通任务、插件任务各有自己的能力面)。- * - 远程伙伴保持原有的窄能力面;只有经隧道挂到的本机自动化(远程 Pi)按同样的分档判定。- * - 伙伴的群专线、历史等非主任务一律按最低档(other)判定。- * - 「自己的任务」= 这个伙伴的 bot_session_links,或它开的后台任务(bot_delegations)。- * - 「已接手项目里的任务」与工作台继续同一判据(isWorkbenchProjectSession)。- */-import { and, eq } from 'drizzle-orm';--import type { ToolCallAuthorization, ToolCallAuthorizer } from '@cindy/mcps';--import type { DbClient } from '../localDb/client/DbClient.js';-import { botDelegations, botSessionLinks, sessions } from '../localDb/schema.js';-import {- decideBotToolCall,- resolveBotTurnAuthority,- type BotTurnAuthority,- type BotTurnExecution,-} from './botTurnAuthority.js';--export type BotCallerAuthority =- | { kind: 'not-bot' }- | { kind: 'remote-bot'; botId: string; authority: BotTurnAuthority }- | { kind: 'bot'; botId: string; main: boolean; authority: BotTurnAuthority };--export interface BotToolCallAuthorizerDeps {- getDb(): Pick<DbClient, 'drizzle'> | null;- readExecution(sessionId: string): BotTurnExecution;- isWorkbenchProjectSession(botId: string, sessionId: string): Promise<boolean>;- /** 账号切换中或数据库换了:拒绝,不在旧账号的数据上判定。 */- isScopeCurrent?(db: Pick<DbClient, 'drizzle'>): boolean;-}--export async function resolveBotCallerAuthority(- db: Pick<DbClient, 'drizzle'>,- sessionId: string,- readExecution: (sessionId: string) => BotTurnExecution,-): Promise<BotCallerAuthority> {- const [row] = await db.drizzle- .select({- botId: botSessionLinks.botId,- role: botSessionLinks.role,- linkArchivedAt: botSessionLinks.archivedAt,- source: sessions.source,- status: sessions.status,- remoteHostId: sessions.remoteHostId,- })- .from(sessions)- .leftJoin(botSessionLinks, eq(botSessionLinks.sessionId, sessions.id))- .where(eq(sessions.id, sessionId))- .limit(1);- if (!row || (!row.botId && row.source !== 'bot')) return { kind: 'not-bot' };- // 伙伴来源但链接坏了:按伙伴最低档处理,绝不退回普通任务的能力。- if (!row.botId) return { kind: 'bot', botId: '', main: false, authority: 'other' };- const main = row.role === 'canonical' && row.linkArchivedAt === null && row.source === 'bot' && row.status === 'active';- const authority = main ? await resolveBotTurnAuthority(db, sessionId, readExecution(sessionId)) : 'other';- if (row.remoteHostId) return { kind: 'remote-bot', botId: row.botId, authority };- return { kind: 'bot', botId: row.botId, main, authority };-}--async function isOwnTask(db: Pick<DbClient, 'drizzle'>, botId: string, sessionId: string): Promise<boolean> {- if (!botId) return false;- const [[link], [delegation]] = await Promise.all([- db.drizzle.select({ id: botSessionLinks.id }).from(botSessionLinks)- .where(and(eq(botSessionLinks.sessionId, sessionId), eq(botSessionLinks.botId, botId))).limit(1),- db.drizzle.select({ id: botDelegations.id }).from(botDelegations)- .where(and(eq(botDelegations.childSessionId, sessionId), eq(botDelegations.requestingBotId, botId))).limit(1),- ]);- return Boolean(link || delegation);-}--const SCOPE_CHANGED: ToolCallAuthorization = {- ok: false,- errorCode: 'OWNER_SCOPE_CHANGED',- message: '账号正在切换,请稍后重试。',-};--export function createBotToolCallAuthorizer(deps: BotToolCallAuthorizerDeps): ToolCallAuthorizer {- const judge = async (- db: Pick<DbClient, 'drizzle'>,- { sessionId, server, tool, args }: Parameters<ToolCallAuthorizer>[0] & { sessionId: string },- ): Promise<ToolCallAuthorization> => {- const caller = await resolveBotCallerAuthority(db, sessionId, deps.readExecution);- if (caller.kind === 'not-bot') return { ok: true };- // Remote Bots keep their unchanged helper surface. Automations live on this- // computer (tunneled to remote Pi), so they follow the same per-turn rules.- if (caller.kind === 'remote-bot' && server !== 'cindy_scheduler') return { ok: true };- const decision = decideBotToolCall(server, tool, args, caller.authority);- if (decision.kind === 'allow') return { ok: true };- if (decision.kind === 'deny') return { ok: false, errorCode: decision.errorCode, message: decision.message };- for (const target of decision.sessionIds) {- if (await isOwnTask(db, caller.botId, target)) continue;- if (decision.scope === 'own-or-handed' && await deps.isWorkbenchProjectSession(caller.botId, target)) continue;- return {- ok: false,- errorCode: 'TASK_OUT_OF_SCOPE',- message: decision.scope === 'own-or-handed'- ? '这一轮只能操作你自己开的任务,或主人交给你的项目里的任务。'- : '这一轮只能操作你自己开的任务;动主人的其他任务要等主人本人发话。',- };- }- return { ok: true };- };- return async (input) => {- // 权限闸门:认不出调用方就拒绝。普通任务的自动化调用本来也要求 session(withAccountDataAccess)。- if (!input.sessionId) {- return { ok: false, errorCode: 'CAPABILITY_NOT_AVAILABLE', message: '认不出这次调用来自哪个任务,已拒绝。' };- }- const db = deps.getDb();- if (!db) return { ok: false, errorCode: 'HOST_NOT_READY', message: '本机数据还没准备好,请稍后重试。' };- const result = await judge(db, { ...input, sessionId: input.sessionId });- // 判定期间换了账号:不在旧账号的数据上放行。- if (result.ok && deps.isScopeCurrent && !deps.isScopeCurrent(db)) return SCOPE_CHANGED;- return result;- };-}diff --git a/apps/desktop/src/main/maker-ipc/botTurnAuthority.ts b/apps/desktop/src/main/maker-ipc/botTurnAuthority.tsdeleted file mode 100644index d73d85a1d2..0000000000--- a/apps/desktop/src/main/maker-ipc/botTurnAuthority.ts+++ /dev/null@@ -1,338 +0,0 @@-/**- * 伙伴主任务「按这一轮是谁触发的」分档(2026-10-01 产品裁决,见 cindy-bots-runtime.md 6.4)。- *- * 本机伙伴主任务和普通任务拿同一套 session 工具;工具列表在整个会话里保持稳定(前缀缓存规则),- * 每次调用时由这里按本轮来源决定放不放行:- *- * - owner:主人本人在伙伴聊天里的输入(桌面、手机、同账号设备,含工作台按钮代发)。由可信输入通道- * 盖章,判据与插件任务「真人接管」共用 `hasAcceptedUserTaskInput`。= 全套。- * - arranged:主人事先安排好的——自动化 / 例行任务、伙伴自己开的后台任务回报或等待交互、- * 授权卡确认后的续跑。= 读全部;只动已接手项目里的任务和自己开的任务;不新建自动化、不改账号设置。- * 后台任务回报与授权续跑不高于引出它们的那一轮:由 other 那一轮引出的仍是 other。- * - other:其余一切(伙伴群聊、其他伙伴的消息、别的任务转来的消息)以及认不出来的。= 只动自己开的- * 任务、只读自己的记录。- *- * 判档只看宿主持有的事实,不看模型说了什么。- */-import { and, desc, eq, isNull, lt, sql } from 'drizzle-orm';--import type { DbClient } from '../localDb/client/DbClient.js';-import { botDelegations, messages, sessions } from '../localDb/schema.js';-import { hasAcceptedUserTaskInput, isAcceptedUserInputRow, type AcceptedTaskInput } from './pluginTaskInput.js';--export type BotTurnAuthority = 'owner' | 'arranged' | 'other';--/**- * 宿主代发的续跑输入:后台任务完成回报、后台任务等待交互、账号授权完成后的续跑。- * 它们本身不是主人说的话,可信程度不高于引出它们的那一轮(见 continuationAuthority)。- */-const CONTINUATION_CLIENT_ID_PREFIXES = [- 'bot-delegation-completion:',- 'bot-delegation-interaction:',- 'bot-authorization-resume:',-] as const;-const DELEGATION_CONTINUATION = /^bot-delegation-(?:completion|interaction):([^:]+)/;-/** 续跑链(后台任务里又开后台任务……)最多回溯几层;更深按最低档。 */-const MAX_CONTINUATION_HOPS = 4;--const isContinuationClientId = (clientId: string | null | undefined): boolean =>- !!clientId && CONTINUATION_CLIENT_ID_PREFIXES.some((prefix) => clientId.startsWith(prefix));--export interface BotTurnExecution {- executing: boolean;- input: AcceptedTaskInput | null;-}--type RootInput = { clientId: string; originKind: string | null; agentMeta: string | null };--/**- * 一轮的起点:`before` 之前最近一条根用户输入(不含回滚、清空前、自动续跑与上下文重建的行)。- * 没有协调器输入(直接派发、或工具先于派发回执到达)时也用它判断这一轮的来源。- */-async function rootUserInputBefore(- db: Pick<DbClient, 'drizzle'>,- sessionId: string,- before: number | null,-): Promise<RootInput | null> {- const meta = sql`CASE WHEN json_valid(${messages.agentMeta}) THEN ${messages.agentMeta} ELSE '{}' END`;- const [row] = await db.drizzle- .select({- clientId: messages.clientId,- agentMeta: messages.agentMeta,- originKind: sql<string | null>`json_extract(${meta}, '$.origin.kind')`,- })- .from(messages)- .innerJoin(sessions, eq(sessions.id, messages.sessionId))- .where(and(- eq(messages.sessionId, sessionId),- eq(messages.role, 'user'),- isNull(messages.rewindAt),- before === null ? undefined : lt(messages.createdAt, before),- sql`${messages.createdAt} > COALESCE(${sessions.clearedAt}, 0)`,- sql`json_extract(${meta}, '$.parentUuid') IS NULL`,- sql`COALESCE(json_extract(${meta}, '$.autoResume'), 0) != 1`,- sql`COALESCE(json_extract(${meta}, '$.contextRebuild'), 0) != 1`,- ))- .orderBy(desc(messages.createdAt), desc(sql`messages.rowid`))- .limit(1);- return row ? { clientId: row.clientId, originKind: row.originKind ?? null, agentMeta: row.agentMeta ?? null } : null;-}--/** 续跑是哪一轮引出来的:后台任务看它被创建时伙伴那边的那一轮;授权续跑看授权卡之前的那一轮。 */-async function continuationAnchor(- db: Pick<DbClient, 'drizzle'>,- sessionId: string,- clientId: string,-): Promise<{ sessionId: string; before: number | null } | null> {- const delegation = DELEGATION_CONTINUATION.exec(clientId);- if (delegation) {- const [row] = await db.drizzle- .select({ parentSessionId: botDelegations.parentSessionId, createdAt: botDelegations.createdAt })- .from(botDelegations)- .where(eq(botDelegations.id, delegation[1]!))- .limit(1);- return row?.parentSessionId ? { sessionId: row.parentSessionId, before: row.createdAt } : null;- }- const [resume] = await db.drizzle- .select({ createdAt: messages.createdAt })- .from(messages)- .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, clientId)))- .limit(1);- // 续跑消息还没落库时,引出它的就是目前最近的那条根输入。- return { sessionId, before: resume?.createdAt ?? null };-}--/**- * 宿主续跑最多算「主人事先安排」,且不高于引出它的那一轮:主人本人或自动化引出的 → arranged;- * 群聊、其他伙伴、别的任务转来的消息引出的 → other(否则开个后台任务就能把档位抬上去)。- */-async function continuationAuthority(- db: Pick<DbClient, 'drizzle'>,- sessionId: string,- clientId: string,- hops: number,-): Promise<BotTurnAuthority> {- if (!isContinuationClientId(clientId) || hops >= MAX_CONTINUATION_HOPS) return 'other';- const anchor = await continuationAnchor(db, sessionId, clientId);- if (!anchor) return 'other';- const root = await rootUserInputBefore(db, anchor.sessionId, anchor.before);- if (!root) return 'other';- if (isAcceptedUserInputRow(root) || root.originKind === 'scheduler') return 'arranged';- return continuationAuthority(db, anchor.sessionId, root.clientId, hops + 1);-}--/**- * 这一轮开始后,有没有别的任务或伙伴用插话(steer)塞进来的输入。插话进来的内容和这一轮混在一起,- * 不能沿用这一轮起点的档位。主人自己在输入框里插话不带 origin,不算。- */-async function hasForeignSteerSince(- db: Pick<DbClient, 'drizzle'>,- sessionId: string,- turnClientId: string,-): Promise<boolean> {- const [start] = await db.drizzle- .select({ createdAt: messages.createdAt })- .from(messages)- .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, turnClientId)))- .limit(1);- if (!start) return false;- const meta = sql`CASE WHEN json_valid(${messages.agentMeta}) THEN ${messages.agentMeta} ELSE '{}' END`;- const [steer] = await db.drizzle- .select({ clientId: messages.clientId })- .from(messages)- .where(and(- eq(messages.sessionId, sessionId),- eq(messages.role, 'user'),- isNull(messages.rewindAt),- sql`${messages.createdAt} >= ${start.createdAt}`,- sql`json_extract(${meta}, '$.delivery') = 'steer'`,- sql`json_extract(${meta}, '$.origin') IS NOT NULL`,- ))- .limit(1);- return Boolean(steer);-}--export async function resolveBotTurnAuthority(- db: Pick<DbClient, 'drizzle'>,- sessionId: string,- execution: BotTurnExecution,-): Promise<BotTurnAuthority> {- const authority = await resolveTurnStartAuthority(db, sessionId, execution);- const turnClientId = execution.input ? execution.input.retrySourceClientId ?? execution.input.clientId : null;- if (authority !== 'other' && turnClientId && await hasForeignSteerSince(db, sessionId, turnClientId)) return 'other';- return authority;-}--async function resolveTurnStartAuthority(- db: Pick<DbClient, 'drizzle'>,- sessionId: string,- execution: BotTurnExecution,-): Promise<BotTurnAuthority> {- if (await hasAcceptedUserTaskInput(db, sessionId, execution.input)) return 'owner';- const input = execution.input;- const source = input- ? { clientId: input.retrySourceClientId ?? input.clientId, originKind: input.originKind ?? null }- : await rootUserInputBefore(db, sessionId, null);- if (!source) return 'other';- if (source.originKind === 'scheduler') return 'arranged';- return continuationAuthority(db, sessionId, source.clientId, 0);-}--// ── 每个工具的规则(纯函数,单测覆盖) ───────────────────────────────────────--export type BotToolDecision =- | { kind: 'allow' }- | { kind: 'deny'; errorCode: string; message: string }- /** 宿主逐个核对目标任务:`own` 只认伙伴自己的任务;`own-or-handed` 另认已接手项目里的任务。 */- | { kind: 'targets'; sessionIds: string[]; scope: 'own' | 'own-or-handed' };--const OWNER_TURN_REQUIRED = {- kind: 'deny',- errorCode: 'OWNER_TURN_REQUIRED',- message: '这一步只能在主人本人发话的那一轮里做;这一轮来自群聊、其他伙伴、自动化或后台任务回报。先告诉主人,等主人自己说了再做。',-} as const satisfies BotToolDecision;--/** 任何来源都能用:自省、登录、伙伴管理自己的后台任务与消息、沉淀技能,读取自己的资料、能力与例行任务。 */-const ANY_TURN_TOOLS = new Set([- 'get_capabilities',- 'get_current_session_id',- 'start_grok_device_login',- 'get_grok_login_status',- 'cancel_grok_device_login',- 'start_session_task',- 'check_session_task',- 'inspect_session_task_route',- 'advance_session_task_route',- 'message_session_task',- 'stop_session_task',- 'list_agents',- 'send_to_agent',- 'check_agent_message',- 'save_teammate_skill',- 'list_teammate_skills',- 'get_teammate_state',- 'find_teammate_capabilities',- // 旧名别名(bot_capabilities.ts),行为同上。- 'get_bot_state',- 'find_bot_capabilities',- 'get_app_default_model',- 'routine_list',- 'routine_sources',- 'routine_history',- 'schedule_notify_current_run',- 'list_available_models',- // 历史读取:前两档不限范围,最低档由历史范围只给伙伴自己的记录(见 mcp-providers)。- 'list_workdirs',- 'list_sessions',- 'get_chat_history',- 'search_chat_history',-]);--/**- * 读全部、动已接手项目:主人本人与主人事先安排的那两档。例行任务的写入也在这里——例行任务跑起来- * 是 arranged,若 other 那一轮能建例行任务,就能借下一次运行把档位抬上去。- */-const OWNER_OR_ARRANGED_TOOLS = new Set([- 'get_workbench',- 'read_workbench_task',- 'set_workbench_task',- 'set_workbench_tasks',- 'continue_workbench_task',- 'list_projects',- 'create_project',- 'routine_save',- 'routine_delete',- 'routine_run_now',- 'schedule_set_pre_run_hook',-]);--/**- * 按目标任务判定的会话控制工具。`read` = 只读;`currentByDefault` = 省略 session_id 时作用于- * 调用方自己的当前任务(伙伴自己的任务,任何档都可以)。- */-const TARGETED_TOOLS = new Map<string, { read: boolean; currentByDefault?: boolean }>([- ['get_session_runtime', { read: true, currentByDefault: true }],- ['list_session_queue', { read: true }],- ['steer_session', { read: false }],- ['stop_session_turn', { read: false }],- ['set_session_runtime', { read: false, currentByDefault: true }],- ['update_session_queued_message', { read: false }],- ['cancel_session_queued_message', { read: false }],-]);--/** 批量整理任务的工具:从参数里取出全部目标任务,按同样的目标规则判定。 */-const TARGETED_BATCH_TOOLS = new Map<string, (args: unknown) => unknown[] | null>([- ['rename_sessions', (args) => arrayArg(args, 'changes')?.map((change) => stringArg(change, 'session_id')) ?? null],- ['archive_sessions', (args) => arrayArg(args, 'session_ids')],- ['unarchive_sessions', (args) => arrayArg(args, 'session_ids')],-]);--/** 自动化里只读或只作用于本次运行的工具;其余(新建 / 改 / 删 / 暂停 / 立即跑)只在主人本人那一轮。 */-const SCHEDULER_READ_TOOLS = new Set(['schedule_list', 'schedule_get', 'schedule_list_runs']);-const SCHEDULER_CURRENT_RUN_TOOLS = new Set(['schedule_notify_current_run', 'schedule_silence_current_run']);--function stringArg(args: unknown, key: string): string | null {- if (!args || typeof args !== 'object') return null;- const value = (args as Record<string, unknown>)[key];- return typeof value === 'string' && value.trim() ? value.trim() : null;-}--function arrayArg(args: unknown, key: string): unknown[] | null {- if (!args || typeof args !== 'object') return null;- const value = (args as Record<string, unknown>)[key];- return Array.isArray(value) ? value : null;-}--export function decideBotToolCall(- server: 'cindy_helper' | 'cindy_scheduler',- tool: string,- args: unknown,- authority: BotTurnAuthority,-): BotToolDecision {- if (authority === 'owner') return { kind: 'allow' };-- if (server === 'cindy_scheduler') {- if (SCHEDULER_CURRENT_RUN_TOOLS.has(tool)) return { kind: 'allow' };- if (authority === 'arranged' && SCHEDULER_READ_TOOLS.has(tool)) return { kind: 'allow' };- return OWNER_TURN_REQUIRED;- }-- if (ANY_TURN_TOOLS.has(tool)) return { kind: 'allow' };- if (OWNER_OR_ARRANGED_TOOLS.has(tool)) {- return authority === 'arranged' ? { kind: 'allow' } : OWNER_TURN_REQUIRED;- }-- const targeted = TARGETED_TOOLS.get(tool);- if (targeted) {- const sessionId = stringArg(args, 'session_id');- if (!sessionId) {- return targeted.currentByDefault- ? { kind: 'allow' }- : { kind: 'deny', errorCode: 'INVALID_ARGS', message: '缺少 session_id。' };- }- if (authority === 'arranged' && targeted.read) return { kind: 'allow' };- return { kind: 'targets', sessionIds: [sessionId], scope: authority === 'arranged' ? 'own-or-handed' : 'own' };- }-- const batchTargets = TARGETED_BATCH_TOOLS.get(tool);- if (batchTargets) {- const ids = batchTargets(args);- const sessionIds = ids?.map((id) => (typeof id === 'string' ? id.trim() : '')) ?? [];- if (sessionIds.length === 0 || sessionIds.some((id) => !id)) {- return { kind: 'deny', errorCode: 'INVALID_ARGS', message: '缺少目标任务的 session id。' };- }- return { kind: 'targets', sessionIds: [...new Set(sessionIds)], scope: authority === 'arranged' ? 'own-or-handed' : 'own' };- }-- if (tool === 'send_to_session') {- const target = stringArg(args, 'target_session_id');- // 新建任务只在主人本人那一轮;其余档用 start_session_task 开自己的后台任务。- if (!target) return OWNER_TURN_REQUIRED;- return { kind: 'targets', sessionIds: [target], scope: authority === 'arranged' ? 'own-or-handed' : 'own' };- }-- // 其余一律只在主人本人那一轮:新建伙伴、改伙伴自己的资料与能力(持久生效,后台任务回报里可能夹带外部内容)/- // 标签 / 项目改名移除与移动任务 / 改应用默认模型 /- // 接手或移除项目 / 反馈 / 技能发布与学习 / 应用更新,以及将来新增、这里还没登记的工具。- return OWNER_TURN_REQUIRED;-}diff --git a/apps/desktop/src/main/maker-ipc/botWorkbenchAccess.ts b/apps/desktop/src/main/maker-ipc/botWorkbenchAccess.tsindex 5cca9cdd93..fd2809162c 100644--- a/apps/desktop/src/main/maker-ipc/botWorkbenchAccess.ts+++ b/apps/desktop/src/main/maker-ipc/botWorkbenchAccess.ts@@ -4,7 +4,7 @@* 产品裁决(2026-10-01):伙伴可以查看、继续「主人明确交给它的项目」里的任务。* 授权来自主人「交给伙伴」的那一次(工作台里点选,或主人本人那一轮让伙伴记下),范围只限记在* 该伙伴 `workbench.json` 里的项目,主人随时可以移除。停止、插话等动作走通用会话工具,- * 由宿主按「这一轮是谁触发的」逐次判定(见 botTurnAuthority.ts)。+ * 沿用当前 Agent 权限;这里仅验证工作台业务对象与目标状态。** 接手 = 理解,不是搬运:项目是目录。宿主先给每个项目一份有界的素材(文档清单、近期提交与* 分支、我的 PR / issue)和近期会话的摘要(起始目的 + 最后几条),伙伴凭这些一次性写下判断diff --git a/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts b/apps/desktop/src/main/maker-ipc/botWorkbenchTools.tsindex 504b4b857e..54c9257444 100644--- a/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts+++ b/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts@@ -96,17 +96,6 @@ async function resolveWorkbenchCaller(callerSessionId: string): Promise<Workbencreturn { ok: true, botId: row.botId };}-/**- * 这件任务在不在主人交给该伙伴的项目里——与工作台继续同一判据。伙伴用通用会话工具- * 处理「主人事先安排」的一轮时,靠它决定能不能动这件任务(见 botTurnAuthority.ts)。- */-export async function isWorkbenchProjectSession(botId: string, sessionId: string): Promise<boolean> {- const { directories } = await readBotWorkbenchState(ownerScopedUserDataPath(), botId);- if (directories.length === 0) return false;- const target = await readWorkbenchTarget(sessionId);- return authorizeWorkbenchTarget(target, directories, isCaseInsensitivePlatform(process.platform)).ok;-}-async function readWorkbenchTarget(taskId: string): Promise<WorkbenchTargetFacts | null> {const db = getDbClient().drizzle;const [row] = await db@@ -468,8 +457,7 @@ async function runProjectChange<T>(run: () => Promise<T | ProjectFailure>): Prom}/**- * 伙伴按主人的话记下一个已接手项目。只认本机、在用的伙伴主任务;「只有主人本人那一轮能用」- * 由工具调用前的按轮判定保证(botTurnAuthority.ts 未列名的工具默认只放行主人本人那一轮)。+ * 伙伴记下一个已接手项目。工作台需要本机、在用的伙伴主任务;操作沿用当前 Agent 权限。*/export function addBotWorkbenchProjectForCaller(params: { callerSessionId: string; path: string }) {return runProjectChange(async () => {diff --git a/apps/desktop/src/main/maker-ipc/taskToolCallAuthorizer.ts b/apps/desktop/src/main/maker-ipc/taskToolCallAuthorizer.tsnew file mode 100644index 0000000000..d4b8a01f12--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/taskToolCallAuthorizer.ts@@ -0,0 +1,23 @@+import { eq } from 'drizzle-orm';+import type { ToolCallAuthorizer } from '@cindy/mcps';+import type { DbClient } from '../localDb/client/DbClient.js';+import { sessions } from '../localDb/schema.js';++/** Correctness at the Host boundary. Tool permissions belong to the Agent runtime. */+export function createTaskToolCallAuthorizer(deps: {+ getDb(): Pick<DbClient, 'drizzle'> | null;+ isScopeCurrent(db: Pick<DbClient, 'drizzle'>): boolean;+}): ToolCallAuthorizer {+ return async ({ sessionId }) => {+ if (!sessionId) return { ok: false, errorCode: 'CAPABILITY_NOT_AVAILABLE', message: '无法识别调用任务。' };+ const db = deps.getDb();+ if (!db) return { ok: false, errorCode: 'HOST_NOT_READY', message: '任务数据尚未就绪。' };+ const [task] = await db.drizzle.select({ status: sessions.status }).from(sessions)+ .where(eq(sessions.id, sessionId)).limit(1);+ if (!deps.isScopeCurrent(db)) return { ok: false, errorCode: 'OWNER_SCOPE_CHANGED', message: '账号正在切换,请重试。' };+ // Archive changes list visibility; an already-running turn may still finish.+ if (!task || (task.status !== 'active' && task.status !== 'archived'))+ return { ok: false, errorCode: 'TASK_UNAVAILABLE', message: '调用任务已删除或不存在。' };+ return { ok: true };+ };+}diff --git a/apps/desktop/src/main/maker-ipc/teammateGuide.ts b/apps/desktop/src/main/maker-ipc/teammateGuide.tsindex 9fdcb296b1..bc7092a932 100644--- a/apps/desktop/src/main/maker-ipc/teammateGuide.ts+++ b/apps/desktop/src/main/maker-ipc/teammateGuide.ts@@ -32,7 +32,7 @@ export function buildTeammateGuide('The preloaded teammate-guide is itself your shared baseline Skill. When asked which Skills or capabilities you have, identify this shared Skill and distinguish it from optional external references returned by `get_teammate_state`. Empty references or an empty personal shelf never mean that you lack the shared teammate Skill or its operating procedures.','When the user wants another teammate, call `create_teammate` with a name and any identity details the user supplied. New teammates receive this same baseline and follow the user’s available default model; do not generate a fixed number of role Skills, prewrite a greeting, or require a profile form. Their personality, personal learning and memory remain independent.','When the user asks to change the application’s default model, use `get_app_default_model` to read the actual current selection and enabled options, then `set_app_default_model` with the returned id and a supported effort if requested. Check the confirmed result. This changes the same default used by new tasks and following teammates; it does not overwrite existing task choices or explicit teammate/global teammate chains. Do not use this global setter when asked to change only this teammate, edit configuration files, guess providers, enable hidden models, or call an auxiliary model.',- `Use direct teammate tools for your own memory and teammates. When work needs another capability, use \`find_teammate_capabilities\` through the helper’s teammate tools to search existing Skills, MCP connections or built-in tools, then \`set_teammate_capability\` to join it. References reuse existing installations and authorization; do not copy credentials or edit shared sources. New mounts take effect next turn in this same task.${pluginGuidance} Discover only what the work needs; do not repeatedly list the whole tool surface.`,+ `Use \`get_capabilities\` with \`scope: runtime\` to inspect registered tools and explicit availability reasons when needed. Use direct teammate tools for your own memory and teammates. When work needs another capability, use \`find_teammate_capabilities\` through the helper’s teammate tools to search existing Skills, MCP connections or built-in tools, and inspect actual availability. Tools and MCP connections follow Cindy by default; use \`set_teammate_capability\` only to change an explicit selection. References reuse existing installations and authorization; do not copy credentials or edit shared sources. New mounts take effect next turn in this same task.${pluginGuidance} Discover only what the work needs; do not repeatedly list the whole tool surface.`,"A real background task is a standalone Session in the user's task list. Follow the workload split in the `start_session_task` guidance: handle short simple work yourself and proactively start independent tasks for coding and medium or large work. Do not wait for the user to ask for delegation. Use `check_session_task`, `message_session_task`, and `stop_session_task` to control that same task when needed. Completion returns automatically; you remain responsible for reviewing and presenting the result.",'Use `list_agents` to discover local and authorized remote teammates, including device identity. Use the exact returned id; never route by name. Use `send_to_agent` only to send one bounded asynchronous message to a named teammate. It is not a task and has no progress or cancellation. Do not substitute a message to a teammate for `start_session_task`.','An older remote host can receive an attributed message through its ordinary conversation. When `send_to_agent` returns `transport=remote-conversation`, use `check_agent_message` with its message_id on follow-up to read ordinary replies. Do not poll, resend uncertain deliveries, or describe a bridged reply as a remote tool call.',diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.tsindex 228ac8b2a3..e4acec2f8a 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts@@ -270,11 +270,17 @@ describe('codexHttpBridge', () => {}));expect(result).toMatchObject({ result: { content: [{ type: 'text', text: expect.stringContaining('remote-task') }] } });expect(start).toHaveBeenCalledWith(expect.objectContaining({ callerSessionId: 'remote-bot', objective: 'Build the report' }));- // The bridge is shared: a live surface change must not reveal ordinary helper controls.+ // The ordinary remote surface retains Cindy introspection, but not local controls or Bot-only tasks.surface = 'default';expect((await list()).result.tools.map(t => t.name).sort()).toEqual(['call_tool', 'list_tools']);- const categories = await readRpcResponse(await request('tools/call', { name: 'list_tools', arguments: {} }));- expect(categories).toMatchObject({ result: { content: [{ text: expect.stringContaining('"categories":[]') }] } });+ const categories = await readRpcResponse(await request('tools/call', { name: 'list_tools', arguments: {} })) as {+ result: { content: Array<{ text: string }> };+ };+ expect(JSON.parse(categories.result.content[0]!.text).categories).toEqual([{ name: 'cindy', tool_count: 2 }]);+ const introspection = await readRpcResponse(await request('tools/call', {+ name: 'call_tool', arguments: { name: 'get_current_session_id', args: {} },+ }));+ expect(introspection).toMatchObject({ result: { content: [{ text: expect.stringContaining('remote-bot') }] } });await request('tools/call', { name: 'start_session_task', arguments: { instruction: 'denied' } }).then(readRpcResponse);expect(start).toHaveBeenCalledTimes(1);if (agentKind === 'codex') {diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.tsindex 38f99526e7..4529baf02e 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts@@ -196,7 +196,7 @@ describe('collab send outcome semantics', () => {botCapabilities,getMakerMemoryManager: vi.fn(),lspPool: {} as never,- pluginRegistry: { isEnabled: () => false } as never,+ pluginRegistry: { isEnabled: () => false, getPlugins: () => [] } as never,resolveIOSSimulatorAccess: () => ({ allowed: true }),invokeRemote: vi.fn(),});@@ -227,7 +227,7 @@ describe('collab send outcome semantics', () => {botCapabilities,getMakerMemoryManager: vi.fn(),lspPool: {} as never,- pluginRegistry: { isEnabled: () => true } as never,+ pluginRegistry: { isEnabled: () => true, getPlugins: () => [] } as never,resolveIOSSimulatorAccess: () => ({ allowed: true }),invokeRemote: vi.fn(),});@@ -256,7 +256,7 @@ describe('collab send outcome semantics', () => {botCapabilities,getMakerMemoryManager: vi.fn(),lspPool: {} as never,- pluginRegistry: { isEnabled: () => true } as never,+ pluginRegistry: { isEnabled: () => true, getPlugins: () => [] } as never,resolveIOSSimulatorAccess: () => ({ allowed: true }),invokeRemote: vi.fn(),isCurrentLocalSessionInstance,@@ -303,7 +303,7 @@ describe('collab send outcome semantics', () => {botCapabilities,getMakerMemoryManager: vi.fn(),lspPool: {} as never,- pluginRegistry: { isEnabled: () => true } as never,+ pluginRegistry: { isEnabled: () => true, getPlugins: () => [] } as never,resolveIOSSimulatorAccess: () => ({ allowed: true }),invokeRemote: vi.fn(),isCurrentLocalSessionInstance,@@ -500,7 +500,7 @@ describe('collab send outcome semantics', () => {botCapabilities,getMakerMemoryManager: vi.fn(),lspPool: {} as never,- pluginRegistry: { isEnabled: () => true } as never,+ pluginRegistry: { isEnabled: () => true, getPlugins: () => [] } as never,resolveIOSSimulatorAccess: () => ({ allowed: true }),invokeRemote: vi.fn(),});@@ -550,7 +550,7 @@ describe('collab send outcome semantics', () => {botCapabilities,getMakerMemoryManager: vi.fn(),lspPool: {} as never,- pluginRegistry: { isEnabled: () => true } as never,+ pluginRegistry: { isEnabled: () => true, getPlugins: () => [] } as never,resolveIOSSimulatorAccess: () => ({ allowed: true }),invokeRemote: vi.fn(),});@@ -611,7 +611,7 @@ describe('collab send outcome semantics', () => {botCapabilities,getMakerMemoryManager: vi.fn(),lspPool: {} as never,- pluginRegistry: { isEnabled: () => true } as never,+ pluginRegistry: { isEnabled: () => true, getPlugins: () => [] } as never,resolveIOSSimulatorAccess: () => ({ allowed: true }),invokeRemote: vi.fn(),});@@ -669,7 +669,7 @@ describe('collab send outcome semantics', () => {botCapabilities,getMakerMemoryManager: vi.fn(),lspPool: {} as never,- pluginRegistry: { isEnabled: () => true } as never,+ pluginRegistry: { isEnabled: () => true, getPlugins: () => [] } as never,resolveIOSSimulatorAccess: () => ({ allowed: true }),invokeRemote: vi.fn(),});@@ -706,7 +706,7 @@ describe('collab send outcome semantics', () => {botCapabilities,getMakerMemoryManager: vi.fn(),lspPool: {} as never,- pluginRegistry: { isEnabled: () => true } as never,+ pluginRegistry: { isEnabled: () => true, getPlugins: () => [] } as never,resolveIOSSimulatorAccess: () => ({ allowed: true }),invokeRemote: vi.fn(),});diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.tsindex 09ee125907..ec142e8fa3 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/piEnvironment.test.ts@@ -25,6 +25,7 @@ vi.mock('electron', () => ({import type { Logger, McpProvider } from '@cindy/maker-core';import { CustomMcpProvider } from '../custom-mcp-provider.js';import { buildBotMcpCatalog } from '../../maker-host/botMcpCatalog.js';+import { readAgentCapabilityCatalog, RUNTIME_MCP_NAMES_KEY } from '../../maker-host/agentCapabilityCatalog.js';import {CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY,CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY,@@ -321,6 +322,54 @@ describe('piEnvironment per-session identity', () => {config?.disposeSessionCtx?.();});+ it('reports the actual mounted Pi capabilities through the live bridge context', async () => {+ const isEnabled = vi.spyOn(PluginRegistry.prototype, 'isEnabled')+ .mockImplementation((pluginId) => pluginId !== 'collab');+ const providers = ['cindy_helper', 'cindy_memory', 'cindy_docs', 'cindy_computer',+ 'cindy_make', 'cindy_orca', 'custom_probe'].map((name) => makeProvider(name));+ const vendorOptions: Record<string, unknown> = {+ [RUNTIME_MCP_NAMES_KEY]: providers.map((provider) => provider.name),+ [CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY]: ['xdt_helper', 'memory', 'docs', 'collab'],+ [CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY]: ['docs'],+ };+ try {+ const config = await getPiExtraSpawnConfig(providers, noopLogger(), {+ sessionId: 'pi-capability-catalog', workingDir: '/repo', memoryEnabled: false,+ vendorOptions,+ botMcpPolicy: { mode: 'allowlist', configured: ['custom_probe'],+ catalog: [{ name: 'custom_probe', source: 'custom', available: true }] },+ });+ expect(config?.mcpBridge?.servers.map((server) => server.name))+ .toEqual(['cindy_helper', 'custom_probe']);+ const probe = config!.mcpBridge!.servers.find((server) => server.name === 'custom_probe')!;+ const headers = { authorization: `Bearer ${config!.mcpBridge!.token}`,+ accept: 'application/json, text/event-stream', 'content-type': 'application/json' };+ const initialized = await fetch(probe.url, { method: 'POST', headers, body: INIT_BODY(1) });+ const mcpSessionId = initialized.headers.get('mcp-session-id')!;+ await initialized.text();+ const response = await fetch(probe.url, {+ method: 'POST', headers: { ...headers, 'mcp-session-id': mcpSessionId },+ body: JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/call',+ params: { name: 'current_vendor_options', arguments: {} } }),+ });+ const result = await readRpcText(response) as { result: { content: Array<{ text: string }> } };+ const runtimeOptions = JSON.parse(result.result.content[0]!.text);+ expect(runtimeOptions[RUNTIME_MCP_NAMES_KEY]).toEqual(['cindy_helper', 'custom_probe']);+ expect(await readAgentCapabilityCatalog(providers, {+ agentKind: 'pi', workingDir: '/repo', vendorOptions: runtimeOptions,+ }, {})).toMatchObject({ capabilities: [+ { server: 'cindy_helper', status: 'registered' },+ ...['cindy_memory', 'cindy_docs', 'cindy_computer', 'cindy_make', 'cindy_orca'].map((server) => ({+ server, status: 'unavailable', reason: 'not-mounted-in-current-runtime',+ })),+ { server: 'custom_probe', status: 'registered' },+ ] });+ config?.disposeSessionCtx?.();+ } finally {+ isEnabled.mockRestore();+ }+ });+it('keeps native companion helpers available when memory is disabled', async () => {const config = await getPiExtraSpawnConfig([makeProvider('cindy_memory'), makeProvider('cindy_helper'),@@ -706,13 +755,14 @@ describe('piEnvironment per-session identity', () => {});const allowedSecret = 'allowed-remote-secret';const excludedSecret = 'excluded-remote-secret';+ const vendorOptions: Record<string, unknown> = { [CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY]: [] };const config = await getPiExtraSpawnConfig([remoteProvider('allowed_remote', 'ALLOWED_REMOTE_TOKEN', allowedSecret),remoteProvider('excluded_remote', 'EXCLUDED_REMOTE_TOKEN', excludedSecret),], noopLogger(), {sessionId: 'pi-bot-remote-allowlist',workingDir: '/repo',- vendorOptions: { [CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY]: [] },+ vendorOptions,botMcpPolicy: {mode: 'allowlist',configured: ['allowed_remote'],@@ -726,6 +776,7 @@ describe('piEnvironment per-session identity', () => {expect(config?.mcpBridge?.servers.map((server) => server.name)).toEqual(['allowed_remote',]);+ expect(vendorOptions[RUNTIME_MCP_NAMES_KEY]).toEqual(['allowed_remote']);expect(Object.values(config?.mcpEnv ?? {})).toContain(`Bearer ${allowedSecret}`);expect(Object.values(config?.mcpEnv ?? {})).not.toContain(`Bearer ${excludedSecret}`);config?.disposeSessionCtx?.();diff --git a/apps/desktop/src/main/mcp-integrations/helperSurface.ts b/apps/desktop/src/main/mcp-integrations/helperSurface.tsindex 4f65cee559..bcc4da2608 100644--- a/apps/desktop/src/main/mcp-integrations/helperSurface.ts+++ b/apps/desktop/src/main/mcp-integrations/helperSurface.ts@@ -1,14 +1,8 @@import type { DbClient } from '../localDb/client/DbClient.js';import { hasAcceptedUserTaskInput, type AcceptedTaskInput } from '../maker-ipc/pluginTaskInput.js';-/**- * Either legacy ownership signal is enough to keep a caller on the Bot surface.- * Requiring both lets a partial Bot record fall through to the full default- * surface, which includes Session control and history.- *- * A local, active Bot main task (`canonical` link on a `bot` source) is `bot-main`:- * it sees the ordinary surface plus Bot tools, and the host judges every call by- * who triggered the current turn (maker-ipc/botTurnAuthority.ts).+/** Companion tasks add their profile tools to the ordinary transport's helper surface.+ * Classification is a business-object distinction, not a separate permission tier.*/export function classifyHelperSurface(source: string | null | undefined,diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.tsindex 692719550e..c31f84bbdc 100644--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts@@ -18,6 +18,7 @@ import {type LiziMcpProvider,type LiziMcpSessionContext,type LspServerPool,+ type XdtHelperMcpDeps,type SshHostSnapshotLike,} from '@cindy/mcps';import type { OrcaMcpDeps } from '@cindy/mcps';@@ -73,12 +74,11 @@ import {} from '../maker-ipc/botSkillService.js';import {addBotWorkbenchProjectForCaller,- isWorkbenchProjectSession,removeBotWorkbenchProjectForCaller,runBotWorkbenchTool,type BotWorkbenchSendDeps,} from '../maker-ipc/botWorkbenchTools.js';-import { createBotToolCallAuthorizer, resolveBotCallerAuthority } from '../maker-ipc/botToolCallAuthorizer.js';+import { createTaskToolCallAuthorizer } from '../maker-ipc/taskToolCallAuthorizer.js';import {patchSessionMetaInDb,renameSessionTitlesInDb,@@ -106,6 +106,7 @@ import { createSkillhubAgentTools } from '../skillhub/agentTools.js';import { startGrokDeviceLogin, grokDeviceLoginStatus, cancelGrokDeviceLogin } from '../maker-host/grok-device-login-service.js';export interface DesktopMcpProvidersDeps {+ runtimeCapabilities?: XdtHelperMcpDeps['runtimeCapabilities'];botCapabilities: Pick<ReturnType<typeof createBotCapabilityService>, 'list' | 'select'>;createMediaDownloadContext?: CindyGhostsHostDeps['createMediaDownloadContext'];/** 当前 Desktop 版本,供 Forge 为具体插件包生成默认 minCindyVersion。 */@@ -196,19 +197,14 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc},};- // 伙伴主任务的每次调用按「这一轮是谁触发的」判定(maker-ipc/botTurnAuthority.ts)。- const authorizeBotToolCall = createBotToolCallAuthorizer({+ const authorizeTaskToolCall = createTaskToolCallAuthorizer({getDb: () => (isAppSessionBoundaryPending() ? null : tryGetDbClient()),- readExecution: (sessionId) => getSessionInputProvenance(sessionId),- isWorkbenchProjectSession,isScopeCurrent: (db) => !isAppSessionBoundaryPending() && db === tryGetDbClient(),});- /** 伙伴主任务在主人本人或主人事先安排的那一轮里可以读全部历史;其余伙伴调用仍只读自己的记录。 */- const botReadsAccountHistory = async (callerSessionId: string | undefined): Promise<boolean> => {- const dbClient = tryGetDbClient();- if (!dbClient || !callerSessionId || isAppSessionBoundaryPending()) return false;- const caller = await resolveBotCallerAuthority(dbClient, callerSessionId, getSessionInputProvenance);- return caller.kind === 'bot' && caller.main && caller.authority !== 'other';+ // Companion history uses the same account scope as ordinary task history.+ const botReadsAccountHistory = async (sessionId: string | undefined): Promise<boolean> => {+ const result = await authorizeTaskToolCall({ sessionId, server: 'cindy_helper', tool: 'history', args: {} });+ return result.ok;};const withAccountDataAccess = async <T>(sessionId: string | undefined, operation: (assertCurrent: () => Promise<void>) => Promise<T>): Promise<T> => {@@ -347,7 +343,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc},scheduler: {withAccountDataAccess,- authorizeCall: authorizeBotToolCall,+ authorizeCall: authorizeTaskToolCall,getScheduler: () => getScheduler(),// 前置检查脚本统一安装服务:落盘路径/协议/自测与 UI「AI 生成」共用同一实现// (hook-script-generator)。lazy import:该链上有 electron app 依赖,且 maker@@ -477,6 +473,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc// 启动早期跑, 那时 registerMakerIpc 还没执行, holder 是 null; 回调真正被调时// (LLM 调工具时) registerMakerIpc 早已执行完毕, holder 已 ready。xdtHelper: {+ runtimeCapabilities: deps.runtimeCapabilities,appUpdate: {isCurrentSession: (sessionId, sessionInstanceId) =>deps.isCurrentLocalSessionInstance?.(sessionId, sessionInstanceId) === true,@@ -504,14 +501,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc},},sessionTags: async (callerSessionId, request) => {- // 伙伴主任务只在主人本人那一轮能管标签(调用入口已按轮次放行,这里再核一次);- // 伙伴自己的会话仍不出现在标签里。- const dbClient = tryGetDbClient();- const caller = dbClient && callerSessionId && !isAppSessionBoundaryPending()- ? await resolveBotCallerAuthority(dbClient, callerSessionId, getSessionInputProvenance)- : null;- const ownerTurnBot = caller?.kind === 'bot' && caller.main && caller.authority === 'owner';- const result = await executeTaskTags(request, callerSessionId, { trustedBotOwnerTurn: ownerTurnBot });+ const result = await executeTaskTags(request, callerSessionId);return ['update', 'delete'].includes(request.action) ? { ...result, sessions: [] } : result;},createProject,@@ -603,8 +593,8 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc};}},- // 伙伴主任务的每次调用按本轮来源判定;放在 resolveSurface 之前,与工具面分类各自独立。- authorizeCall: authorizeBotToolCall,+ // 共用任务与账号有效性检查;操作权限由当前 Agent 的权限档处理。+ authorizeCall: authorizeTaskToolCall,resolveSurface: async ({ sessionId }) => {const dbClient = tryGetDbClient();if (!dbClient || isAppSessionBoundaryPending()) return 'restricted';@@ -985,11 +975,17 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc// 用 plugin registry gate 包装每个 provider 的 isEnabled。// essential plugin 始终放行;非 essential plugin 按 project → user → default 判定。// provider name(如 'lizi_jira') 会先映射成用户可见的 plugin id(如 'jira')。- const gated = providers.map((p) => {+ const gated: LiziMcpProvider[] = providers.map((p) => {const originalIsEnabled = p.isEnabled;const pluginId = pluginIdForProviderName(p.name);+ const declaration = pluginRegistry.getPlugins().find((entry) => entry.id === pluginId);return {...p,+ capability: {+ title: declaration?.name ?? p.name,+ description: declaration?.description ?? '',+ source: 'builtin' as const,+ },isEnabled: (ctx: LiziMcpSessionContext) => {// Codex 与 Pi 的共享 app-server / bridge 在还没有 thread/workdir 的阶段构建// MCP 工具清单。普通工具必须先全部注册,真正调用时由 HTTP bridge 按新会话@@ -1048,6 +1044,10 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMcgated.push({name: 'cindy',+ capability: {+ title: 'Plugins and media', description: 'Discover installed plugins, their tools, accounts and media capabilities.',+ source: 'builtin', discovery: { tool: 'ghost_list' },+ },isEnabled: () => true,// ctx 闭包进 deps:claude in-process 路径的 tool-call 没有 ALS 语境,// 目录过户(workdir 钳制)与卡片 session 锚定都靠这份按 session 绑定的diff --git a/apps/desktop/src/main/mcp-integrations/piEnvironment.ts b/apps/desktop/src/main/mcp-integrations/piEnvironment.tsindex 39b66e2fd9..50c22739e4 100644--- a/apps/desktop/src/main/mcp-integrations/piEnvironment.ts+++ b/apps/desktop/src/main/mcp-integrations/piEnvironment.ts@@ -62,6 +62,7 @@ import { pluginIdForKnownProviderName } from '../maker-host/plugins/builtin-plug// 从 mcp-integrations 反向 import 会成环。import { createPluginRegistry } from '../maker-host/plugins/index.js';import { isAllowedRemoteMcpUrl, isDesktopLoopbackMcpUrl } from './piMcpTransport.js';+import { RUNTIME_MCP_NAMES_KEY } from '../maker-host/agentCapabilityCatalog.js';interface StartedPiBridge {bridge: CodexHttpBridge | null;@@ -162,6 +163,8 @@ export async function getPiExtraSpawnConfig(logger: MakerLogger,sessionCtx?: PiExtraSpawnConfigContext,): Promise<PiExtraSpawnConfig | null> {+ const vendorOptions = sessionCtx ? (sessionCtx.vendorOptions ??= {}) : {};+ vendorOptions[RUNTIME_MCP_NAMES_KEY] = [];const started = await ensureBridge(providers, logger);if (!started) return null;// JS 同步段内完成“确认未退役 + 加 lease”,invalidate 不会插进中间。@@ -228,16 +231,13 @@ export async function getPiExtraSpawnConfig(// It has no plugin id on purpose — empty ghost_list, not a missing server.// Frozen Bot allowlists therefore must not treat it as an unknown host provider.if (server.name === 'cindy') return true;- // A frozen Bot runtime may use explicitly configured custom MCPs, but it- // must not inherit miscellaneous host providers merely because the shared- // Pi bridge knows about them. Unknown providers absent from the Bot's- // custom catalog are therefore hidden from discovery and execution.+ // Use the exact frozen capability snapshot for every provider, including+ // shared host providers without an optional toolset id.if (allowedPluginIds) {const policy = sessionCtx?.botMcpPolicy;const entry = policy?.catalog.find((item) => item.name === server.name);- if (!entry || entry.source !== 'custom' || entry.available === false) return false;- // `inherit` is a legacy storage value for Bots, not ambient access.- // External MCPs are always exact grants at the execution boundary.+ if (!entry || entry.available === false) return false;+ // Inheritance was resolved at session preparation, keeping this turn stable.return policy?.configured.includes(server.name) === true;}return true;@@ -245,16 +245,21 @@ export async function getPiExtraSpawnConfig(// The legacy flag enables companion facades; the bridge separately checks// whether memory is mounted. Helper capabilities must survive memory being off.- const withBotMemoryFacade = (+ const buildSessionBridge = (servers: NonNullable<PiExtraSpawnConfig['mcpBridge']>['servers'],- ): NonNullable<PiExtraSpawnConfig['mcpBridge']> => ({- token: bridge?.token ?? '',- servers,- ...((sessionCtx?.botMcpPolicy || sessionCtx?.memoryScopeKey?.startsWith('bot:'))- && servers.some((server) => server.name === 'cindy_memory' || server.name === 'cindy_helper')- ? { botMemoryFacade: true }- : {}),- });+ ): NonNullable<PiExtraSpawnConfig['mcpBridge']> => {+ // The catalog and live bridge context share this runtime's actual descriptor,+ // after toolset, MCP, session and transport filtering. Do not rederive policy.+ vendorOptions[RUNTIME_MCP_NAMES_KEY] = servers.map((server) => server.name);+ return {+ token: bridge?.token ?? '',+ servers,+ ...((sessionCtx?.botMcpPolicy || sessionCtx?.memoryScopeKey?.startsWith('bot:'))+ && servers.some((server) => server.name === 'cindy_memory' || server.name === 'cindy_helper')+ ? { botMemoryFacade: true }+ : {}),+ };+ };// 匿名会话:不注册身份、URL 不带 query。工具 handler 拿不到 ctx 时回落业务// 错误码(如 LEAD_NOT_SUPPORTED)—— 与改动前一致,不打 401。@@ -265,7 +270,7 @@ export async function getPiExtraSpawnConfig(]);return {mcpBridge: {- ...withBotMemoryFacade(servers),+ ...buildSessionBridge(servers),},mcpEnv: selectMcpEnvForServers(servers, mcpEnv),disposeSessionCtx: disposeLease,@@ -278,7 +283,7 @@ export async function getPiExtraSpawnConfig(const servers = capabilityGated(cloneRemoteServers(remoteServers));return {mcpBridge: {- ...withBotMemoryFacade(servers),+ ...buildSessionBridge(servers),token: '',},mcpEnv: selectMcpEnvForServers(servers, mcpEnv),@@ -293,7 +298,6 @@ export async function getPiExtraSpawnConfig(// PiAgent 传入的是该 session 专属的可变副本。这里必须保留同一引用:start_team// 成功后 MakerSession.setVendorOptions 会原地写入 Lead 身份,既有 HTTP MCP handler// 要在下一次 create_worker 调用时立即看到。复制对象会把 bridge 永久冻结在启动态。- const vendorOptions = sessionCtx?.vendorOptions ?? {};vendorOptions[CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY] = disabledPluginIds;if (allowedPluginIds) {vendorOptions[CODEX_ALLOWED_BUILTIN_PLUGIN_IDS_KEY] = allowedPluginIds;@@ -349,7 +353,7 @@ export async function getPiExtraSpawnConfig(]);return {mcpBridge: {- ...withBotMemoryFacade(servers),+ ...buildSessionBridge(servers),token: sessionToken,},mcpEnv: selectMcpEnvForServers(servers, mcpEnv),diff --git a/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx b/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsxindex 6ec64f77ac..b99bd2e4fe 100644--- a/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx+++ b/apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx@@ -165,7 +165,7 @@ export function BotCapabilitySettings({}));if (toolsetResult.status === 'fulfilled')next.toolset = toolsetResult.value- .filter((item) => !['memory', 'xdt_helper', 'scheduler', 'collab'].includes(item.id))+ .filter((item) => !['memory', 'xdt_helper', 'scheduler', 'lsp'].includes(item.id)).map((item) => ({id: item.id,name: item.name,@@ -239,6 +239,13 @@ export function BotCapabilitySettings({const rows = [...(entries[kind] ?? [])];for (const id of selected[kind])if (!rows.some((item) => item.id === id)) rows.push({ id, name: id, available: false });+ const mode = kind === 'mcp' ? capabilities.mcpMode : kind === 'toolset' ? capabilities.toolsetMode : 'allowlist';+ // Inheritance can only become an explicit selection from a complete+ // catalog of this kind. Missing/refreshing entries must not drop tools.+ const canEdit = mode !== 'inherit' || entries[kind] !== undefined;+ const selectedIds = mode === 'inherit'+ ? [...new Set([...selected[kind], ...rows.filter((item) => item.available).map((item) => item.id)])]+ : selected[kind];const matching = rows.filter((item) =>`${item.id} ${item.name}`.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase()),);@@ -256,14 +263,14 @@ export function BotCapabilitySettings({<inputtype="checkbox"className="accent-[var(--text-primary)]"- checked={item.personal ? item.available : selected[kind].includes(item.id)}- disabled={item.personal || (!item.available && !selected[kind].includes(item.id))}+ checked={item.personal ? item.available : selectedIds.includes(item.id)}+ disabled={!canEdit || item.personal || (!item.available && !selectedIds.includes(item.id))}onChange={(event) =>- onChange(+ canEdit && onChange(kind,event.target.checked- ? [...selected[kind], item.id]- : selected[kind].filter((id) => id !== item.id),+ ? [...selectedIds, item.id]+ : selectedIds.filter((id) => id !== item.id),)}/>diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botCapabilitySettings.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botCapabilitySettings.test.tsxindex 0ef8e95204..32b33f87a1 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botCapabilitySettings.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/botCapabilitySettings.test.tsx@@ -1,5 +1,5 @@// @vitest-environment jsdom-import { cleanup, render, waitFor } from '@testing-library/react';+import { cleanup, fireEvent, render, waitFor } from '@testing-library/react';import { afterEach, describe, expect, it, vi } from 'vitest';import type { BotProfile } from '../botStore';@@ -65,3 +65,75 @@ describe('controlled capability page lifetime', () => {await waitFor(() => expect(h.list).toHaveBeenCalledTimes(2));});});+++it('shows inherited tools as selected and preserves the others when one is explicitly removed', async () => {+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: {+ localDb: { sessionsPush: { onPatched: () => h.offPush }, bots: { listSkills: async () => [] } },+ maker: { onMcpChanged: () => h.offMcp, listCustomMcpServers: h.list,+ listAgentSkills: async () => ({ success: true, skills: [] }),+ plugins: { list: async () => [+ { id: 'docs', name: 'Documents', available: true },+ { id: 'collab', name: 'Orca', available: true },+ ] },+ },+ } });+ const onChange = vi.fn();+ const view = render(<BotCapabilitySettings expanded+ bot={{ id: 'bot-1', canonicalSessionId: 's1' } as BotProfile}+ capabilities={{ modelChain: [], modelChainOverride: null, mcpServers: [], toolsets: [],+ toolsetMode: 'inherit', mcpMode: 'inherit' } as unknown as BotProfile['capabilities']}+ skills={[]} onChange={onChange} />);+ await waitFor(() => expect(view.getByText('Documents')).toBeTruthy());+ const checkbox = (name: string) => view.getByText(name).closest('label')!.querySelector('input')!;+ expect(checkbox('Documents').checked).toBe(true);+ expect(checkbox('Orca').checked).toBe(true);+ fireEvent.click(checkbox('Documents'));+ expect(onChange).toHaveBeenCalledWith('toolset', ['collab']);+});++it.each(['mcp', 'toolset'] as const)('preserves inherited %s tools until its failed catalog is retried', async (kind) => {+ let recovered = false;+ const entries = [+ { id: 'saved', name: 'Saved capability', available: true },+ { id: 'inherited', name: 'Other inherited capability', available: true },+ ];+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: {+ localDb: { sessionsPush: { onPatched: () => h.offPush }, bots: { listSkills: async () => [] } },+ maker: {+ onMcpChanged: () => h.offMcp,+ listCustomMcpServers: async () => {+ if (kind === 'mcp' && !recovered) throw new Error('MCP catalog unavailable');+ return { agentKind: 'pi', servers: kind === 'mcp' ? entries : [] };+ },+ listAgentSkills: async () => ({ success: true, skills: [] }),+ plugins: { list: async () => {+ if (kind === 'toolset' && !recovered) throw new Error('Tool catalog unavailable');+ return kind === 'toolset' ? entries : [];+ } },+ },+ } });+ const onChange = vi.fn();+ const view = render(<BotCapabilitySettings expanded+ bot={{ id: 'bot-1', canonicalSessionId: 's1' } as BotProfile}+ capabilities={{ modelChain: [], modelChainOverride: null,+ mcpServers: kind === 'mcp' ? ['saved'] : [], toolsets: kind === 'toolset' ? ['saved'] : [],+ toolsetMode: 'inherit', mcpMode: 'inherit' } as unknown as BotProfile['capabilities']}+ skills={[]} onChange={onChange} />);+ const saved = () => view.getByRole('checkbox', { name: /saved/ }) as HTMLInputElement;+ expect(saved().disabled).toBe(true);+ await waitFor(() => expect(view.getByRole('button', { name: 'bots.retry' })).toBeTruthy());+ expect(saved().checked).toBe(true);+ expect(saved().disabled).toBe(true);+ fireEvent.click(saved());+ expect(onChange).not.toHaveBeenCalled();++ recovered = true;+ fireEvent.click(view.getByRole('button', { name: 'bots.retry' }));+ await waitFor(() => expect(view.getByText('Other inherited capability')).toBeTruthy());+ const loaded = view.getByRole('checkbox', { name: 'Saved capability' }) as HTMLInputElement;+ expect(loaded.disabled).toBe(false);+ expect((view.getByRole('checkbox', { name: 'Other inherited capability' }) as HTMLInputElement).checked).toBe(true);+ fireEvent.click(loaded);+ expect(onChange).toHaveBeenCalledExactlyOnceWith(kind, ['inherited']);+});diff --git a/apps/desktop/src/renderer/features/bots/botStore.ts b/apps/desktop/src/renderer/features/bots/botStore.tsindex 8538524aa4..00e397a50e 100644--- a/apps/desktop/src/renderer/features/bots/botStore.ts+++ b/apps/desktop/src/renderer/features/bots/botStore.ts@@ -457,13 +457,12 @@ function defaultCapabilities(harness: primary.harness,modelChain: globalChain,modelChainOverride: null,- // A Bot starts with its own/profile capabilities, not the entire Cindy- // environment. Explicit grants remain available through the advanced UI.+ // Share ordinary Agent tools; retain the companion’s own learned Skills.skillMode: 'allowlist',skillsExcluded: [],- toolsetMode: 'allowlist',+ toolsetMode: 'inherit',toolsets: [],- mcpMode: 'allowlist',+ mcpMode: 'inherit',mcpServers: [],memory: true,// 新建伙伴默认放手做(产品裁决 2026-08-18)。**只作用于「新建」**:读取既有diff --git a/apps/desktop/src/shared/botCapabilitySelection.ts b/apps/desktop/src/shared/botCapabilitySelection.tsindex c1e14285e4..ac5f45c51e 100644--- a/apps/desktop/src/shared/botCapabilitySelection.ts+++ b/apps/desktop/src/shared/botCapabilitySelection.ts@@ -10,3 +10,20 @@ export function reconcileBotCapabilityList(previous: string[], local: string[],...local.filter((id) => !baseline.has(id)),])];}++/**+ * Legacy lists do not distinguish generated defaults from user selections.+ * The shared-capability migration intentionally opens every legacy list while+ * retaining its references. Choices saved under version 1, including empty+ * allowlists, remain explicit restrictions on subsequent loads.+ */+export function normalizeBotToolCapabilities(config: Record<string, unknown>): Record<string, unknown> & {+ toolCapabilityVersion: 1; toolsetMode: 'inherit' | 'allowlist'; mcpMode: 'inherit' | 'allowlist';+} {+ if (config.toolCapabilityVersion === 1) return {+ ...config, toolCapabilityVersion: 1,+ toolsetMode: config.toolsetMode === 'allowlist' ? 'allowlist' : 'inherit',+ mcpMode: config.mcpMode === 'allowlist' ? 'allowlist' : 'inherit',+ };+ return { ...config, toolCapabilityVersion: 1, toolsetMode: 'inherit', mcpMode: 'inherit' };+}diff --git a/docs/dev-rules/agent-capabilities.md b/docs/dev-rules/agent-capabilities.mdnew file mode 100644index 0000000000..5a403b8aa6--- /dev/null+++ b/docs/dev-rules/agent-capabilities.md@@ -0,0 +1,62 @@+# Agent 能力声明与伙伴继承++伙伴和普通 Agent 复用已有工具实现、注册和权限档。新增一个工具,不需要再登记伙伴来源分档、底层调用口或另一份 `control_session` 操作表。++## 声明放在哪里++- 内置 MCP:在现有 `createLiziMcpProviders` / Desktop provider 注册处声明。`capability` 元数据可提供名称、说明、来源和渐进发现入口;实际工具名称、参数、说明仍从 MCP 注册读取。+- 插件:沿插件自己的 manifest 和 `ghost_list → ghost_info → ghost_call` 发现,不复制为另一套工具。+- 自定义 MCP:沿现有连接配置及引擎 MCP 发现。目录查询不会另起进程或读出 URL、headers、token。+- 命令行、文件、原生子 Agent:由当前引擎提供。伙伴不再额外禁用;运行时能力摘要和引擎实际提供的工具共同表达可用范围。+- Skill:仍使用既有安装、发现和伙伴自有 Skill 学习体系。工具全部继承不意味着覆盖伙伴人格、共享个人记忆或将全部 Skill 正文塞入上下文。++## 如何查询++调用已有 `cindy_helper` 的 `get_capabilities`:++```json+{ "scope": "runtime" }+```++返回当前 Agent 的 provider 目录、注册/不可用状态、原因、权限档及宿主交互能力摘要。`registered` 表示注册及入口条件满足,不代表外部服务已连通。++```json+{ "scope": "runtime", "server": "cindy_helper", "category": "control" }+```++读取内置 server 的真实 schema 与渐进目录。没有 `scope` 时保留原产品说明查询行为。宿主交互能力不等于 Agent 已有可调用接口;例如应用安装更新、重启没有正式 Agent 接口,`check_app_update` 只查询当前更新渠道。++## 伙伴默认配置++```json+{+ "toolCapabilityVersion": 1,+ "toolsetMode": "inherit",+ "mcpMode": "inherit"+}+```++新伙伴默认继承 Cindy 已启用的工具和连接,创建时的显式选择优先。读取或导入旧配置时,空和非空工具允许名单都统一升级为继承,工具集与 MCP 一致,旧引用不删除。`toolCapabilityVersion: 1` 下的明确选择(包括主动清空的名单)均保留,后续读取不会再次放开。配置变更继续沿同任务轮次边界刷新,已开始的一轮保持冻结快照。++2026-10-02 产品确认:旧格式没有可靠记录名单来自用户还是系统;AI 创建、导入也会生成非空名单。用户确认旧名单统一放开,不再用空/非空猜测用户是否设置过。此迁移也会放开旧版真正手选过的限制;升级后仍可重新选择,并按新声明语义持久保留。++现有 ask / auto / 完全访问保持原值,全局停用、平台/引擎不支持和连接缺失如实报告。所有伙伴共享这套解释规则,不按名字或数量逐个适配。++## 权限与正确性++权限继续由 Agent 配置、统一审批以及普通工具的公共入口处理。删除伙伴单独的 owner / arranged / other 工具分档。账号切换、过期实例、目标不存在、队列消息归属、对象操作条件仍须校验;插件自身的面板/后台入口保留其已有授权,不因没有 Agent 在场就获得 Agent 权限。++已知边界:群专线、其他伙伴及自动化转来的消息,沿用该 Agent 的能力与权限档,目前没有按触发来源整轮降低权限的实现。若该 Agent 配置为完全访问,这些来源也沿用完全访问;现有公共审批不能被描述为已经实现来源隔离。本次不自动更改用户的权限档,后续如区分来源,应在 Agent 执行层统一处理,而不是恢复逐工具分档。++调用任务的归档状态不是停止信号:已有运行轮次在归档后仍可调用 helper 和自动化工具;共享入口拒绝缺失、已删除的调用任务和失效账号。具体操作仍保留各自的目标状态要求。++伙伴自己的资料、工作台、群记录等仍有具体业务对象;普通任务没有伙伴资料,远程工作目录也不能冒充本机工作台。查询目录和执行操作必须返回真实结果,不把未连接当成权限拒绝,不把宿主内部方法写成公开工具。++## 回归入口++- `botCanonicalSession.test.ts`:创建、存量配置、同任务刷新、跨引擎/远端可用性和能力修改。+- `botProfileVersioning.test.ts`:旧名单升级、保留权限档、显式选择的幂等保存。+- `botCapabilitySettings.test.tsx`:默认全选及主动取消后的其他能力保留。+- `agentCapabilityCatalog.test.ts`:真实 SDK schema、渐进目录、未挂载原因和外部连接不被重复启动。+- `lizi_xdtHelperMcpServer.test.ts`:普通任务/伙伴使用同一个能力查询和通用任务工具。+- 三个引擎各自的伙伴启动回归:没有伙伴专属的原生子 Agent 禁用参数。diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex eb29b7d515..d8fc8979d3 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -190,9 +190,9 @@ harness + provider + model + effort + fastMode轻量不等于没有 Skill。伙伴启动时按以下优先级构造能力:1. 伙伴家目录中的自有 / 后学 Skill;-2. 用户在伙伴设置里明确授予的工具集或 MCP;+2. 与普通 Agent 共用的内置工具集、已连接 MCP 和插件,默认全部继承;3. Cindy 已安装的插件、Skill、MCP 与内置工具可以按需发现并复用。默认不灌入全量- Skill、MCP schema 或插件花名册;伙伴通过轻量入口搜索,再引用需要的能力。+ Skill 正文、MCP schema 或插件详细说明;伙伴通过轻量入口查询真实声明,再按需展开。- Skill / MCP / 工具集引用保存在各伙伴自己的 Profile,复用共享源的安装与连接;加入或移除不修改共享源、凭证或全局开关。配置改变后在同一主任务的安全轮次边界重建能力快照,不要求新建任务。@@ -206,10 +206,9 @@ harness + provider + model + effort + fastMode- **提示词承诺必须等于工具面**。能力说明按实际挂载的工具集逐块注入(挂了 docs 才讲怎么做文档),且挂载必须真实生效:显式挂载 docs 工具集时,运行时把 `cindy_docs` 写进该伙伴的 MCP allowlist——不允许出现「提示词说有、运行时够不到」或反向的错位。-- 伙伴的 harness 会话不得加载项目或全局 `AGENTS.md` / `CLAUDE.md`,不得暴露 harness 原生- subagent 面(pi 的 `subagent` 工具、cc 的 `Task`),也不得继承 Cindy 完整 system prompt、- 全量 Skill 清单或全量 MCP schema。-- 普通伙伴不能启动 Orca / Team Worker。需要独立执行的工作走 Cindy Session 任务(见 6.1)。+- 伙伴保留自己的身份、记忆与 Skill 上下文,不加载项目或全局 `AGENTS.md` / `CLAUDE.md` 替代人格。+ 这不限制工具能力:Pi / Claude Code / Codex 的原生子 Agent 与普通任务相同;Orca 也不因伙伴身份禁用,+ 仍遵循用户的全局开关、当前引擎支持与权限档。持久后台工作仍可使用 Cindy Session 任务(见 6.1)。- 伙伴主动为用户积累记忆和 Skill,不以用户明确要求为前提。清晰稳定的偏好、纠正与长期背景第一次出现就记;每次纠正做法、指定可复用格式或完成有价值的任务后,主动整理格式与已验证的做法,形成或改进个性化 Skill。一次已经验证且明显可复用的成功也可立即沉淀,不设轮次数或 Skill 数量配额。@@ -263,10 +262,10 @@ harness + provider + model + effort + fastMode恢复后只生效一次,取消优先撤销暂存回答。恢复依据宿主实际应用回执清理等待状态,已应用的回答不再通知发起伙伴;确实未答的交互仍重新通知。渠道卡片的回答状态不表示引擎已恢复。这些模式都只作用于调用伙伴拥有的后台任务。本机伙伴主任务另外拿到和普通任务同一套通用 Session- 工具,能做多少由宿主按这一轮是谁触发的逐次判定,见 6.4。+ 工具,沿用当前 Agent 的权限档,见 6.4。主人通过工作台交给伙伴的项目里的原有任务,另走 6.3 的工作台工具,不经过这些后台任务入口。伙伴可以登记、列出、重命名和隐藏账号项目,也可以把已有的非伙伴任务移入或移出项目。- 移动任务必须已经持有该任务的 session id,不能按标题枚举其他任务。远程伙伴不获得这些工具。+ 移动任务先用 `list_sessions` 找到 session id,再走普通任务的移动规则;SSH 任务仍受该传输的能力范围约束。群专线、历史等伙伴非主任务与远程伙伴仍不包含停止、插话、改运行时、改名、归档、标签或读取其他任务的历史与输入队列;本机伙伴主任务按 6.4 获得这些能力。`check_session_task.control.last_stop_request` 保留最近一次优雅停止请求的时间、返回状态和轮次;@@ -443,7 +442,7 @@ Session 任务遵守同一套机制与呈现契约:### 6.3 工作台:主人交给伙伴的项目2026-10-01 产品裁决(用户已同意):伙伴可以查看、继续「用户明确交给它的项目」里的任务(停止走通用的-`stop_session_turn`,按 6.4 逐轮判定)。2026-10-02 起工作台是伙伴的「负责范围」:不设项目数上限,主人可以口头交代。+`stop_session_turn`,沿用当前 Agent 权限)。2026-10-02 起工作台是伙伴的「负责范围」:不设项目数上限,主人可以口头交代。同日用户实机试用后多次修订,最终口径:1. **接手 = 理解,不是搬运**——伙伴先读懂项目里已有的工作,写下判断;主人点头(或点「跟进」)的那一件才@@ -454,7 +453,7 @@ Session 任务遵守同一套机制与呈现契约:过没有都在工作台上、也都在 `get_workbench` 里;只有还没导入的外部会话要等伙伴判断后才上工作台。- **授权来源**:只来自主人的「交给<伙伴>」——在伙伴工作台里点选,或主人本人那一轮口头交代、伙伴用- `add_workbench_project` 记下(只在主人本人发话的那一轮可用,见 6.4;只收存在的绝对路径目录,不收磁盘根目录、+ `add_workbench_project` 记下(沿用当前 Agent 权限,见 6.4;只收存在的绝对路径目录,不收磁盘根目录、主目录与 Cindy 数据目录,符号链接按它指向的真实目录同样判定)。宿主把项目目录记在该伙伴 Home 的 `workbench.json`(`directories`,去重;不设产品上限,只有 50 个的防护上限),主人可以随时在工作台上移除,或让伙伴用 `remove_workbench_project`移除,移除即收回,项目里的任务、文件与伙伴写过的判断都不动。工具不接受 botId。移除在进行中的调用里同样@@ -514,7 +513,7 @@ Session 任务遵守同一套机制与呈现契约:拿不准的几件 `read_workbench_task`;判断要体现对项目的理解,不只复述会话;文档、最近的 PR 与 issue 同样是素材。主人提到项目、让跟进或问进展时先看工作台。写完后在聊天里用几句话告诉主人没做完的几件与值得做的几件,问主人接着做哪件,不自作主张开始做。只有本机、在用的伙伴主任务可以调用;远程- 伙伴不提供工作台。读写工作台与继续任务只在主人本人与主人事先安排的那两档可用(6.4)。+ 伙伴不提供工作台。读写工作台与继续任务沿用当前 Agent 权限(6.4)。- **校验位置**:每次调用在 main 里确定性校验(`maker-ipc/botWorkbenchAccess.ts`),越权返回明确错误码且不读、不写、不投递;工作台详情视图读同一份摘录时也按该伙伴已接手的项目判定范围。- **工作台显示什么**:已接手项目里最近 30 天的 Cindy 任务一律列出——包括主人自己开的、伙伴还没判断过的;@@ -560,51 +559,37 @@ Session 任务遵守同一套机制与呈现契约:并展开右侧栏;伙伴聊天头部常驻「工作台」入口,标签被关掉后可重新打开;伙伴页保留全局右侧栏的其它能力。Mobile 与远程伙伴暂不提供。-### 6.4 伙伴主任务的 session 能力:按这一轮是谁触发的判定--2026-10-02 产品裁决(用户已同意):本机伙伴主任务和普通任务拿同一套 session 工具——查看全部任务并读全文,-发消息、插话、停止,开新任务、选模型,归档、改名、打标签,建普通自动化。伙伴不再比普通任务「权限更低」。--- **工具列表在整个会话里不变**(前缀缓存规则):本机伙伴主任务的 `cindy_helper` 是普通任务的全部类目加- `bots` 类目;伙伴基线挂载 `memory`、`xdt_helper` 与 `scheduler`(`maker-host/plugins/types.ts`)。- 能做多少不靠增删工具,而是每次调用时由宿主判定(`maker-ipc/botTurnAuthority.ts`、- `maker-ipc/botToolCallAuthorizer.ts`),判档只看宿主持有的事实,不看模型说了什么。-- **三档**:- - **主人本人**:主人在伙伴聊天里的输入(桌面、手机、同账号设备,含工作台按钮代发),由可信输入通道盖章,- 判据与插件任务「真人接管」共用 `hasAcceptedUserTaskInput`。= 全套。- - **主人事先安排**:自动化 / 例行任务的运行、伙伴自己开的后台任务回报或等待交互、账号授权完成后的续跑。- = 读全部任务与历史;只动自己开的任务和已接手项目里的任务;不新建、不修改自动化,不改账号设置- (应用默认模型、项目改名移除与移动任务等),不接手或移除项目,不新建伙伴、不改自己的资料与能力(回报里可能- 夹带网页等外部内容,不能让它永久改变伙伴)。可以写例行任务与工作台判断、登记新项目。- - **其它**:其他伙伴的消息、别的任务转来的消息,以及认不出来的。= 只动自己开的任务、只读自己的记录- (伙伴的 session 与它开的后台任务);不新建伙伴,不改自己的资料与能力(这些持久生效,不能由别的来源引出)。-- **插话不沿用档位**:这一轮开始后若有别的任务或伙伴用插话(steer)塞进输入,这一轮按「其它」判定;- 主人自己在输入框插话不算。伙伴私信、群消息、授权续跑一律排队成新的一轮,不会插进正在跑的那一轮。-- **续跑不抬档**:后台任务回报、等待交互与授权续跑本身不是主人说的话,可信程度不高于引出它们的那一轮——- 由主人本人或自动化引出的算「主人事先安排」,由「其它」那一轮引出的仍是「其它」(否则开个后台任务就能- 抬档)。回溯最多 4 层,更深按「其它」。-- **按目标判定的动作**:停止、插话、改运行时、改排队消息、给已有任务发话、改名、归档 / 取消归档,在后两档逐个- 核对目标任务(「主人事先安排」认自己的任务与已接手项目里的任务,「其它」只认自己的任务),批量里有一件越界就整批拒绝。- 开新任务、打标签、项目整理(改名 / 移除项目、移动任务)、改应用默认模型、接手或移除工作台项目、新建伙伴、- 改伙伴自己的资料与能力只在主人本人那一轮。-- **默认拒绝**:判定表里没有登记的工具(含将来新增的)只在主人本人那一轮放行。被拒返回- `OWNER_TURN_REQUIRED` 或 `TASK_OUT_OF_SCOPE`,伙伴照实告诉主人、等主人自己说,不换工具绕过。-- **「自己开的任务」**:该伙伴的 `bot_session_links` 与它开的后台任务(`bot_delegations.child_session_id`)。- 「已接手项目里的任务」与工作台继续同一判据(`isWorkbenchProjectSession`)。-- **历史范围**:前两档读全部历史(`list_sessions` / `get_chat_history` / `search_chat_history` 与记忆的- 会话搜索);「其它」档只读自己的记录,含自己开的后台任务的转录。-- **不变的部分**:远程伙伴、群专线与历史等伙伴非主任务保持原来的窄能力面且不按轮判定;唯一例外是自动化——- 它在这台电脑上(远程 Pi 经隧道挂到),远程伙伴调用时同样按本节分档。普通任务操作伙伴 session 的方式不变(标签仍不打到伙伴的任务上)。保留语义独特的伙伴工具- (`start/check/message/stop_session_task`、路由工具、`continue_workbench_task`、`read_workbench_task`、- `get_workbench`、`set_workbench_task(s)`),只删掉纯重复的 `stop_workbench_task`。-- **这不是安全边界**:分档防的是伙伴误操作、以及别的来源借伙伴的会话工具动主人的任务;它不是沙箱。伙伴主任务- 本身有命令行等原生工具(沿用普通任务权限),开出的后台任务也是能力完整的普通任务(6.1),这些都不受本节分档- 约束。提示词明确要求伙伴被拒后不换工具、不开后台任务、不用命令行、不请别的伙伴去做被拒的事。判定入口认不出- 调用方(拿不到 session)时一律拒绝。-- **范围是这台电脑**:伙伴看得到、管得了的是这台电脑上 Cindy 记录的任务;别的电脑上的任务看不到,远程伙伴(在别的- 电脑上运行的伙伴)没有这套能力;工作台不收 SSH 远程任务。跨电脑另行设计。-- **提示词**:伙伴主任务的「你会做什么」里加「你能看、能管主人的任务」(三档与被拒怎么办)和- 「你能建普通自动化」(只在主人本人那一轮)两块,只在本机主任务注入。+### 6.4 伙伴与普通 Agent 共用能力声明和权限++声明位置、查询与维护见 [Agent 能力声明](../dev-rules/agent-capabilities.md)。++2026-10-02 修订:工具能力与普通任务共用,不再按伙伴输入的来源维护第二套逐工具权限表。++- 新伙伴默认继承 Cindy 已启用的工具集和已连接的 MCP,创建时的显式选择优先;插件继续复用共享网关。+ 旧 Profile 的空和非空允许名单都升级为继承,工具集与 MCP 一致。+ 旧格式无法可靠区分用户手选和系统生成;2026-10-02 用户确认统一放开,包括旧版真正手选的限制。+ 连接引用、身份、记忆和用户选择的权限档保持原值。+ `toolCapabilityVersion: 1` 标记新的声明语义;此后的明确选择(包括空允许名单)照常生效。+- 能力目录来自运行时 provider 注册,不手抄工具数量或另维护底层调用口登记表。+ `get_capabilities(scope: runtime)` 返回当前引擎的注册项、启用状态及未挂载原因;指定 `server` 读取+ 真实工具 schema,内置渐进目录可继续按 `category` 展开。插件和外部 MCP 沿原有发现入口展开,+ 不为查目录额外启动外部进程,也不暴露连接凭证。+- 本地伙伴的 helper 使用普通任务类目加伙伴类目;远程任务遵循该引擎与传输本来支持的普通能力面。+ 新工具随注册进入共享目录和默认继承范围,不再要求登记“只有主人那一轮可用”。+- 权限由 Agent 的 ask / auto / bypassPermissions 和现有工具组配置统一处理,包含命令行、文件与 MCP。+ 不强制升级已有权限档,也不新增伙伴来源分档。宿主继续检查真实调用任务、当前账号、实例代次、+ 目标状态、队列归属及业务对象归属;这些是操作正确性,不是伙伴专属工具权限。+- 已知边界:群专线、其他伙伴、自动化等非主人触发沿用该 Agent 的权限档,没有整轮按来源降权。+ 完全访问也会沿用,不能把公共审批描述为已经接上来源隔离。本次不悄悄改权限档。+- 归档不等于停止运行,已在运行的轮次归档后仍可调用通用工具;共享入口拒绝已删除或不存在的+ 调用任务,具体操作的目标状态要求保持原样。+- 群专线与主任务都能使用相同的通用工具;伙伴专属“修改自己的资料”、工作台、群历史等工具仍需要+ 对应的业务对象和本机数据。后台任务的跟踪、回传、停止仍使用现有 Session 任务契约。+- 不隐瞒能力缺口:未安装、未连接、全局停用或当前引擎/远端不支持时明确返回状态。目录读取失败+ 必须报告,不能用空列表启动并宣称已全配。Cindy 安装更新与重启目前没有 Agent 可直接调用的正式接口,+ `check_app_update` 只检查更新,安装仍由用户在内置更新界面操作。+- 本改动不引入跨设备控制协议、新的 `control_session` 大工具或新的幂等数据库表。+ 通用工具保留原名和发现路径。伙伴的身份、个人记忆和 Skill 学习与工具权限分开维护。## 7. 实现红线@@ -635,17 +620,16 @@ Codex 切模型重建时,线程索引里的路径不等于文件已经落盘- canonical Session 能反查唯一 Bot;后台任务能反查发起任务,彼此上下文隔离。- 压缩或异常恢复前后使用同一个 `<bot home>/workspace/`;不同 owner / Bot 的 Home 不串用。- 关闭全局 Maker Memory 后 Bot Memory 仍可读写;全局列举与清空不包含 Bot Memory。-- 新伙伴不默认加载全量 Skill / MCP,但能按需发现并加入已有能力;Bot-own Skill 始终可用。- 伙伴可发现、调用用户已有插件,保留实时授权限制;普通 Bot 无 Orca / harness subagent 入口。+- 新伙伴及所有旧名单默认继承普通 Agent 已启用的工具集和 MCP;新版显式选择(包括空名单)不被覆盖。+ 伙伴可按需发现插件;Bot-own Skill 始终可用。+ 三个引擎均不得因伙伴身份禁用原生子 Agent;Orca 服从普通任务相同的全局设置。- 后台任务承接 ask / auto / bypassPermissions 三档,权限变更中不读旧值;既有计划快照可恢复。- 伙伴会话的上下文里没有项目 / 全局 AGENTS.md、CLAUDE.md 与 Cindy 产品提示词。- `start_session_task` 能:任务卡实时更新到终态、挂起交互回到伙伴代答、完成唤醒信号对用户不可见;每次执行收口另存可展开的结果入口(按任务与执行轮次去重),历史原卡不移动。结果入口直接展示该次结果与文件,超时复用既有终态归一;当次失败原因随回执保存,桌面与手机仅在用户展开错误详情后显示,续跑不改写旧回执。忙时排队、过程收拢和重新打开不影响读取;阅读历史时沿用新消息提示,不强拉到底部。父任务异常恢复后仍投递到当前主任务;check / message / stop 都只能控制它创建的 Session 任务。主人交给伙伴的项目里的原有任务经 6.3 的工作台工具查看、继续,越权(项目外、伙伴隐藏任务、非主任务调用、远程、归档)一律被宿主拒绝。-- 本机伙伴主任务的通用 session 工具按 6.4 逐轮判定:主人本人那一轮全套可用;主人事先安排的那一轮只能动- 自己的任务与已接手项目里的任务、不能建自动化;其它来源只能动自己的任务、只读自己的记录;后台任务回报不高于- 引出它的那一轮;没登记的工具默认只在主人本人那一轮放行。+- 通用 session 工具及历史查询不再按伙伴来源分档;账号、实例、目标与队列归属检查保持有效。- 伙伴主聊天通知优先使用当前已完成轮次的最终回复纯文本摘要;Markdown 转为可读文字后才截断,遵守推送协议的 UTF-16 长度上限且不拆分代理对。无可用正文时使用本地化新回复兜底;沿用通知开关及系统预览隐私,静默自动化仍不外发。普通任务保留任务通知语义。- 完成信号临时失败与 Host 重启后会幂等补投;等待事项在重启恢复期间保持可见且不消耗执行期限。- `send_to_agent` 的同一伙伴对最多 12 条、单方最多连续 2 条;达到上限和空闲超时都会结束本轮。diff --git a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.tsindex 4f9911b45a..f66da5808b 100644--- a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts+++ b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts@@ -18,6 +18,23 @@ function parsePayload(result: unknown): Record<string, unknown> {}describe("cindy_helper MCP server", () => {+ it.each(['default', 'bot-main'] as const)('exposes runtime declarations through the same helper tool for %s', async (surface) => {+ const runtimeCapabilities = vi.fn(async () => ({ ok: true, capabilities: [{ server: 'fixture' }] }));+ const server = createXdtHelperMcpServer({ resolveSurface: async () => surface, runtimeCapabilities }, {+ agentKind: 'pi', workingDir: '/repo', sessionId: 'current-task',+ });+ const client = new Client({ name: 'catalog-test', version: '1' });+ const [ct, st] = InMemoryTransport.createLinkedPair();+ await Promise.all([server.connect(st), client.connect(ct)]);+ try {+ const result = parsePayload(await client.callTool({ name: 'call_tool', arguments: {+ name: 'get_capabilities', args: { scope: 'runtime', server: 'fixture', category: 'files' },+ } }));+ expect(result).toMatchObject({ ok: true, capabilities: [{ server: 'fixture' }] });+ expect(runtimeCapabilities).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'current-task', agentKind: 'pi' }), { server: 'fixture', category: 'files' });+ } finally { await client.close(); await server.close(); }+ });+it('offers update checks without installation only to a live local task', async () => {let context = {agentKind: 'codex' as const, workingDir: '/repo', sessionId: 'local-task',@@ -117,7 +134,7 @@ describe("cindy_helper MCP server", () => {await Promise.all([server.connect(st), client.connect(ct)]);try {const overview = parsePayload(await client.callTool({ name: 'list_tools', arguments: {} }));- expect(overview.categories).toEqual([{ name: 'auth', tool_count: 3 }]);+ expect(overview.categories).toEqual([{ name: 'cindy', tool_count: 2 }, { name: 'auth', tool_count: 3 }]);const result = parsePayload(await client.callTool({name: 'call_tool', arguments: { name: 'start_grok_device_login', args: {} },}));@@ -763,69 +780,22 @@ describe("cindy_helper MCP server", () => {const overview = parsePayload(await client.callTool({ name: "list_tools", arguments: {} }),);- expect(overview.categories).toEqual([- { name: "cindy", tool_count: 2 },- { name: "control", tool_count: 2 },- { name: "bots", tool_count: 1 },- ]);-- // Project/session management is now part of the Bot surface.- const projectRegistration = parsePayload(- await client.callTool({- name: "call_tool",- arguments: { name: "create_project", args: { working_dir: "/repo" } },- }),- );- expect(projectRegistration).toMatchObject({ ok: true, working_dir: "/repo" });- expect(createProject).toHaveBeenCalled();-- const controlTools = parsePayload(- await client.callTool({ name: "list_tools", arguments: { category: "control" } }),- );- const controlNames = (controlTools.tools as Array<{ name: string; description: string }>);- expect(controlNames.map((tool) => tool.name)).toEqual(["create_project", "move_session"]);- expect(controlNames.find((tool) => tool.name === "create_project")?.description).toContain(- "start_session_task",- );- expect(controlNames.find((tool) => tool.name === "create_project")?.description).not.toContain(- "send_to_session",- );- expect(controlNames.find((tool) => tool.name === "move_session")?.description).not.toContain(- "list_sessions",- );- expect(controlNames.find((tool) => tool.name === "move_session")?.description).toContain(- "cannot look up another task by title",- );- for (const name of ["stop_session_turn", "list_session_queue"]) {- expect(- parsePayload(await client.callTool({ name: "call_tool", arguments: { name, args: {} } })),- ).toMatchObject({ ok: false, errorCode: "CAPABILITY_NOT_AVAILABLE" });- }- expect(stopSessionTurn).not.toHaveBeenCalled();- expect(listSessionQueue).not.toHaveBeenCalled();-- const forbiddenCategory = parsePayload(- await client.callTool({ name: "list_tools", arguments: { category: "handoff" } }),- );- expect(forbiddenCategory).toMatchObject({- ok: false,- errorCode: "CAPABILITY_NOT_AVAILABLE",- });-- const forbiddenCall = parsePayload(- await client.callTool({- name: "call_tool",- arguments: {- name: "send_to_session",- args: { target_session_id: TARGET_SESSION_ID, message: "Do work" },- },- }),- );- expect(forbiddenCall).toMatchObject({- ok: false,- errorCode: "CAPABILITY_NOT_AVAILABLE",- });- expect(sendToSession).not.toHaveBeenCalled();+ expect(overview.categories).toEqual(expect.arrayContaining([+ expect.objectContaining({ name: 'cindy' }),+ expect.objectContaining({ name: 'control' }),+ expect.objectContaining({ name: 'history' }),+ expect.objectContaining({ name: 'handoff' }),+ expect.objectContaining({ name: 'bots' }),+ ]));+ const controlTools = parsePayload(await client.callTool({ name: 'list_tools', arguments: { category: 'control' } }));+ const controlNames = controlTools.tools as Array<{ name: string; description: string }>;+ expect(controlNames.map((tool) => tool.name)).toEqual(expect.arrayContaining(['create_project', 'move_session', 'stop_session_turn']));+ expect(controlNames.find((tool) => tool.name === 'move_session')?.description).toContain('list_sessions');+ const handedOff = parsePayload(await client.callTool({ name: 'call_tool', arguments: {+ name: 'send_to_session', args: { target_session_id: TARGET_SESSION_ID, message: 'Do work' },+ } }));+ expect(handedOff).toMatchObject({ ok: true });+ expect(sendToSession).toHaveBeenCalled();const botTools = parsePayload(await client.callTool({ name: "list_tools", arguments: { category: "bots" } }),@@ -927,7 +897,7 @@ describe("cindy_helper MCP server", () => {}});- it("keeps a remote Bot main task and other Bot sessions on the unchanged narrow, ungated surface", async () => {+ it("gives remote and secondary companion tasks the ordinary surface for their transport", async () => {const authorizeCall = vi.fn(async () => ({ ok: true as const }));const createProject = vi.fn(async () => ({ ok: true as const, workingDir: "/repo" }));for (const context of [@@ -944,8 +914,12 @@ describe("cindy_helper MCP server", () => {try {const overview = parsePayload(await client.callTool({ name: "list_tools", arguments: {} }));const categories = (overview.categories as Array<{ name: string }>).map((category) => category.name);- expect(categories).not.toContain("history");- expect(categories).not.toContain("handoff");+ if (context.remoteHostId) {+ expect(categories).not.toContain("history");+ } else {+ expect(categories).toContain("cindy");+ expect(categories).toContain("control");+ }} finally {await client.close();await server.close();diff --git a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.tsindex de1c3c6c32..ae19b47a1f 100644--- a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts+++ b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts@@ -210,22 +210,9 @@ function cindyAvailableForSession(sessionCtx: XdtHelperMcpSessionCtx): boolean {return !ctx.remoteHostId || ctx.agentKind === 'pi';}-/** Project tools a Bot may use without receiving the rest of `control` or `history`. */-const BOT_PROJECT_TOOLS = new Set([- 'create_project',- 'list_projects',- 'rename_project',- 'remove_project',- 'move_session',-]);-interface HelperSurfaceAllow {/** null means every registered category. An empty set means none. */categories: ReadonlySet<string> | null;- /** Named tools visible even when their category stays closed. */- extraTools: ReadonlySet<string>;- /** Bot callers: each call is also judged by the host's per-turn authority. */- gated?: boolean;}function toolAllowed(@@ -233,24 +220,7 @@ function toolAllowed(tool: { name: string; category: string },): boolean {if (!allow.categories) return true;- return allow.categories.has(tool.category) || allow.extraTools.has(tool.name);-}--/** Bot project tools must not point at history/handoff tools that stay closed. */-function describeBotProjectTool(tool: { name: string; description: string }): string {- if (tool.name === 'create_project') {- return tool.description.replace(- 'Pass the returned working_dir to send_to_session to start work there.',- 'Pass the returned working_dir to start_session_task to start work there.',- );- }- if (tool.name === 'move_session') {- return tool.description.replace(- 'Use list_sessions to find session_id and list_projects to find directories;',- 'Pass a session_id this Bot already has, such as one returned by start_session_task. This cannot look up another task by title. Use list_projects to find directories;',- );- }- return tool.description;+ return allow.categories.has(tool.category);}function registerListToolsEntry(@@ -284,7 +254,7 @@ function registerListToolsEntry(category,tools: tools.map((t) => ({name: t.name,- description: allowed.extraTools.has(t.name) ? describeBotProjectTool(t) : t.description,+ description: t.description,...(t.category === 'bots' || t.category === 'skills' ? {inputSchema: z.toJSONSchema(z.strictObject(registry.get(t.name)!.inputShape)),} : {}),@@ -344,7 +314,7 @@ function registerCallToolEntry(}const result = definition? await withToolCallAuthority(- allowed.gated ? telemetry.authorizeCall : undefined,+ telemetry.authorizeCall,{ sessionId: telemetry.getSessionId(), server: 'cindy_helper', tool: name, args },() => registry.call(name, args),)@@ -740,13 +710,17 @@ export interface XdtHelperMcpDeps {/*** Host-owned runtime classification. `bot-main` is a local Bot's main task: it sees* the ordinary task surface plus Bot tools, and every call is judged by `authorizeCall`.- * `bot` keeps the narrow Bot surface (group lanes, history, remote Bots).+ * Companions add self-management to the ordinary tool surface for their execution location.*/resolveSurface?: (input: {sessionId: string;}) => Promise<'default' | 'bot' | 'bot-main' | 'restricted'>;- /** Live per-call check for Bot tasks; the tool list itself never changes mid-session. */+ /** Live caller/account check for all tasks; the tool list itself never changes mid-session. */authorizeCall?: ToolCallAuthorizer;+ runtimeCapabilities?: (+ context: import('./types.js').LiziMcpSessionContext,+ query: import('./xdt-helper/get_capabilities.js').RuntimeCapabilityQuery,+ ) => Promise<unknown>;/*** 历史聊天数据查询的回调集合(读本地 SQLite 的 sessions / messages 表)。host* 注入后, history 类工具(list_workdirs / list_sessions / get_chat_history /@@ -841,7 +815,7 @@ export function createXdtHelperMcpServer(});const registry = new XdtHelperToolRegistry();- const none: HelperSurfaceAllow = { categories: new Set(), extraTools: new Set() };+ const none: HelperSurfaceAllow = { categories: new Set() };const allowedSurface = async (): Promise<HelperSurfaceAllow> => {const context = resolveLiziMcpSessionContext(sessionCtx);const sessionId = context.sessionId;@@ -852,34 +826,23 @@ export function createXdtHelperMcpServer(if (context.remoteHostId) defaultCategories.delete('app_update');const allow = (categories: ReadonlySet<string>): HelperSurfaceAllow => ({categories,- extraTools: new Set(),});if (!sessionId) return allow(remoteBotOnly ? new Set() : defaultCategories);- if (!deps.resolveSurface) return allow(remoteBotOnly ? new Set(['auth']) : defaultCategories);+ if (!deps.resolveSurface) return allow(remoteBotOnly ? new Set(['auth', 'cindy']) : defaultCategories);const surface = await deps.resolveSurface({ sessionId }).catch(() => 'restricted' as const);- // A local Bot main task works like an ordinary task: the full surface plus Bot- // tools. What a given turn may actually do (owner / arranged / other) is- // decided per call by the host, so the tool list stays stable across turns.- if (surface === 'bot-main' && !context.remoteHostId) {- return { categories: new Set([...defaultCategories, 'bots']), extraTools: new Set(), gated: true };- }- // Other Bot sessions (group lanes, history, remote Bots) keep their unchanged- // narrow surface: bots/cindy/auth, with project tools as named exceptions so a- // Bot can register and organize projects without stop/steer/archive/history access.if (surface === 'bot' || surface === 'bot-main') {- // Project tools run only on the local host. A remote Bot must keep its- // own tooling without being offered calls that always return unsupported.- return {- categories: new Set(['bots', 'cindy', 'auth']),- extraTools: context.remoteHostId ? new Set() : BOT_PROJECT_TOOLS,- };+ // Companion identity adds self-management, not a narrower ordinary tool surface.+ const categories = remoteBotOnly ? new Set(['auth', 'cindy']) : defaultCategories;+ return { categories: new Set([...categories, 'bots']) };}if (surface === 'restricted') return none;- return allow(remoteBotOnly ? new Set(['auth']) : defaultCategories);+ return allow(remoteBotOnly ? new Set(['auth', 'cindy']) : defaultCategories);};// 'cindy' 类: 自省 (无 host 依赖, 始终注册)。- registerGetCapabilitiesTool(registry);+ registerGetCapabilitiesTool(registry, deps.runtimeCapabilities+ ? (query) => deps.runtimeCapabilities!(resolveLiziMcpSessionContext(sessionCtx), query)+ : undefined);if (deps.appUpdate) {registerAppUpdateTools(registry, {getSessionContext: () => resolveLiziMcpSessionContext(sessionCtx),@@ -1053,7 +1016,7 @@ export function createXdtHelperMcpServer(}const sessionId = resolveLiziMcpSessionContext(sessionCtx).sessionId;const result = await withToolCallAuthority(- allowed.gated ? deps.authorizeCall : undefined,+ deps.authorizeCall,{ sessionId, server: 'cindy_helper', tool: definition.name, args },() => registry.call(definition.name, args),);diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.tsindex 30f9926ef4..ae80c1963d 100644--- a/packages/lizi-mcps/src/types.ts+++ b/packages/lizi-mcps/src/types.ts@@ -966,6 +966,12 @@ export interface CodexHttpMcpConfig {export interface LiziMcpProvider {name: string;+ capability?: {+ title: string;+ description: string;+ source: 'builtin' | 'plugin' | 'custom';+ discovery?: { tool: string; args?: Record<string, unknown> };+ };isEnabled?(context: LiziMcpSessionContext): boolean;toClaudeSdkConfig(context: LiziMcpSessionContext): unknown | null;/** Remote MCP config for Codex app-server; SDK instance providers use the host HTTP bridge instead. */diff --git a/packages/lizi-mcps/src/xdt-helper/get_capabilities.ts b/packages/lizi-mcps/src/xdt-helper/get_capabilities.tsindex b95e2f19bc..292e023ab5 100644--- a/packages/lizi-mcps/src/xdt-helper/get_capabilities.ts+++ b/packages/lizi-mcps/src/xdt-helper/get_capabilities.ts@@ -15,23 +15,34 @@ import { z } from 'zod';import { findCapability, listCapabilityIndex } from './capabilities.js';import type { XdtHelperToolRegistry } from '../lizi_xdtHelperToolRegistry.js';-export function registerGetCapabilitiesTool(registry: XdtHelperToolRegistry): void {+export interface RuntimeCapabilityQuery { server?: string; category?: string; }+export type RuntimeCapabilityReader = (query: RuntimeCapabilityQuery) => Promise<unknown>;++export function registerGetCapabilitiesTool(registry: XdtHelperToolRegistry, readRuntime?: RuntimeCapabilityReader): void {registry.register({name: 'get_capabilities',category: 'cindy',description:`查询 ${BRAND_NAME} 自身能力。不传参数 → 返回所有能力的 {key, title, oneLiner} 索引;` +- '传 key=<具体能力 key> → 返回该能力的完整 detail。' ++ '传 key=<具体能力 key> → 返回该能力的完整 detail。scope=runtime 查询当前 Agent 的真实工具目录;指定 server 查看注册工具,category 展开内置类目。产品说明不等于可调用工具。' +`当用户问"${BRAND_NAME} 能做什么 / 有哪些功能 / 支持 X 吗"时调用本工具,而不是用训练数据回答。` +`用户问"你是谁 / 你是什么 / 你跑在哪 / ${BRAND_NAME} 是什么产品 / 谁做的 / 开不开源 / 源码在哪"时,` +'同样调本工具取 key=about-cindy,不要靠工作目录路径、工具名或训练数据推断。',inputShape: {+ scope: z.enum(['product', 'runtime']).optional().describe('product 查询产品介绍;runtime 查询实际注册与启用状态。'),+ server: z.string().optional().describe('从 runtime 目录返回的 server 标识。'),+ category: z.string().optional().describe('该 server 的 list_tools 返回的类目。'),key: z.string().optional().describe('能力 key(从不传参的索引返回中获取)。不传 = 返回索引列表。'),},- handler: async ({ key }) => {+ handler: async ({ key, scope, server, category }) => {+ if (scope === 'runtime') {+ const result = readRuntime ? await readRuntime({ server, category })+ : { ok: false, errorCode: 'RUNTIME_CATALOG_UNAVAILABLE', message: '当前宿主尚未提供运行能力目录。' };+ return { content: [{ type: 'text' as const, text: JSON.stringify(result) }] };+ }if (!key) {return {content: [diff --git a/packages/maker-core/src/agents/claude-code/__tests__/bot-own-skills-mount.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/bot-own-skills-mount.test.tsindex 5b5f94f273..aa2e2e14f5 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/bot-own-skills-mount.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/bot-own-skills-mount.test.ts@@ -203,14 +203,14 @@ describe('Claude Code mounts the Bot\'s own learned Skills', () => {const options = await startBotSession({ ownSkillPluginRoots: [OWN_SKILL_ROOT] });expect(options.plugins).toEqual([{ type: 'local', path: OWN_SKILL_ROOT }]);expect(options.settingSources).toEqual([]);- expect(options.disallowedTools).toEqual(['Task', 'Agent']);+ expect(options.disallowedTools).toBeUndefined();expect(options.strictMcpConfig).toBe(true);expect(options.settings).toMatchObject({ autoMemoryEnabled: false, autoDreamEnabled: false });});it('keeps remote Bot tools and memory in the same scope as local Bots', async () => {const options = await startBotSession({ remote: true });- expect(options.disallowedTools).toEqual(['Task', 'Agent']);+ expect(options.disallowedTools).toBeUndefined();expect(options.strictMcpConfig).toBe(true);expect(options.settings).toMatchObject({ autoMemoryEnabled: false, autoDreamEnabled: false });});diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex ae15331a68..608acc6846 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -3541,7 +3541,7 @@ export class ClaudeCodeAgent extends BaseAgent {// options (cc-mgr.ts:106), 所以 extraOptions 是任意 SDK 字段的统一透传出口。extraOptions: {includePartialMessages: true,- ...(opts.botRuntimeProfile ? { disallowedTools: ['Task', 'Agent'], strictMcpConfig: true } : {}),+ ...(opts.botRuntimeProfile ? { strictMcpConfig: true } : {}),...thinkingOpts,...(currentSdkEffort ? { effort: currentSdkEffort } : {}),// settings 对象跟本地分支同源 — 不透传则远端 SDK 拿不到@@ -4127,8 +4127,8 @@ export class ClaudeCodeAgent extends BaseAgent {// permissionMode=auto 时再调用远程安全分类器。动态聚合入口不在列表中。...(claudeAllowedTools ? { allowedTools: [...claudeAllowedTools] } : {}),canUseTool,- // Bot work is delegated through tracked Cindy Session tasks.- ...(opts.botRuntimeProfile ? { disallowedTools: ['Task', 'Agent'], strictMcpConfig: true } : {}),+ // Bot MCP selection is explicit; native delegation remains available.+ ...(opts.botRuntimeProfile ? { strictMcpConfig: true } : {}),settingSources: reviewMode || !!opts.botRuntimeProfile? []: ['user', 'project', 'local'],diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 0280bea7f0..7502a99235 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -6665,12 +6665,12 @@ describe('CodexAgent.startSession developerInstructions', () => {config?: Record<string, unknown>;};expect(params.config).toMatchObject({- 'features.multi_agent': false,- 'features.multi_agent_v2': false,- 'agents.enabled': false,'memories.generate_memories': false,'memories.use_memories': false,});+ expect(params.config?.['features.multi_agent']).not.toBe(false);+ expect(params.config?.['features.multi_agent_v2']).not.toBe(false);+ expect(params.config?.['agents.enabled']).not.toBe(false);expect(params.developerInstructions).toContain('BOT SOUL');expect(params.developerInstructions).toContain('BOT HOME CONTEXT');expect(params.developerInstructions).not.toContain('GLOBAL CINDY HOST PROMPT');diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 455e9b34a4..a998f1d0c0 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -6371,12 +6371,9 @@ assertRouteCurrent();// Install while the thread is created/resumed: a later switch to Auto// changes the turn reviewer without rebuilding this thread config....nativeContinuationConfig,- // Bot memory and delegation belong to its Cindy Profile and Session- // tasks, not the shared native home or hidden harness child threads.+ // Keep companion memory in its own Home. Native delegation uses the+ // same feature settings and permissions as an ordinary task....(opts.botRuntimeProfile ? {- 'features.multi_agent': false,- 'features.multi_agent_v2': false,- 'agents.enabled': false,'memories.generate_memories': false,'memories.use_memories': false,} : {}),diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.tsindex 4c105b9fe8..996cb67083 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts@@ -3232,12 +3232,10 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {arg === '--extension' ? [captured.args[index + 1]] : []);expect(extensionPaths).toEqual(expect.arrayContaining([path.posix.join(captured.env.PI_CODING_AGENT_DIR!, 'internal-extensions', 'cindy-bridge.ts'),- ]));- // Bot 会话是产品人格,不是 coding harness:pi 原生 subagent 面必须不可见,- // 项目/全局 AGENTS.md 也不得从 cwd 链被吸进上下文。- expect(extensionPaths).not.toEqual(expect.arrayContaining([path.posix.join(captured.env.PI_CODING_AGENT_DIR!, 'internal-extensions', 'cindy-subagent.ts'),]));+ // Bot 共享普通任务的子代理能力,但仍保留独立人格和记忆,+ // 不从 cwd 链加载项目/全局 AGENTS.md。expect(captured.args).toContain('--no-context-files');expect(deps.resolvePiGlobalContextHome).not.toHaveBeenCalled();const promptIndex = captured.args.indexOf('--append-system-prompt');diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.tsindex a31c2f3999..7cfe5d1f32 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts@@ -362,6 +362,20 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {};}+ it('mounts native subagent tools for companion sessions too', async () => {+ const agent = new PiAgent(buildDeps());+ const handle = await agent.startSession({ ...opts(), botRuntimeProfile: {+ botId: 'bot', profileVersion: 1,+ skillPolicy: { mode: 'allowlist', configured: [], catalog: [] },+ mcpPolicy: { mode: 'allowlist', configured: [], catalog: [] },+ toolsetPolicy: { mode: 'allowlist', configured: [], catalog: [] },+ } });+ try {+ expect(repeatedArgValues(knobs.spawnedArgs[0]!, '--extension'))+ .toEqual(expect.arrayContaining([expect.stringContaining('cindy-subagent')]));+ } finally { await handle.close(); }+ });+it('disposes ctx (and does not close a nonexistent proc) when the process constructor throws synchronously', async () => {knobs.ctorThrows = true;const agent = new PiAgent(buildDeps());diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 98f0b4f363..621cd49e81 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -3155,13 +3155,9 @@ export class PiAgent extends BaseAgent {// the remote host while Cindy observes and controls an unrelated local// directory. Keep the capability absent until the wire protocol owns those// files remotely end-to-end.- // Bot sessions are a product persona, not a coding harness: the native- // subagent surface must stay invisible to them. Their tracked work goes- // through Cindy Session tasks instead.const localSubagentSupported = Boolean(!reviewMode&& !remote- && !opts.botRuntimeProfile&& this.deps.spawnPiSubagentRunner,);if (localSubagentSupported) {diff --git a/packages/maker-core/src/interfaces/mcp-provider.ts b/packages/maker-core/src/interfaces/mcp-provider.tsindex 9c91c0f59e..a7e94dbf35 100644--- a/packages/maker-core/src/interfaces/mcp-provider.ts+++ b/packages/maker-core/src/interfaces/mcp-provider.ts@@ -66,6 +66,13 @@ export interface CodexHttpMcpServerConfig {export interface McpProvider {/** MCP server 唯一名(host 自定义) */name: string;+ /** Discovery metadata lives beside the provider; never a second tool/permission table. */+ capability?: {+ title: string;+ description: string;+ source: 'builtin' | 'plugin' | 'custom';+ discovery?: { tool: string; args?: Record<string, unknown> };+ };/** 按 session 上下文决定是否启用,例如飞书 bot MCP 只给 source='feishu' 会话。 */isEnabled?(context: McpProviderContext): boolean;/**