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(teammates): bind hook confirmations to execution targets

Chris4355d5607d2b
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/taskActionAuthorization.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/taskActionAuthorization.test.ts
index 0cd7cc834a..5e9d005770 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/taskActionAuthorization.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/taskActionAuthorization.test.ts
@@ -308,10 +308,12 @@ function desktopFixture(kind: 'private' | 'group' | 'automatic' = 'group') {
});
const routines = new Map<string, { enabled: boolean; revision: number; prompt?: string; preRunCommand?: string }>();
const schedules = new Map<string, TaskActionScheduleDefinition>();
+ const workDirs = new Map([['companion', '/companion']]);
const authorize = createDesktopTaskActionAuthorizer({
input: () => ({ ...activeInput }), confirm, getSession,
capturePermissionRequest,
getScheduleDefinition: async id => structuredClone(schedules.get(id) ?? null),
+ getSessionWorkDir: async id => workDirs.get(id),
captureRoutine: async (_botId, id) => {
const row = routines.get(id);
if (!row) return undefined;
@@ -323,7 +325,7 @@ function desktopFixture(kind: 'private' | 'group' | 'automatic' = 'group') {
},
});
return { authorize, confirm, activeInput, caller, rows, runtime, getSession,
- permissionRequest, capturePermissionRequest, routines, schedules };
+ permissionRequest, capturePermissionRequest, routines, schedules, workDirs };
}
const ownerWrites = [
['cindy_helper', 'start_session_task'],
@@ -1019,7 +1021,7 @@ describe('teammate turn principal', () => {
expect(JSON.stringify(await withToolCallAuthority(h.authorize, request, install))).toContain('USER_CANCELLED');
expect(install).not.toHaveBeenCalled();
expect(h.confirm).toHaveBeenCalledWith('companion', request.tool, request.args,
- { server: 'cindy_helper', risk: 'command' });
+ { server: 'cindy_helper', risk: 'command', details: { installation: { workingDir: '/companion' } } });
h.confirm.mockResolvedValue(true);
expect(await withToolCallAuthority(h.authorize, request, install)).toBe('installed');
expect(install).toHaveBeenCalledTimes(1);
@@ -1029,6 +1031,77 @@ describe('teammate turn principal', () => {
expect(h.confirm).not.toHaveBeenCalled();
});
+ // r4409429594: installer inherits mutable target state after its card.
+ // Unit: production admission must show the target and reject a changed directory/path.
+ it('binds the scheduler hook installer decision to its actual schedule target', async () => {
+ const h = desktopFixture('automatic');
+ live(h);
+ const target = { id: 'bound', name: 'Bound check', executionMode: 'agent' as const,
+ targetSessionId: 'child', workingDir: '/schedule', preRunHook: { command: 'node old.mjs' },
+ hookInstallation: { workingDir: '/session', fallbackDir: '/fallback' } };
+ h.schedules.set('bound', target);
+ const request = { ...helper('schedule_set_pre_run_hook', { scheduleId: 'bound', script: 'process.exit(2)' }), server: 'cindy_scheduler' as const };
+ const install = vi.fn(async () => 'installed');
+ h.confirm.mockImplementation(async () => {
+ target.hookInstallation.workingDir = '/replacement';
+ target.preRunHook.command = 'node replacement.mjs';
+ return true;
+ });
+ expect(JSON.stringify(await withToolCallAuthority(h.authorize, request, install)))
+ .toContain('AUTHORIZATION_EXPIRED');
+ expect(install).not.toHaveBeenCalled();
+ expect(h.confirm).toHaveBeenCalledWith('companion', request.tool, request.args,
+ expect.objectContaining({ details: { schedule: expect.objectContaining({
+ targetSessionId: 'child', preRunHook: { command: 'node old.mjs' },
+ hookInstallation: { workingDir: '/session', fallbackDir: '/fallback' },
+ }) } }));
+ h.confirm.mockResolvedValue(true);
+ expect(await withToolCallAuthority(h.authorize, request, install)).toBe('installed');
+ expect(install).toHaveBeenCalledTimes(1);
+ });
+
+ // Helper deliberately accepts no scheduleId/workingDir: its actual target is the caller workspace.
+ it('binds the helper installation directory without granting a schedule target', async () => {
+ const h = desktopFixture('automatic');
+ live(h);
+ const request = helper('schedule_set_pre_run_hook', { script: 'process.exit(2)' });
+ const install = vi.fn(async () => 'installed');
+ h.confirm.mockImplementation(async () => {
+ h.workDirs.set('companion', '/replacement');
+ return true;
+ });
+ expect(JSON.stringify(await withToolCallAuthority(h.authorize, request, install)))
+ .toContain('AUTHORIZATION_EXPIRED');
+ expect(install).not.toHaveBeenCalled();
+ expect(h.confirm).toHaveBeenCalledWith('companion', request.tool, request.args,
+ { server: 'cindy_helper', risk: 'command', details: { installation: { workingDir: '/companion' } } });
+ h.confirm.mockResolvedValue(true);
+ expect(await withToolCallAuthority(h.authorize, request, install)).toBe('installed');
+ expect(install).toHaveBeenCalledTimes(1);
+ });
+
+ // r4409429587: ID-only manual execution runs the saved shell hook, not just a prompt.
+ // Existing save tests did not cover an enabled rule's command. Unit, real admission/effect.
+ it.each(['cindy_helper', 'cindy_scheduler'] as const)(
+ 'shows and confirms the saved routine command before %s manual execution', async server => {
+ const h = desktopFixture('automatic');
+ live(h);
+ h.routines.set('command', { enabled: true, revision: 3, prompt: 'Reviewed instructions', preRunCommand: 'node check.mjs' });
+ const request = { ...helper('routine_run_now', { botId: 'bot', id: 'command' }), server };
+ const execute = vi.fn(async () => taskActionRoutineRevision('bot', 'command'));
+ h.confirm.mockResolvedValue(false);
+ expect(JSON.stringify(await withToolCallAuthority(h.authorize, request, execute))).toContain('USER_CANCELLED');
+ expect(execute).not.toHaveBeenCalled();
+ expect(h.confirm).toHaveBeenCalledWith('companion', request.tool, request.args,
+ expect.objectContaining({ risk: 'command', details: { routine: expect.objectContaining({
+ id: 'command', preRunCommand: 'node check.mjs', revision: 3,
+ }) } }));
+ h.confirm.mockResolvedValue(true);
+ expect(await withToolCallAuthority(h.authorize, request, execute)).toBe(3);
+ expect(execute).toHaveBeenCalledTimes(1);
+ },
+ );
+
// Security r4409367066: saving instructions must not manufacture a standing
// owner grant for the next routine turn. Unit, production admission + effect.
it.each(['cindy_helper', 'cindy_scheduler'] as const)(
diff --git a/apps/desktop/src/main/maker-ipc/taskActionAuthorization.ts b/apps/desktop/src/main/maker-ipc/taskActionAuthorization.ts
index 4d12218451..d808986d7a 100644
--- a/apps/desktop/src/main/maker-ipc/taskActionAuthorization.ts
+++ b/apps/desktop/src/main/maker-ipc/taskActionAuthorization.ts
@@ -116,7 +116,9 @@ export const SCHEDULER_TASK_ACTION_TOOLS: ReadonlySet<string> = new Set([
export type TaskActionRisk = 'remove' | 'permission' | 'resume' | 'command' | 'authority';
export type TaskActionScheduleDefinition = Pick<Schedule,
- 'id' | 'name' | 'executionMode' | 'scriptConfig' | 'preRunHook' | 'workingDir' | 'targetSessionId'>;
+ 'id' | 'name' | 'executionMode' | 'scriptConfig' | 'preRunHook' | 'workingDir' | 'targetSessionId'> & {
+ hookInstallation?: { workingDir?: string; fallbackDir: string };
+ };
export interface TaskActionConfirmation {
server: string;
risk?: TaskActionRisk;
@@ -159,6 +161,7 @@ export function taskActionRisk(call: Pick<Call, 'server' | 'tool' | 'args'>,
return 'command';
}
}
+ if (call.tool === 'routine_run_now' && facts?.routinePreRunCommand?.trim()) return 'command';
const routineHook = args.preRunHook;
if (call.tool === 'routine_save' && routineHook && typeof routineHook === 'object' &&
'command' in routineHook && typeof routineHook.command === 'string' && routineHook.command.trim() &&
diff --git a/apps/desktop/src/main/maker-ipc/taskActionHost.ts b/apps/desktop/src/main/maker-ipc/taskActionHost.ts
index 06a1d27282..803dd335c7 100644
--- a/apps/desktop/src/main/maker-ipc/taskActionHost.ts
+++ b/apps/desktop/src/main/maker-ipc/taskActionHost.ts
@@ -113,7 +113,8 @@ export function createDesktopTaskActionAuthorizer(deps: {
confirm(sessionId: string, tool: string, args: unknown, context?: TaskActionConfirmation): Promise<boolean>;
capturePermissionRequest(sessionId: string, taskId: string): Promise<TaskActionTarget | null>;
captureRoutine(botId: string, id: string): Promise<TaskActionRoutineSnapshot | undefined>;
- getScheduleDefinition(id: string): Promise<TaskActionScheduleDefinition | null>;
+ getSessionWorkDir(sessionId: string): Promise<string | undefined>;
+ getScheduleDefinition(id: string, hookInstallation?: { workingDir?: string }): Promise<TaskActionScheduleDefinition | null>;
}): ToolCallAuthorizer {
return isolateTaskActionAuthorizer(async (call) => {
// Per invocation: a concurrent automatic call must never inherit owner evidence.
@@ -226,11 +227,17 @@ export function createDesktopTaskActionAuthorizer(deps: {
? await deps.captureRoutine(routineBotId, routineId) : undefined;
// Read saved commands for execution/partial updates; the card must show
// what a bare schedule ID will run, and a changed definition expires it.
+ const helperInstallation = principal === 'autonomous' && runtimePermissionApplies &&
+ call.server === 'cindy_helper' && call.tool === 'schedule_set_pre_run_hook';
+ const helperInstallDir = helperInstallation ? await deps.getSessionWorkDir(sessionId) : undefined;
+ const hookInstallation = call.server === 'cindy_scheduler' && call.tool === 'schedule_set_pre_run_hook'
+ ? { workingDir: typeof args.workingDir === 'string' ? args.workingDir : undefined } : undefined;
+ const scheduleIdArg = hookInstallation ? args.scheduleId : args.id;
const scheduleId = principal === 'autonomous' && runtimePermissionApplies &&
- call.server === 'cindy_scheduler' && (!args.device || args.device === 'local') &&
- ['schedule_update', 'schedule_run_now'].includes(call.tool) && typeof args.id === 'string'
- ? args.id : undefined;
- const schedule = scheduleId ? await deps.getScheduleDefinition(scheduleId) : undefined;
+ (hookInstallation || call.server === 'cindy_scheduler' && (!args.device || args.device === 'local') &&
+ ['schedule_update', 'schedule_run_now'].includes(call.tool)) && typeof scheduleIdArg === 'string'
+ ? scheduleIdArg : undefined;
+ const schedule = scheduleId ? await deps.getScheduleDefinition(scheduleId, hookInstallation) : undefined;
const scheduleSignature = JSON.stringify(schedule);
const readDelegation = async (rechecking = false) => {
if (
@@ -361,7 +368,9 @@ export function createDesktopTaskActionAuthorizer(deps: {
if (fingerprint !== taskActionFingerprint(call))
throw new Error('TASK_ACTION_AUTHORIZATION_EXPIRED');
await assertDeliveryCurrent();
- if (scheduleId && JSON.stringify(await deps.getScheduleDefinition(scheduleId)) !== scheduleSignature)
+ if (helperInstallation && await deps.getSessionWorkDir(sessionId) !== helperInstallDir)
+ throw new Error('TASK_ACTION_AUTHORIZATION_EXPIRED');
+ if (scheduleId && JSON.stringify(await deps.getScheduleDefinition(scheduleId, hookInstallation)) !== scheduleSignature)
throw new Error('TASK_ACTION_AUTHORIZATION_EXPIRED');
assertCurrentSync();
},
@@ -376,6 +385,7 @@ export function createDesktopTaskActionAuthorizer(deps: {
await scope.assertCurrent();
const confirmed = await deps.confirm(sessionId, call.tool, structuredClone(call.args),
{ server: call.server, risk, ...(permissionTarget ? { details: permissionTarget.details }
+ : helperInstallation ? { details: { installation: { workingDir: helperInstallDir ?? null } } }
: risk === 'command' && schedule ? { details: { schedule } }
: call.tool === 'routine_run_now' && routine?.details ? { details: routine.details } : {}) });
if (!confirmed) {
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index ca33ebe68f..e04551273c 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -309,17 +309,36 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
},
}));
+ // Share the installer's directory resolver with its reviewed target snapshot.
+ const resolveHookSessionWorkDir = async (sessionId: string) => {
+ try {
+ const { getMaker } = await import('../maker-host/index.js');
+ const meta = await getMaker().getSessionMeta(sessionId);
+ return meta?.workDir?.trim() ? meta.workDir : undefined;
+ } catch {
+ return undefined;
+ }
+ };
+
const authorizeTaskToolCall = createTaskToolCallAuthorizer({
getDb: () => (isAppSessionBoundaryPending() ? null : tryGetDbClient()),
isScopeCurrent: (db) => !isAppSessionBoundaryPending() && db === tryGetDbClient(),
authorizeAction: createDesktopTaskActionAuthorizer({
input: getTaskActionInputState, getSession: getTaskActionSession, confirm: confirmTaskAction,
capturePermissionRequest: captureTaskActionPermissionRequest,
- getScheduleDefinition: async id => {
+ getSessionWorkDir: resolveHookSessionWorkDir,
+ getScheduleDefinition: async (id, hookInstallation) => {
const schedule = await getScheduler().get(id);
if (!schedule) return null;
const { name, executionMode, scriptConfig, preRunHook, workingDir, targetSessionId } = schedule;
- return { id, name, executionMode, scriptConfig, preRunHook, workingDir, targetSessionId };
+ const definition = { id, name, executionMode, scriptConfig, preRunHook, workingDir, targetSessionId };
+ if (!hookInstallation) return definition;
+ let installWorkingDir = hookInstallation.workingDir;
+ if (!installWorkingDir && executionMode !== 'script' && targetSessionId)
+ installWorkingDir = await resolveHookSessionWorkDir(targetSessionId) ?? installWorkingDir;
+ const { app } = await import('electron');
+ return { ...definition, hookInstallation: { workingDir: installWorkingDir ?? workingDir,
+ fallbackDir: pathJoin(app.getPath('userData'), 'schedule-hooks') } };
},
captureRoutine: async (botId, id) => {
const engine = await getRoutineEngine();
@@ -525,15 +544,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
},
// 绑定会话(heartbeat)任务安装 hook 时解析会话真实工作目录 —— schedule
// 行上的 workingDir 为空/过期,落盘与自测必须用会话 meta.workDir。
- resolveSessionWorkDir: async (sessionId) => {
- try {
- const { getMaker } = await import('../maker-host/index.js');
- const meta = await getMaker().getSessionMeta(sessionId);
- return meta?.workDir?.trim() ? meta.workDir : undefined;
- } catch {
- return undefined;
- }
- },
+ resolveSessionWorkDir: resolveHookSessionWorkDir,
stabilizeCommand: async ({ command, workingDir }) => {
await assertPreRunHookCommandSyntax(command);
return stabilizeHookCommand(command, workingDir);
@@ -544,6 +555,8 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
import('../maker-host/index.js'),
import('electron'),
]);
+ // Recheck after target resolution and lazy imports, before any script write/self-test.
+ await assertTaskActionCurrent();
// maker 仅 description 生成模式需要;未就绪时传 null,script 模式照常工作,
// description 模式由生成器报"maker not ready"。
let maker = null;
diff --git a/docs/product-rules/teammate-authority.md b/docs/product-rules/teammate-authority.md
index c70c4126fe..bc66b7a5b9 100644
--- a/docs/product-rules/teammate-authority.md
+++ b/docs/product-rules/teammate-authority.md
@@ -19,7 +19,7 @@
| 风险 | 实际入口 |
| --- | --- |
-| 本机调度命令 | `schedule_create` / `schedule_update` 保存脚本执行或命令前置检查、`schedule_run_now` 执行含此类命令的已存定义、`cindy_helper` 和 `cindy_scheduler` 两个入口的 `schedule_set_pre_run_hook` 安装并自测脚本,以及 `routine_save` 保存新命令前置检查(沿用同一命令不追加确认) |
+| 本机调度命令 | `schedule_create` / `schedule_update` 保存脚本执行或命令前置检查、`schedule_run_now` 执行含此类命令的已存定义、`cindy_helper` 和 `cindy_scheduler` 两个入口的 `schedule_set_pre_run_hook` 安装并自测脚本,以及 `routine_save` 保存新命令前置检查(沿用同一命令不追加确认)、`routine_run_now` 手动执行含前置命令的已存规则 |
| 授予常驻指令 | `routine_save` 新建启用的自定义规则或改写启用规则的指令;禁用草稿和不改指令的编辑沿原权限 |
| 删除自动化 | `routine_delete`、`schedule_delete` |
| 代用户回答权限请求 | `message_session_task` 携带 `decision` |
@@ -29,7 +29,7 @@
主人输入、已核实的主人转达和受托指令沿正常权限审核,不再加第二张行动确认卡。
风险表不是平台权限、账号访问或消息来源认证的替代品。
本机调度的脚本及前置检查由宿主直接执行,不经过 Agent 的 Bash 审批;自主调用须展示命令、工作目录及准确动作,由主人决定。普通提示词自动化、提醒与只读工具不追加此类确认。
-按 ID 执行或修改时,卡片展示已存命令定义;确认期间定义变化使旧许可失效。跨电脑调度仍沿已有逐次任务权限流程。
+按 ID 执行或修改时,卡片展示已存命令定义;脚本安装按 `scheduleId` 展示目标、旧命令及绑定任务解析出的目录与后备落盘目录,并绑定同一快照;helper 安装器保持不接受 `scheduleId` 或外部目录,只展示并绑定调用伙伴自身的任务目录。确认期间定义或解析目录变化使旧许可失效,安装前再次复核。跨电脑调度仍沿已有逐次任务权限流程。
禁用草稿、重命名、改时间等不改常驻指令和命令的保存不追加授权;主人输入和受托指令仍沿原权限。
自主创建启用的自定义指令或改写启用规则指令,必须经一次性本人确认才可作为后续 entrusted 执行的常驻授权,不能靠保存制造主人授权。
停用草稿可普通保存;启用或手动执行前须确认完整指令。手动执行许可仅限这一次,不改变规则的停用状态。