Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(plugins): restrict account data and reject worker full access

Dash0a774f10bb76
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginStartTeamAdmission.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginStartTeamAdmission.test.ts
index 0743d4f9bc..f4e9a86b27 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginStartTeamAdmission.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginStartTeamAdmission.test.ts
@@ -4,6 +4,7 @@ import ts from 'typescript';
import { assertPluginTaskResult, PluginTaskError } from '../pluginTaskService.js';
import { createOrcaLifecycleService, type OrcaLifecycleDeps } from '../orcaLifecycleService.js';
import { startOrcaTeamWithPermissionGate } from '../orcaStartTeamPermissionGate.js';
+import { hasAcceptedUserTaskInput } from '../pluginTaskInput.js';
vi.mock('../../maker-host/codex-credential-switch.js', () => ({ isCredentialModeSwitchBusyError: () => false }));
@@ -46,6 +47,70 @@ describe('plugin team active-task admission', () => {
});
});
+describe('public start_team Full access admission', () => {
+ const helper = source.slice(source.indexOf(' const startOrcaTeamForCaller ='), source.indexOf(' const pluginPermissionRequests ='));
+ const authority = source.slice(source.indexOf(' const assertPluginWorkerAutoAuthorized ='), source.indexOf(' const orcaWorkerCreationService ='));
+ const wired = ts.transpileModule(`${authority}\n${helper}\nreturn { start: startOrcaTeamForCaller, capture: captureOrcaPluginAuthority };`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ const states = ['plugin', 'ask', 'plan', 'disabled', 'revoked-running', 'ordinary', 'revoked-idle', 'revoked-human'] as const;
+ const cases = (['auto', 'bypassPermissions'] as const).flatMap(preference => [
+ ...states.map(state => ({ state, preference, requested: 'bypassPermissions' as 'auto' | 'bypassPermissions' | undefined })),
+ ...(['auto', undefined] as const).map(requested => ({ state: 'plugin' as const, preference, requested })),
+ ]);
+
+ it.each(cases)(
+ '$state requests $requested with global preference $preference', async ({ state, preference, requested }) => {
+ const epoch = { client: {} };
+ const revoked = state.startsWith('revoked-');
+ const input = state === 'revoked-running' ? { clientId: 'plugin-task:run' }
+ : state === 'revoked-human' ? { clientId: 'human', authoredText: 'Start a team' } : null;
+ const ordinary = ['ordinary', 'revoked-idle', 'revoked-human'].includes(state);
+ const task = { status: 'active', permissionMode: state === 'ask' ? 'default' : 'auto', planModeEnabled: state === 'plan' };
+ const request = vi.fn(async () => ({ confirmed: true }));
+ const create = vi.fn(async () => ({ id: 'team', leadSessionId: 'lead' }));
+ const setPreference = vi.fn();
+ let capture: OrcaLifecycleDeps['getWorkerPermissionModeOverride'];
+ const lifecycle = createOrcaLifecycleService({
+ getWorkerPermissionMode: () => preference,
+ getWorkerPermissionModeOverride: (id: string) => capture!(id),
+ setWorkerPermissionMode: setPreference,
+ getActiveTeamByLead: async () => null, createActiveTeam: create,
+ setSessionOrcaRole: vi.fn(), clearKnownNonOrcaSession: vi.fn(), setLeadVendorOptions: vi.fn(),
+ markTeamEnded: vi.fn(), clearLeadVendorOptions: vi.fn(),
+ } as unknown as OrcaLifecycleDeps);
+ const bindings = {
+ PluginTaskError, hasAcceptedUserTaskInput, startOrcaTeamWithPermissionGate,
+ getCurrentDbClientSnapshot: () => epoch,
+ maker: { getSession: () => null }, inputCoordinator: { getAcceptedInputProvenance: () => input },
+ createPluginTaskStore: () => ({ get: async () => state === 'ordinary' ? null
+ : { operation: 'create', pluginId: 'plugin', payload: JSON.stringify({ ownershipRevoked: revoked }) } }),
+ pluginTaskServiceForCurrentOwner: () => ({ get: async () => task }),
+ isPluginTaskAuthorized: () => state !== 'disabled', readGhostErrandConfig: () => ({ permissionMode: 'auto' }),
+ assertLeadCollabProjectEnabled: async () => {}, getWorkerPermissionModeFromCreationPrefs: () => preference,
+ orcaWorkerPermissionConfirmBridge: { request }, t: (key: string) => key, orcaLifecycleService: lifecycle,
+ };
+ const run = new Function(...Object.keys(bindings), wired)(...Object.values(bindings));
+ capture = run.capture;
+ const result = await run.start('lead', requested);
+ if (ordinary) {
+ expect(result).toMatchObject({ ok: true, workerPermissionMode: 'bypassPermissions' });
+ expect(request).toHaveBeenCalledTimes(preference === 'auto' ? 1 : 0);
+ expect(setPreference).toHaveBeenCalledWith('bypassPermissions');
+ expect(create).toHaveBeenCalledOnce();
+ } else if (requested === 'bypassPermissions') {
+ expect(result).toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });
+ expect(request).not.toHaveBeenCalled();
+ expect(setPreference).not.toHaveBeenCalled();
+ expect(create).not.toHaveBeenCalled();
+ } else {
+ expect(result).toMatchObject({ ok: true, workerPermissionMode: 'auto' });
+ expect(request).not.toHaveBeenCalled();
+ expect(setPreference).not.toHaveBeenCalled();
+ expect(create).toHaveBeenCalledOnce();
+ }
+ },
+ );
+});
+
describe('plugin team activation uses the native lifecycle compensation', () => {
const helper = source.slice(source.indexOf(' const startOrcaTeamForCaller ='), source.indexOf(' const pluginPermissionRequests ='));
const wired = ts.transpileModule(`${helper}\n${js}`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index e7770467bd..489b571ad3 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -10675,6 +10675,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const startOrcaTeamForCaller = async (leadSessionId: string, workerPermissionMode?: OrcaWorkerPermissionMode, assertCurrent?: (activationStarted?: boolean) => Promise<void>, completeOperation?: PluginTaskService['completeOperation']) => {
try {
await assertLeadCollabProjectEnabled(leadSessionId);
+ // Plugin Auto cannot request Full access, including through the public
+ // Agent tool. Reject before showing a confirmation we cannot honor.
+ if (workerPermissionMode === 'bypassPermissions'
+ && (await captureOrcaPluginAuthority(leadSessionId)).permissionMode === 'auto') {
+ throw new PluginTaskError('PERMISSION_DENIED', 'Plugin tasks cannot request Worker Full access');
+ }
return await startOrcaTeamWithPermissionGate(
{ leadSessionId, workerPermissionMode },
{
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/pluginTaskHelperScope.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/pluginTaskHelperScope.test.ts
index d9847d8af6..9de3dbd640 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/pluginTaskHelperScope.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/pluginTaskHelperScope.test.ts
@@ -1,10 +1,12 @@
-import { readFileSync } from 'node:fs';
+import { existsSync, mkdtempSync, promises as fs, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import Database from 'better-sqlite3';
import { drizzle } from 'drizzle-orm/better-sqlite3';
import { eq } from 'drizzle-orm';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
-import { createXdtHelperMcpServer } from '@cindy/mcps';
+import { createLiziMcpProviders, createXdtHelperMcpServer, type LiziMcpSessionContext } from '@cindy/mcps';
import ts from 'typescript';
import { expect, it, vi } from 'vitest';
import { botSessionLinks, sessions } from '../../localDb/schema.js';
@@ -50,7 +52,10 @@ function fixture() {
}).outputText;
const searchSessions = new Function(...Object.keys(searchDeps), searchWired)(...Object.values(searchDeps)) as
(query: string, opts: { callerSessionId: string; sessionId?: string }) => Promise<unknown[]>;
- return { sqlite, db, resolve, searchSessions, searchSessionsFn, setCurrent: (next?: DbClient) => { current = next; },
+ const accessSource = source.slice(source.indexOf(' const withAccountDataAccess ='), source.indexOf(' const providers ='));
+ const accessJs = ts.transpileModule(`${accessSource}\nreturn withAccountDataAccess;`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ const withAccountDataAccess = new Function(...Object.keys(deps), accessJs)(...Object.values(deps));
+ return { sqlite, db, resolve, searchSessions, searchSessionsFn, withAccountDataAccess, setCurrent: (next?: DbClient) => { current = next; },
setExecution: (next: typeof execution) => { execution = next; },
setPending: () => { pending = true; } };
}
@@ -230,3 +235,84 @@ it.each(['codex', 'claude-code', 'pi'] as const)('blocks helper discovery and gu
.toMatchObject({ ok: false, errorCode: 'CAPABILITY_NOT_AVAILABLE' });
} finally { await client.close(); await server.close(); f.sqlite.close(); }
});
+
+it.each(['lead', 'worker'].flatMap(sessionId => (['codex', 'claude-code', 'pi'] as const).flatMap(agentKind =>
+ (['cindy_contacts', 'cindy_scheduler', 'cindy_slack'] as const).map(name => ({ sessionId, agentKind, name })))))(
+ 'protects account data from $sessionId through $agentKind $name', async ({ sessionId, agentKind, name }) => {
+ const f = fixture();
+ const privateData = [{ id: 'private', displayName: 'Synthetic private contact', prompt: 'Synthetic private schedule' }];
+ const read = vi.fn(async () => privateData);
+ const manager = vi.fn(() => ({ getStore: () => ({ listContacts: read }) }));
+ const scheduler = vi.fn(() => ({ list: read }));
+ const getBridge = vi.fn(() => ({ availability: () => ({ bound: true, connected: true, serverSupportsTools: true }),
+ callTool: async () => ({ ok: true, result: await read() }) }));
+ const { withAccountDataAccess } = f;
+ const providers = createLiziMcpProviders({ enabled: [name],
+ contacts: { getManager: manager, withAccountDataAccess },
+ scheduler: { getScheduler: scheduler, withAccountDataAccess },
+ slackHook: { getBridge, withAccountDataAccess },
+ } as unknown as Parameters<typeof createLiziMcpProviders>[0]);
+ const workingDir = mkdtempSync(join(tmpdir(), 'plugin-account-scope-'));
+ let liveId = sessionId;
+ const ctx: LiziMcpSessionContext = { agentKind, workingDir, sessionId,
+ ...(agentKind !== 'claude-code' ? { sessionId: undefined, getSessionContext: () => ({ agentKind, workingDir, sessionId: liveId }) } : {}) };
+ const config = await providers[0]!.toClaudeSdkConfig(ctx);
+ const server = (config as { instance: ReturnType<typeof createXdtHelperMcpServer> }).instance;
+ const client = new Client({ name: 'plugin-account-scope', version: '1' });
+ const [ct, st] = InMemoryTransport.createLinkedPair();
+ await Promise.all([client.connect(ct), server.connect(st)]);
+ const call = (spill = false) => client.callTool(name === 'cindy_slack'
+ ? { name: 'slack_call_tool', arguments: { name: 'search', ...(spill ? { out_file: 'private.json' } : {}) } }
+ : { name: 'call_tool', arguments: { name: name === 'cindy_contacts' ? 'contacts_list' : 'schedule_list', args: {} } });
+ const denied = (result: unknown) => {
+ expect(result).toMatchObject({ isError: true });
+ expect(JSON.stringify(result)).not.toContain('Synthetic private');
+ };
+ try {
+ denied(await client.callTool({ name: name === 'cindy_slack' ? 'slack_list_tools' : 'list_tools', arguments: {} }));
+ denied(await call());
+ if (name === 'cindy_slack') denied(await client.callTool({ name: 'slack_status', arguments: {} }));
+ else for (const tool of name === 'cindy_contacts'
+ ? ['contacts_get', 'contacts_resolve', 'contacts_search', 'contacts_export_vcf', 'contacts_import_system', 'contacts_export_system', 'contacts_delete', 'contacts_create']
+ : ['schedule_get', 'schedule_list_runs', 'schedule_create', 'schedule_update', 'schedule_delete', 'schedule_run_now']) {
+ denied(await client.callTool({ name: 'call_tool', arguments: { name: tool, args: { id: 'private' } } }));
+ }
+ expect(manager).not.toHaveBeenCalled(); expect(scheduler).not.toHaveBeenCalled(); expect(getBridge).not.toHaveBeenCalled();
+ f.sqlite.exec(`UPDATE plugin_task_requests SET payload='{"ownershipRevoked":true}'`);
+ f.setExecution({ executing: true, input: { clientId: 'plugin-task:run' } });
+ denied(await call());
+ f.setExecution({ executing: true, input: { clientId: 'new-human', authoredText: 'My own request' } });
+ expect(JSON.stringify(await call())).toContain('Synthetic private');
+ read.mockImplementationOnce(async () => { f.setCurrent(); return privateData; });
+ denied(await call(true));
+ expect(existsSync(join(workingDir, 'private.json'))).toBe(false);
+ f.setCurrent(f.db);
+ read.mockImplementationOnce(async () => { f.setExecution({ executing: true, input: { clientId: 'plugin-task:run' } }); return privateData; });
+ denied(await call(true));
+ expect(existsSync(join(workingDir, 'private.json'))).toBe(false);
+ f.setExecution({ executing: true, input: { clientId: 'new-human', authoredText: 'My own request' } });
+ if (name === 'cindy_slack') {
+ // Revocation after fetching data must also block the existing spill path.
+ const mkdir = fs.mkdir.bind(fs);
+ const spy = vi.spyOn(fs, 'mkdir').mockImplementation(async (...args) => {
+ const result = await mkdir(...args);
+ if (String(args[0]) === workingDir) f.setCurrent();
+ return result;
+ });
+ try {
+ denied(await call(true));
+ expect(existsSync(join(workingDir, 'private.json'))).toBe(false);
+ } finally { spy.mockRestore(); f.setCurrent(f.db); }
+ }
+ if (agentKind !== 'claude-code') {
+ liveId = 'user';
+ f.sqlite.exec(`UPDATE plugin_task_requests SET payload='{}'`);
+ expect(JSON.stringify(await call())).toContain('Synthetic private');
+ liveId = sessionId;
+ denied(await call());
+ }
+ f.setPending();
+ denied(await call());
+ } finally { await client.close(); await server.close(); f.sqlite.close(); rmSync(workingDir, { recursive: true, force: true }); }
+ },
+);
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index ff1a3d103e..a335d873d0 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -167,6 +167,21 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
};
}
+ const withAccountDataAccess = async <T>(sessionId: string | undefined, operation: (assertCurrent: () => Promise<void>) => Promise<T>): Promise<T> => {
+ const dbClient = tryGetDbClient();
+ if (!dbClient || !sessionId) throw new Error('Account data caller unavailable');
+ const assertAccess = async () => {
+ if (isAppSessionBoundaryPending() || dbClient !== tryGetDbClient()) throw new Error('Account changed');
+ if (await resolveHelperSurface(dbClient, sessionId, getSessionInputProvenance) === 'restricted')
+ throw new Error('Account data is unavailable for plugin-managed tasks');
+ if (isAppSessionBoundaryPending() || dbClient !== tryGetDbClient()) throw new Error('Account changed');
+ };
+ await assertAccess();
+ const result = await operation(assertAccess);
+ await assertAccess();
+ return result;
+ };
+
const providers = createLiziMcpProviders({
// 先传完整内置列表;按会话启停由下面的 isEnabled 包装处理。
enabled: BUILTIN_LIZI_MCP_IDS,
@@ -282,10 +297,12 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
// 注册表取用(静态 import ipc.ts 会与 maker-host 闭环, 见 slackToolBridge
// 模块头); 未注册 = null, provider isEnabled fail-closed。
slackHook: {
+ withAccountDataAccess,
getBridge: () => getSlackToolBridge(),
logger: createLogger('mcp/cindy_slack'),
},
scheduler: {
+ withAccountDataAccess,
getScheduler: () => getScheduler(),
// 前置检查脚本统一安装服务:落盘路径/协议/自测与 UI「AI 生成」共用同一实现
// (hook-script-generator)。lazy import:该链上有 electron app 依赖,且 maker
@@ -379,6 +396,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
// 智能通讯录: 全局单库 manager 懒加载单例; 开关现读 settings store —
// 每次 session start 时 provider isEnabled 评估, 关着时 server 整个不注册。
contacts: {
+ withAccountDataAccess,
getManager: getDesktopContactsManager,
isEnabled: () => readContactsSettings().enabled,
// 系统通讯录读取仅 macOS 注入(JXA); 缺省时 contacts_import_system 工具不注册。
diff --git a/docs/dev-rules/plugin-task-api-implementation.md b/docs/dev-rules/plugin-task-api-implementation.md
index 8904393455..7b77bdebaa 100644
--- a/docs/dev-rules/plugin-task-api-implementation.md
+++ b/docs/dev-rules/plugin-task-api-implementation.md
@@ -15,7 +15,8 @@
- 回执独立落库,区分任务、输入执行及原生执行代次;原生终态按 instanceId + generation 结算,不以 idle 或最后一条 assistant 消息猜测完成。
- send 回执写入后,进入宿主派发前的检查拒绝可确定未发送,结算为 failed;进入派发后的异常仍为 reconciling,明确拒绝仍为 failed,已有原生进展优先。同 requestKey 只读取旧回执,权限恢复后需新 key 显式提交。若账号、归属或存储条件不再允许结算,调用仍拒绝并保留回执,不绕过权限门补写终态。
- 读取限定于本插件创建的任务;返回消息 clientId。list/listRuns 按 (createdAt, id) 排序,现有回执 ID 游标在同插件与目标内解析,不再只按随机 UUID 排序。列表是分页查询,不是增量订阅;刷新应从首页重扫,不能把游标当永久同步水位(同毫秒追加、系统时钟回退或既有回执终态更新均需刷新)。
-- 插件持有 create 归属的任务及其 Orca Worker 使用既有 restricted `cindy_helper` 能力面,不提供账号级历史、待发消息或跨任务控制;发现与实际调用共用实时 Host 判据,猜工具名也不放行。另一个原始历史入口 `cindy_memory.session_search` 复用同一判据,在查询前拒绝,不伪装为空结果;读取期间账号变化也不返回结果。按创建回执和 Worker→Team→Lead 关系判断,不按 `source=plugin` 一刀切,也不因团队结束而放开。旧 errand/workspace 无回执时保持原行为;明确 `ownershipRevoked=true` 后,调用方已无正在执行的输入或已接受新的 Host 真人输入时,保留的用户任务恢复普通 helper 与历史检索能力;仍执行旧插件输入时继续受限。发现、调用和 memory 检索复用 Orca 的只读来源判据,首个异步查询前固定当前来源、返回前复核;真人重试保留 Host 文本及稳定来源,插件重试不变真人。Lead 自动回报可沿当前可见输入追溯,但 Worker 的新 Lead 指令阻断对更早真人的回溯。损坏回执、未知来源或查询失败保持拒绝;这不恢复插件归属、旧 requestKey 或插件控制权,也不承诺停止已接受执行。独立 Orca 工具不受影响。这只收住宿主 helper 与原始历史检索入口,不是通用执行或文件系统隔离。
+- 插件持有 create 归属的任务及其 Orca Worker 使用既有 restricted `cindy_helper` 能力面,不提供账号级历史、待发消息或跨任务控制;发现与实际调用共用实时 Host 判据,猜工具名也不放行。另一个原始历史入口 `cindy_memory.session_search` 复用同一判据,在查询前拒绝,不伪装为空结果;读取期间账号变化也不返回结果。按创建回执和 Worker→Team→Lead 关系判断,不按 `source=plugin` 一刀切,也不因团队结束而放开。旧 errand/workspace 无回执时保持原行为;明确 `ownershipRevoked=true` 后,调用方已无正在执行的输入或已接受新的 Host 真人输入时,保留的用户任务恢复普通 helper 与历史检索能力;仍执行旧插件输入时继续受限。发现、调用和 memory 检索复用 Orca 的只读来源判据,首个异步查询前固定当前来源、返回前复核;真人重试保留 Host 文本及稳定来源,插件重试不变真人。Lead 自动回报可沿当前可见输入追溯,但 Worker 的新 Lead 指令阻断对更早真人的回溯。损坏回执、未知来源或查询失败保持拒绝;这不恢复插件归属、旧 requestKey 或插件控制权,也不承诺停止已接受执行。独立 Orca 工具不受影响。这不是通用执行或文件系统隔离。
+- 账号级 `cindy_contacts`、`cindy_scheduler`、`cindy_slack` 的发现与实际调用也复用上述实时来源判据。插件持有的任务及 Worker 在读取管理器、调度器或 Slack 绑定前拒绝,猜工具名不能绕过;Codex/Pi 共用服务按每次调用的实际任务判定,Claude 使用当前服务上下文。读取后再核验账号及来源,不返回过期结果;Slack 的既有结果文件路径解析与目录准备后、写入前再核验。普通任务与明确撤权后的真人接管保持原能力;缺少上下文或核验失败拒绝。这不回滚已经接受的外部写操作,不保证中断已派发原生执行或跨工具授权事务,也不改变独立 UI 的调度与通讯录管理。
- 取消只撤回自己的排队输入或其原生重试别名;停止前在 Session 锁内再次核对执行身份与插件权限。
- 请求跨账号切换后不能继续操作新账号数据库。禁用插件后不能继续发送或停止。
- 用户通过插件页或市场卸载时,在删除插件包前持久撤销其旧任务归属;保留任务、消息、作答文件、成绩和回执。正常更新保留归属;卸载重装后旧任务和旧 requestKey 不再可用,新请求键可创建新任务。撤销写入失败则不删除包;删除包失败时已撤销的归属不回滚。此处不改变内置插件 orphan/audience 自动回收路径。
@@ -50,6 +51,8 @@
### 主任务协调评测
+插件拥有的主任务通过公共 `start_team` 显式请求 Worker Full access 时,Host 在原确认入口前复用当前插件归属与 Auto 判据,直接返回 PERMISSION_DENIED,不弹确认、不更新全局偏好或创建团队。Auto/省略参数和普通用户任务的 Full access 确认保持原流程;已撤权任务仍按当前接受输入的来源判定,旧插件执行不会变成普通用户调用。
+
Worker 创建后至首条输入真正接受,继续核对实际解析的目录与模型路由;落盘、创建预留释放、Lead 激活和排队接收不会结束这次校验。异步来源/计划读取后同步复核当前目录授权,配置目录被取消或 picker 记录淘汰不能借旧检查放行。复用原创建失败补偿;排队后迟到拒绝只取消该输入,不删除已创建的 Worker。回调仅在 Host 内传递,不进入任务回执或 IPC 返回值。
模型调用的暂停 Worker、归档、结束团队与切换焦点,也复用当前输入来源和插件权限检查;关闭、归档及既有目录锁等待后的写入前复核。原有延后完成确认保存同次调用的核验回调,消费一次后不重登记;独立用户确认不继承模型限制。用户 UI/远程控制的停止清理及内部失败补偿保持原入口。多步清理途中拒绝可能已有局部效果,不构成跨工具授权事务,也不保证停止已接受的原生执行。
diff --git a/packages/lizi-mcps/src/account-data-access.ts b/packages/lizi-mcps/src/account-data-access.ts
new file mode 100644
index 0000000000..3ff75588ab
--- /dev/null
+++ b/packages/lizi-mcps/src/account-data-access.ts
@@ -0,0 +1,18 @@
+/** Host checks the calling task before account data is accessed and returned. */
+export type AccountDataAccess = <T>(sessionId: string | undefined, operation: (assertCurrent: () => Promise<void>) => Promise<T>) => Promise<T>;
+
+export async function withAccountDataAccess<T>(
+ access: AccountDataAccess | undefined,
+ sessionId: string | undefined,
+ operation: (assertCurrent: () => Promise<void>) => Promise<T>,
+): Promise<T | { isError: true; content: Array<{ type: 'text'; text: string }> }> {
+ if (!access) return operation(async () => {});
+ try {
+ return await access(sessionId, operation);
+ } catch {
+ // Do not return account data embedded in an error from a stale operation.
+ return { isError: true, content: [{ type: 'text', text: JSON.stringify({
+ ok: false, errorCode: 'CAPABILITY_NOT_AVAILABLE', message: 'Account data is unavailable for this task.',
+ }) }] };
+ }
+}
diff --git a/packages/lizi-mcps/src/cindy_contactsMcpServer.ts b/packages/lizi-mcps/src/cindy_contactsMcpServer.ts
index 97cf942900..e7f5498aa9 100644
--- a/packages/lizi-mcps/src/cindy_contactsMcpServer.ts
+++ b/packages/lizi-mcps/src/cindy_contactsMcpServer.ts
@@ -17,6 +17,7 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import { jsonObjectArg } from './json-object-arg.js';
+import { withAccountDataAccess } from './account-data-access.js';
import { ContactsToolRegistry } from './cindy_contactsToolRegistry.js';
import {
@@ -67,7 +68,7 @@ const D_CALL_TOOL =
const CATEGORY_ENUM = ['search', 'read', 'write', 'manage'] as const;
-function registerListToolsEntry(server: McpServer, registry: ContactsToolRegistry): void {
+function registerListToolsEntry(server: McpServer, registry: ContactsToolRegistry, deps: ContactsMcpDeps): void {
server.tool(
'list_tools',
D_LIST_TOOLS,
@@ -75,7 +76,7 @@ function registerListToolsEntry(server: McpServer, registry: ContactsToolRegistr
category: z.enum(CATEGORY_ENUM).optional().describe('工具类目, 不传时返回所有类目概览'),
},
{ readOnlyHint: true, destructiveHint: false },
- async ({ category }) => {
+ async ({ category }) => withAccountDataAccess(deps.withAccountDataAccess, deps.getSessionContext?.().sessionId, async () => {
if (category) {
const tools = registry.list(category);
// rules 去重: 同类多工具共享同一份规则文本时只下发一次
@@ -114,7 +115,7 @@ function registerListToolsEntry(server: McpServer, registry: ContactsToolRegistr
},
],
};
- },
+ }),
);
}
@@ -126,7 +127,7 @@ function registerCallToolEntry(server: McpServer, registry: ContactsToolRegistry
name: z.string().describe('工具名, 从 list_tools 获取 (e.g. contacts_resolve / contacts_search)'),
args: jsonObjectArg('工具参数 JSON; 不确定 schema 可先传 {} 触发反馈'),
},
- async ({ name, args }) => {
+ async ({ name, args }) => withAccountDataAccess(deps.withAccountDataAccess, deps.getSessionContext?.().sessionId, async () => {
const result = await registry.call(name, args);
// agent 经 MCP 直写同进程 store, 绕过 IPC 层的变更广播 — 这里按类目
// 兜底通知宿主(write/manage 均可能改库), 让设置页/管理浮层实时刷新
@@ -139,7 +140,7 @@ function registerCallToolEntry(server: McpServer, registry: ContactsToolRegistry
}
}
return result;
- },
+ }),
);
}
@@ -174,7 +175,7 @@ export function createCindyContactsMcpServer(deps: ContactsMcpDeps): McpServer {
registerContactsExportSystemTool(registry, deps);
registerContactsGroupTools(registry, deps);
- registerListToolsEntry(server, registry);
+ registerListToolsEntry(server, registry, deps);
registerCallToolEntry(server, registry, deps);
return server;
diff --git a/packages/lizi-mcps/src/cindy_schedulerMcpServer.ts b/packages/lizi-mcps/src/cindy_schedulerMcpServer.ts
index df217edcab..40c76dc906 100644
--- a/packages/lizi-mcps/src/cindy_schedulerMcpServer.ts
+++ b/packages/lizi-mcps/src/cindy_schedulerMcpServer.ts
@@ -40,6 +40,7 @@ import {
registerScheduleUpdateTool,
} from './scheduler/index.js';
import { resolveLiziMcpSessionContext } from './session-context.js';
+import { withAccountDataAccess, type AccountDataAccess } from './account-data-access.js';
import type { LiziMcpSessionContext, SchedulerMcpDeps } from './types.js';
/**
@@ -85,6 +86,8 @@ const CATEGORY_ENUM = ['scheduler'] as const;
function registerListToolsEntry(
server: McpServer,
registry: SchedulerToolRegistry,
+ access: AccountDataAccess | undefined,
+ getSessionContext: () => LiziMcpSessionContext,
): void {
server.tool(
'list_tools',
@@ -96,7 +99,7 @@ function registerListToolsEntry(
.describe('工具类目。不传时返回所有类目概览。'),
},
{ readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
- async ({ category }) => {
+ async ({ category }) => withAccountDataAccess(access, getSessionContext().sessionId, async () => {
if (category) {
const tools = registry.list(category);
return {
@@ -135,13 +138,15 @@ function registerListToolsEntry(
},
],
};
- },
+ }),
);
}
function registerCallToolEntry(
server: McpServer,
registry: SchedulerToolRegistry,
+ access: AccountDataAccess | undefined,
+ getSessionContext: () => LiziMcpSessionContext,
): void {
server.tool(
'call_tool',
@@ -152,7 +157,7 @@ function registerCallToolEntry(
.describe('工具名,从 list_tools 获取(如 schedule_create / schedule_list)'),
args: jsonObjectArg('工具参数(JSON 对象)。不确定 schema 时可先传 {} 触发错误反馈。'),
},
- async ({ name, args }) => registry.call(name, args),
+ async ({ name, args }) => withAccountDataAccess(access, getSessionContext().sessionId, () => registry.call(name, args)),
);
}
@@ -198,8 +203,8 @@ export function createSchedulerMcpServer(
registerScheduleNotifyCurrentRunTool(registry, deps, getSessionContext);
registerScheduleDeleteTool(registry, deps, getSessionContext);
- registerListToolsEntry(server, registry);
- registerCallToolEntry(server, registry);
+ registerListToolsEntry(server, registry, deps.withAccountDataAccess, getSessionContext);
+ registerCallToolEntry(server, registry, deps.withAccountDataAccess, getSessionContext);
return server;
}
diff --git a/packages/lizi-mcps/src/cindy_slackMcpServer.ts b/packages/lizi-mcps/src/cindy_slackMcpServer.ts
index 14aa88fdd8..2f0a4c7308 100644
--- a/packages/lizi-mcps/src/cindy_slackMcpServer.ts
+++ b/packages/lizi-mcps/src/cindy_slackMcpServer.ts
@@ -25,6 +25,7 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import { jsonObjectArg } from './json-object-arg.js';
+import { withAccountDataAccess } from './account-data-access.js';
import { PathBoundaryError, resolvePathInsideRoot } from './shared/assertInsidePath.js';
import type { SlackHookMcpDeps, SlackToolBridgeLike } from './types.js';
@@ -95,6 +96,7 @@ async function deliver(
data: unknown,
outFile: string | undefined,
workingDir: string | undefined,
+ assertCurrent: () => Promise<void>,
): Promise<SlackToolResult> {
const text = JSON.stringify(data ?? null);
if (outFile === undefined && text.length <= RESULT_MAX_CHARS) {
@@ -106,6 +108,8 @@ async function deliver(
const fileName = outFile ?? `slack-result-${Date.now().toString(36)}.json`;
const abs = await resolvePathInsideRoot(workingDir, fileName);
await fs.mkdir(path.dirname(abs), { recursive: true });
+ try { await assertCurrent(); }
+ catch { return errorResult('CAPABILITY_NOT_AVAILABLE', 'Account data is unavailable for this task.'); }
await fs.writeFile(abs, text, 'utf-8');
return jsonResult({
ok: true,
@@ -143,7 +147,7 @@ export function createSlackMcpGatewayServer(deps: SlackHookMcpDeps): McpServer {
const TEAM_ID_DESC =
'可选: 以哪个 Slack workspace 的绑定身份执行(bindings 列表见 slack_status)。设备绑定了多个 workspace 时必须传, 否则 server 拒绝猜测(AMBIGUOUS_TEAM); 只绑一个时可省略';
- server.tool('slack_status', descStatus.trim(), {}, async () => {
+ server.tool('slack_status', descStatus.trim(), {}, async () => withAccountDataAccess(deps.withAccountDataAccess, deps.getSessionContext?.().sessionId, async () => {
const bridge = requireBridge(deps);
if ('err' in bridge) return bridge.err;
const local = bridge.availability();
@@ -167,7 +171,7 @@ export function createSlackMcpGatewayServer(deps: SlackHookMcpDeps): McpServer {
const r = await bridge.callTool('status');
if (!r.ok) return errorResult(r.error.code, r.error.message);
return jsonResult({ ok: true, connected: true, ...(r.result as object) });
- });
+ }));
server.tool(
'slack_list_tools',
@@ -179,13 +183,14 @@ export function createSlackMcpGatewayServer(deps: SlackHookMcpDeps): McpServer {
.optional()
.describe('可选: 把完整清单 JSON 写进会话工作目录的该相对路径, 只返回文件路径'),
},
- async ({ team_id, out_file }) => {
+ async ({ team_id, out_file }) => withAccountDataAccess(deps.withAccountDataAccess, deps.getSessionContext?.().sessionId, async assertCurrent => {
const bridge = requireBridge(deps);
if ('err' in bridge) return bridge.err;
const r = await bridge.callTool('listTools', undefined, team_id ?? null);
+ await assertCurrent();
if (!r.ok) return errorResult(r.error.code, r.error.message);
- return deliver(r.result, out_file, deps.workingDir);
- },
+ return deliver(r.result, out_file, deps.workingDir, assertCurrent);
+ }),
);
server.tool(
@@ -202,20 +207,15 @@ export function createSlackMcpGatewayServer(deps: SlackHookMcpDeps): McpServer {
'可选: 把完整结果 JSON 写进会话工作目录的该相对路径(如 tmp/slack-result.json), 只返回文件路径 —— 结果大、要交给脚本处理时用。结果超 50KB 时即使不传也会自动落盘返回路径',
),
},
- async ({ name, arguments: toolArgs, team_id, out_file }) => {
+ async ({ name, arguments: toolArgs, team_id, out_file }) => withAccountDataAccess(deps.withAccountDataAccess, deps.getSessionContext?.().sessionId, async assertCurrent => {
const bridge = requireBridge(deps);
if ('err' in bridge) return bridge.err;
- const r = await bridge.callTool(
- 'callTool',
- {
- name,
- ...(toolArgs !== undefined ? { arguments: toolArgs } : {}),
- },
- team_id ?? null,
- );
+ const r = await bridge.callTool('callTool', { name, ...(toolArgs !== undefined ? { arguments: toolArgs } : {}) }, team_id ?? null);
+ // Recheck before returning private bytes or spilling them to the workdir.
+ await assertCurrent();
if (!r.ok) return errorResult(r.error.code, r.error.message);
- return deliver(r.result, out_file, deps.workingDir);
- },
+ return deliver(r.result, out_file, deps.workingDir, assertCurrent);
+ }),
);
return server;
diff --git a/packages/lizi-mcps/src/providers.ts b/packages/lizi-mcps/src/providers.ts
index 4c07590740..90b21cc2e2 100644
--- a/packages/lizi-mcps/src/providers.ts
+++ b/packages/lizi-mcps/src/providers.ts
@@ -325,6 +325,8 @@ export function createLiziMcpProviders(
name: 'cindy_slack',
instance: createSlackMcpGatewayServer({
getBridge: opts.slackHook!.getBridge,
+ withAccountDataAccess: opts.slackHook!.withAccountDataAccess,
+ getSessionContext: () => resolveLiziMcpSessionContext(ctx),
// 大结果落盘的钳制根: 绑定当前会话工作目录(空 = 只截断不落盘)
...(ctx.workingDir ? { workingDir: ctx.workingDir } : {}),
...(opts.slackHook!.logger !== undefined ? { logger: opts.slackHook!.logger } : {}),
@@ -336,8 +338,7 @@ export function createLiziMcpProviders(
if (opts.scheduler && selected(enabled, 'cindy_scheduler')) {
providers.push({
name: 'cindy_scheduler',
- // 第一版无门控:cc / codex 任何 session 都能用 schedule_* 工具。
- // 与 IPC 层 maker.schedule.* 同源(renderer 也是任何窗口都能调)。
+ // Host 可按实时任务来源限制账号调度数据;独立 Renderer IPC 保持原路径。
// 绑定 ctx 仅为 schedule_silence_current_run / schedule_notify_current_run 服务:
// 它们据 sessionId 反查本会话当前 in-flight run,免去 agent 传 runId
// (杜绝传参漂移 + caller-ownership)。
@@ -483,10 +484,10 @@ export function createLiziMcpProviders(
// token); Codex host 长生命周期下运行期关闭由 withContacts 的
// CONTACTS_NOT_READY 工具级拦截兜底。
...(opts.contacts.isEnabled ? { isEnabled: () => opts.contacts!.isEnabled!() } : {}),
- toClaudeSdkConfig: () => ({
+ toClaudeSdkConfig: (ctx) => ({
type: 'sdk',
name: 'cindy_contacts',
- instance: createCindyContactsMcpServer(opts.contacts!),
+ instance: createCindyContactsMcpServer({ ...opts.contacts!, getSessionContext: () => resolveLiziMcpSessionContext(ctx) }),
}),
});
}
diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.ts
index 32d940256c..4282c88633 100644
--- a/packages/lizi-mcps/src/types.ts
+++ b/packages/lizi-mcps/src/types.ts
@@ -201,6 +201,8 @@ export interface SlackToolBridgeLike {
* (大结果落盘的钳制根)。
*/
export interface SlackHookMcpDeps {
+ withAccountDataAccess?: import('./account-data-access.js').AccountDataAccess;
+ getSessionContext?: () => LiziMcpSessionContext;
getBridge(): SlackToolBridgeLike | null;
/** 当前会话工作目录(out_file 泄洪根; 空 = 不落盘只截断)。 */
workingDir?: string;
@@ -229,6 +231,7 @@ export interface RoutineToolService {
* @cindy/maker-scheduler still has zero runtime deps per Phase 1).
*/
export interface SchedulerMcpDeps {
+ withAccountDataAccess?: import('./account-data-access.js').AccountDataAccess;
getScheduler(): import('@cindy/maker-scheduler').Scheduler;
/**
* 前置检查脚本(preRunHook)统一安装服务(host 注入,desktop 实现为
@@ -405,8 +408,8 @@ export interface SshMcpDeps {
/**
* cindy_contacts(智能通讯录)MCP server 工厂参数。
*
- * 与 memory 的差异: 通讯录是全局单库(人不属于 workdir), 不需要 workdir /
- * getSessionContext。开关由 host 设置层注入 isEnabled — provider 注册门控 +
+ * 与 memory 的差异: 通讯录是全局单库(人不属于 workdir),调用上下文仅供 Host
+ * 核验账号数据访问边界。开关由 host 设置层注入 isEnabled — provider 注册门控 +
* withContacts 工具级双重拦截(Codex host 长生命周期下 server 可能已 spawn,
* 运行期关闭靠工具级拦截兜底, 跟 memory 的 MAKER_MEMORY_NOT_READY 同模式)。
*
@@ -414,6 +417,8 @@ export interface SshMcpDeps {
* vCard 序列化, workspace dep 已声明), 依赖方向仍单向 @cindy/mcps → maker-core。
*/
export interface ContactsMcpDeps {
+ withAccountDataAccess?: import('./account-data-access.js').AccountDataAccess;
+ getSessionContext?: () => LiziMcpSessionContext;
getManager(): import('@cindy/maker-core').MakerContactsManager;
/** host 设置层的功能开关. 缺省视为常开(测试/独立复用场景) */
isEnabled?: () => boolean;