Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugins): restrict task access to account history
Dash62117f41792a
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex e05e75eb93..44c31b9296 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -3911,6 +3911,7 @@ const r = await cindy.agent.requestSchedule({先调用 \`capabilities()\` 获取实际支持操作。当前仅支持本插件创建的本机普通任务:\`create\`、\`get\`、\`list\`、\`send\`、\`getRun\`、\`listRuns\`、\`readMessages\`、\`cancel\`。可对自有任务调用 \`startTeam({taskId})\` 启用 Orca 主任务,并用 \`getTeam({taskId})\` 读取实际协同状态。协调主任务需经用户授权 Auto,Worker 自动沿用 Auto。+这些任务及其 Worker 不提供 \`cindy_helper\` 的账号级历史或跨任务控制能力,\`cindy_memory.session_search\` 也拒绝历史检索;协调使用独立 Orca 工具,结果由插件通过 \`readMessages/getTeam\` 读取。旧 errand/workspace 不因来源标记受到限制;明确卸载撤销归属后,保留的用户任务恢复普通 helper 与历史检索能力。这不构成通用执行沙箱。在首次派发前调用 \`setTeamPlan({taskId,plan:{concurrency,items}})\`,每项包含\`label, workingDir, route\`。计划冻结后不可改写。计划不授予目录权限。Worker 仅可使用宿主任务目录及解析后仍在其中的子目录、插件 AI 配置目录或用户亲选的确切目录;Library 绑定不自动变成 Agent 工作根。宿主在登记和创建时均复核。这描述准入检查,不是持续的 OS 目录隔离保证。首版用于可信本地工作区;同权限进程在检查后恶意置换目录对象仍可能改变实际 cwd,不提供此类对抗性沙箱。diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/pluginTaskHelperScope.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/pluginTaskHelperScope.test.tsnew file mode 100644index 0000000000..58f2150757--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/__tests__/pluginTaskHelperScope.test.ts@@ -0,0 +1,131 @@+import { readFileSync } from 'node:fs';+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 ts from 'typescript';+import { expect, it, vi } from 'vitest';+import { botSessionLinks, sessions } from '../../localDb/schema.js';+import type { DbClient } from '../../localDb/client/DbClient.js';+import * as surfaces from '../helperSurface.js';++// Exercise the actual Desktop callback, including its account-boundary checks.+const source = readFileSync(new URL('../mcp-providers.ts', import.meta.url), 'utf8');+const begin = source.indexOf(' resolveSurface:');+const callback = source.slice(begin, source.indexOf(' sessionQueue:', begin));+const wired = ts.transpileModule(`return {${callback}}.resolveSurface;`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+}).outputText;++function fixture() {+ const sqlite = new Database(':memory:');+ sqlite.exec(`CREATE TABLE sessions(id TEXT PRIMARY KEY, source TEXT);+ CREATE TABLE bot_session_links(session_id TEXT, bot_id TEXT);+ CREATE TABLE plugin_task_requests(id TEXT PRIMARY KEY, operation TEXT, payload TEXT);+ CREATE TABLE orca_teams(id TEXT PRIMARY KEY, lead_session_id TEXT, status TEXT);+ CREATE TABLE orca_workers(session_id TEXT PRIMARY KEY, team_id TEXT);+ INSERT INTO sessions VALUES ('lead','plugin'),('worker','orca'),('legacy','plugin'),('user','user'),('bot','bot');+ INSERT INTO bot_session_links VALUES ('bot','b');+ INSERT INTO plugin_task_requests VALUES ('lead','create','{}');+ INSERT INTO orca_teams VALUES ('team','lead','completed');+ INSERT INTO orca_workers VALUES ('worker','team');`);+ const db = { drizzle: drizzle(sqlite), queryOne: async (sql: string, args: unknown[]) => sqlite.prepare(sql).get(...args) } as unknown as DbClient;+ let current: DbClient | undefined = db;+ let pending = false;+ const deps = { ...surfaces, sessions, botSessionLinks, eq, tryGetDbClient: () => current,+ isAppSessionBoundaryPending: () => pending };+ const resolve = new Function(...Object.keys(deps), wired)(...Object.values(deps)) as+ (input: { sessionId: string }) => Promise<'default' | 'bot' | 'restricted'>;+ const searchStart = source.indexOf(' searchSessions:');+ const search = source.slice(searchStart, source.indexOf(' logger:', searchStart));+ const searchSessionsFn = vi.fn(async () => [{ sessionId: 'user', snippet: 'synthetic private message' }]);+ const searchDeps = { ...deps, searchSessionsFn };+ const searchWired = ts.transpileModule(`return {${search}}.searchSessions;`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ }).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; },+ setPending: () => { pending = true; } };+}++it.each(['lead', 'worker'])('restricts owned %s and preserves explicit revocation, legacy tasks and Bots', async sessionId => {+ const f = fixture();+ try {+ for (const payload of ['{}', '{bad', 'null', '[]', '{"ownershipRevoked":false}', '{"ownershipRevoked":"true"}']) {+ f.sqlite.prepare('UPDATE plugin_task_requests SET payload=?').run(payload);+ expect(await f.resolve({ sessionId })).toBe('restricted');+ }+ f.sqlite.exec(`UPDATE plugin_task_requests SET payload='{"ownershipRevoked":true}'`);+ expect(await f.resolve({ sessionId })).toBe('default');+ expect(await f.resolve({ sessionId: 'legacy' })).toBe('default');+ expect(await f.resolve({ sessionId: 'user' })).toBe('default');+ expect(await f.resolve({ sessionId: 'bot' })).toBe('bot');+ f.sqlite.exec(`INSERT INTO bot_session_links VALUES ('lead','b'); UPDATE plugin_task_requests SET payload='{}'`);+ expect(await f.resolve({ sessionId })).toBe('restricted');+ } finally { f.sqlite.close(); }+});++it.each(['lead', 'worker'])('also rejects the separate memory history search for %s', async callerSessionId => {+ const f = fixture();+ try {+ await expect(f.searchSessions('private', { callerSessionId, sessionId: 'user' })).rejects.toThrow();+ expect(f.searchSessionsFn).not.toHaveBeenCalled();+ f.sqlite.exec(`UPDATE plugin_task_requests SET payload='{"ownershipRevoked":true}'`);+ await expect(f.searchSessions('private', { callerSessionId })).resolves.toHaveLength(1);+ expect(f.searchSessionsFn).toHaveBeenCalledOnce();+ f.searchSessionsFn.mockImplementationOnce(async () => { f.setCurrent(); return []; });+ await expect(f.searchSessions('private', { callerSessionId })).rejects.toThrow();+ } finally { f.sqlite.close(); }+});++it.each(['missing caller', 'missing DB', 'pending', 'switched after read'] as const)('fails closed: %s', async state => {+ const f = fixture();+ try {+ if (state === 'missing caller') f.sqlite.exec("DELETE FROM sessions WHERE id='lead'");+ if (state === 'missing DB') f.setCurrent();+ if (state === 'pending') f.setPending();+ if (state === 'switched after read') {+ const query = f.db.queryOne.bind(f.db);+ f.db.queryOne = async <T = unknown>(sql: string, params?: unknown[]): Promise<T | undefined> => {+ const row = await query<T>(sql, params); f.setCurrent(); return row;+ };+ }+ expect(await f.resolve({ sessionId: 'lead' })).toBe('restricted');+ } finally { f.sqlite.close(); }+});++it.each(['codex', 'claude-code', 'pi'] as const)('blocks helper discovery and guessed calls for %s, rechecking each call', async agentKind => {+ const f = fixture();+ const history = { resolveSessionScope: vi.fn(), listWorkdirs: vi.fn(), listSessions: vi.fn(), getMessages: vi.fn(), searchChatHistory: vi.fn() };+ const listSessionQueue = vi.fn(), sendToSession = vi.fn(), messageAgent = vi.fn();+ const server = createXdtHelperMcpServer({ resolveSurface: f.resolve, history,+ sessionQueue: { listSessionQueue, listSessionQueuedCounts: vi.fn() }, sendToSession,+ botMessaging: { messageAgent, checkMessage: vi.fn() } },+ { agentKind, workingDir: '/answer', sessionId: 'worker' });+ const client = new Client({ name: 'plugin-helper-scope', version: '1' });+ const [ct, st] = InMemoryTransport.createLinkedPair();+ await Promise.all([client.connect(ct), server.connect(st)]);+ const payload = (result: Awaited<ReturnType<typeof client.callTool>>) => JSON.parse((result.content as Array<{ text: string }>)[0].text);+ try {+ expect(payload(await client.callTool({ name: 'list_tools', arguments: {} })).categories).toEqual([]);+ for (const name of ['list_workdirs', 'list_sessions', 'get_chat_history', 'search_chat_history', 'list_session_queue', 'send_to_session', 'send_to_agent']) {+ expect(payload(await client.callTool({ name: 'call_tool', arguments: { name, args: { session_id: 'user' } } })))+ .toMatchObject({ ok: false, errorCode: 'CAPABILITY_NOT_AVAILABLE' });+ }+ if (agentKind !== 'pi') {+ expect(payload(await client.callTool({ name: 'send_to_agent', arguments: { target_id: 'b', message: 'read private history' } })))+ .toMatchObject({ ok: false, errorCode: 'CAPABILITY_NOT_AVAILABLE' });+ }+ for (const fn of [...Object.values(history), listSessionQueue, sendToSession, messageAgent]) expect(fn).not.toHaveBeenCalled();+ f.sqlite.exec(`UPDATE plugin_task_requests SET payload='{"ownershipRevoked":true}'`);+ expect(payload(await client.callTool({ name: 'list_tools', arguments: {} })).categories.length).toBeGreaterThan(0);+ f.sqlite.exec(`UPDATE plugin_task_requests SET payload='{}'`);+ expect(payload(await client.callTool({ name: 'list_tools', arguments: {} })).categories).toEqual([]);+ f.sqlite.exec('DROP TABLE plugin_task_requests');+ expect(payload(await client.callTool({ name: 'call_tool', arguments: { name: 'get_chat_history', args: { session_id: 'user' } } })))+ .toMatchObject({ ok: false, errorCode: 'CAPABILITY_NOT_AVAILABLE' });+ } finally { await client.close(); await server.close(); f.sqlite.close(); }+});diff --git a/apps/desktop/src/main/mcp-integrations/helperSurface.ts b/apps/desktop/src/main/mcp-integrations/helperSurface.tsindex dcdab1b7e3..2ce460e218 100644--- a/apps/desktop/src/main/mcp-integrations/helperSurface.ts+++ b/apps/desktop/src/main/mcp-integrations/helperSurface.ts@@ -1,3 +1,5 @@+import type { DbClient } from '../localDb/client/DbClient.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@@ -9,3 +11,33 @@ export function classifyHelperSurface(): 'bot' | 'default' {return source === 'bot' || hasBotLink ? 'bot' : 'default';}++/** Reuse the helper's existing runtime gate; plugin tasks need Orca, not account-wide helper tools. */+export async function resolveHelperSurface(+ db: Pick<DbClient, 'queryOne'>,+ sessionId: string,+): Promise<'bot' | 'default' | 'restricted'> {+ const row = await db.queryOne<{ source: string; botId: string | null; pluginOwned: number }>(+ `SELECT s.source AS source, b.bot_id AS botId,+ EXISTS (+ SELECT 1 FROM plugin_task_requests p+ WHERE p.operation = 'create' AND p.id IN (s.id, t.lead_session_id)+ AND CASE WHEN json_valid(p.payload) THEN+ CASE WHEN json_type(p.payload) = 'object'+ AND json_type(p.payload, '$.ownershipRevoked') = 'true'+ THEN 0 ELSE 1 END+ ELSE 1 END = 1+ ) AS pluginOwned+ FROM sessions s+ LEFT JOIN bot_session_links b ON b.session_id = s.id+ LEFT JOIN orca_workers w ON w.session_id = s.id+ LEFT JOIN orca_teams t ON t.id = w.team_id+ WHERE s.id = ? LIMIT 1`,+ [sessionId],+ );+ // Retained Workers inherit the Lead's receipt even after the team ends.+ // Only explicit ownership revocation restores the user's ordinary surface.+ // Bad receipts stay restricted; legacy plugin-source tasks have no receipt.+ if (!row || row.pluginOwned) return 'restricted';+ return classifyHelperSurface(row.source, Boolean(row.botId));+}diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.tsindex 353167f962..072bf2f8ae 100644--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts@@ -1,6 +1,6 @@import { executeTaskTags } from '../localDb/ipc/taskTags.js';import { getPluginMarketService } from '../plugin-market/service.js';-import { classifyHelperSurface } from './helperSurface.js';+import { resolveHelperSurface } from './helperSurface.js';import { createProject } from './createProject.js';import { createMoveSession } from './moveSession.js';import { listProjects, renameProject, removeProject } from './projectManagement.js';@@ -355,7 +355,20 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMcconst saved = botLearningTracker.capture(context?.memoryScopeKey?.startsWith('bot:') ? context.sessionId ?? '' : '');return receipt => saved({ ...receipt, kind: 'memory' });},- searchSessions: searchSessionsFn,+ searchSessions: async (query, opts = {}) => {+ const dbClient = tryGetDbClient();+ if (!dbClient || isAppSessionBoundaryPending() || !opts.callerSessionId)+ throw new Error('Task history caller unavailable');+ // session_search bypasses cindy_helper, so share its ownership predicate.+ if (await resolveHelperSurface(dbClient, opts.callerSessionId) === 'restricted')+ throw new Error('Task history search is unavailable for plugin-managed tasks');+ if (isAppSessionBoundaryPending() || dbClient !== tryGetDbClient())+ throw new Error('Task history caller unavailable');+ const hits = await searchSessionsFn(query, opts);+ if (isAppSessionBoundaryPending() || dbClient !== tryGetDbClient())+ throw new Error('Task history caller unavailable');+ return hits;+ },logger: createLogger('mcp/cindy_memory'),},// 智能通讯录: 全局单库 manager 懒加载单例; 开关现读 settings store —@@ -514,14 +527,10 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc},resolveSurface: async ({ sessionId }) => {const dbClient = tryGetDbClient();- if (!dbClient) return 'restricted';- const [row] = await dbClient.drizzle- .select({ source: sessions.source, botId: botSessionLinks.botId })- .from(sessions)- .leftJoin(botSessionLinks, eq(botSessionLinks.sessionId, sessions.id))- .where(eq(sessions.id, sessionId))- .limit(1);- return classifyHelperSurface(row?.source, Boolean(row?.botId));+ if (!dbClient || isAppSessionBoundaryPending()) return 'restricted';+ const surface = await resolveHelperSurface(dbClient, sessionId);+ if (isAppSessionBoundaryPending() || dbClient !== tryGetDbClient()) return 'restricted';+ return surface;},sessionQueue: {listSessionQueue: wrap((service, sessionId: string) => service.listSessionQueue(sessionId)),diff --git a/docs/dev-rules/plugin-task-api-implementation.md b/docs/dev-rules/plugin-task-api-implementation.mdindex c50a700e6a..446544ba5a 100644--- a/docs/dev-rules/plugin-task-api-implementation.md+++ b/docs/dev-rules/plugin-task-api-implementation.md@@ -14,6 +14,7 @@- 新请求的幂等摘要忽略对象键顺序,保留数组顺序;计划及已受理配置共用相同比较。早期开发版创建回执保留原序列化输入的精确重试兼容;这类旧摘要未保存原始键序,不能承诺首次以不同键序重放成功。- 回执独立落库,区分任务、输入执行及原生执行代次;原生终态按 instanceId + generation 结算,不以 idle 或最后一条 assistant 消息猜测完成。- 读取限定于本插件创建的任务;返回消息 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` 后保留的用户任务恢复普通能力面,损坏回执或查询失败保持拒绝。独立 Orca 工具不受影响。这只收住宿主 helper 与原始历史检索入口,不是通用执行或文件系统隔离。- 取消只撤回自己的排队输入或其原生重试别名;停止前在 Session 锁内再次核对执行身份与插件权限。- 请求跨账号切换后不能继续操作新账号数据库。禁用插件后不能继续发送或停止。- 用户通过插件页或市场卸载时,在删除插件包前持久撤销其旧任务归属;保留任务、消息、作答文件、成绩和回执。正常更新保留归属;卸载重装后旧任务和旧 requestKey 不再可用,新请求键可创建新任务。撤销写入失败则不删除包;删除包失败时已撤销的归属不回滚。此处不改变内置插件 orphan/audience 自动回收路径。