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(desktop): 收紧远程 IM turn 权限边界

nana85842ff762c0
diff --git a/apps/desktop/src/main/__tests__/destructiveGuard.test.ts b/apps/desktop/src/main/__tests__/destructiveGuard.test.ts
index 1dd332aa2e..13110b7c47 100644
--- a/apps/desktop/src/main/__tests__/destructiveGuard.test.ts
+++ b/apps/desktop/src/main/__tests__/destructiveGuard.test.ts
@@ -64,6 +64,13 @@ describe('checkDestructiveToolCall — Bash command match', () => {
});
}
+ it('matches Pi lowercase bash with the same deletion rules', () => {
+ expect(checkDestructiveToolCall('bash', { command: 'rm -rf build' })).toEqual({
+ destructive: true,
+ reason: 'shell command contains `rm`',
+ });
+ });
+
const allowCommands = [
'ls -la',
'cat package.json',
diff --git a/apps/desktop/src/main/destructiveGuard.ts b/apps/desktop/src/main/destructiveGuard.ts
index acc746cc29..8ac4684c32 100644
--- a/apps/desktop/src/main/destructiveGuard.ts
+++ b/apps/desktop/src/main/destructiveGuard.ts
@@ -40,7 +40,11 @@ const SHELL_COMMAND_PATTERNS: ReadonlyArray<{ pattern: RegExp; label: string }>
{ pattern: /\bgit\s+clean\s+-[a-zA-Z]*f/, label: 'git clean -f' },
];
-const SHELL_TOOL_NAMES = new Set(['Bash', 'PowerShell']);
+// 大小写不敏感:Claude 的 shell 工具名是 `Bash`,Pi 的内置工具全小写 `bash`
+// (见 packages/maker-core/src/agents/pi/auto-review-policy.ts)。集合按小写存,
+// 比较前把 toolName 归一化 —— 否则 `checkDestructiveToolCall('bash', {command:'rm -rf …'})`
+// 不命中任何规则,微信/Telegram 远程渠道对 Pi 的删除类命令红线被直接击穿。
+const SHELL_TOOL_NAMES = new Set(['bash', 'powershell']);
export interface GuardResult {
destructive: boolean;
@@ -62,8 +66,8 @@ export function checkDestructiveToolCall(
return { destructive: true, reason: `tool name contains "${toolNameMatch[0]}"` };
}
- // 2. Bash / PowerShell 命令文本匹配
- if (SHELL_TOOL_NAMES.has(toolName) && input && typeof input === 'object') {
+ // 2. Bash / PowerShell 命令文本匹配(工具名大小写不敏感:Claude `Bash` / Pi `bash`)
+ if (SHELL_TOOL_NAMES.has(toolName.toLowerCase()) && input && typeof input === 'object') {
const cmd = (input as { command?: unknown }).command;
if (typeof cmd === 'string' && cmd.length > 0) {
for (const { pattern, label } of SHELL_COMMAND_PATTERNS) {
diff --git a/apps/desktop/src/main/im/dingtalk/__tests__/permissionPolicy.test.ts b/apps/desktop/src/main/im/dingtalk/__tests__/permissionPolicy.test.ts
index fe956286b2..f91555f271 100644
--- a/apps/desktop/src/main/im/dingtalk/__tests__/permissionPolicy.test.ts
+++ b/apps/desktop/src/main/im/dingtalk/__tests__/permissionPolicy.test.ts
@@ -12,5 +12,20 @@ describe('dingtalk turn permission policy', () => {
});
expect(policy.forceConfirmToolCall?.('file_change', {})).toBe(true);
expect(policy.forceConfirmToolCall?.('permissions', {})).toBe(true);
+ expect(policy.forceConfirmToolCall?.('bash', { command: 'rm -rf build' })).toBe(true);
+ expect(policy.forceConfirmToolCall?.('mcp__cindy_contacts__call_tool', {
+ name: 'contacts_delete',
+ args: { id: 'contact-1' },
+ })).toBe(true);
+ expect(policy.forceConfirmToolCall?.('mcp__cindy__ghost_call', {
+ ghost_id: 'files',
+ tool: 'call_tool',
+ args: {
+ name: 'bash',
+ args: { command: 'rm -rf generated' },
+ },
+ })).toBe(true);
+ expect(policy.forceConfirmToolCall?.('write', { path: 'notes.md', content: 'safe' })).toBe(false);
+ expect(policy.forceConfirmToolCall?.('edit', { path: 'notes.md', oldText: 'a', newText: 'b' })).toBe(false);
});
});
diff --git a/apps/desktop/src/main/im/dingtalk/permissionPolicy.ts b/apps/desktop/src/main/im/dingtalk/permissionPolicy.ts
index bda161f11c..fe85869ae9 100644
--- a/apps/desktop/src/main/im/dingtalk/permissionPolicy.ts
+++ b/apps/desktop/src/main/im/dingtalk/permissionPolicy.ts
@@ -1,11 +1,6 @@
import type { TurnPermissionPolicy } from '@cindy/maker-core';
-import { checkDestructiveToolCall } from '../../destructiveGuard';
-
-function record(value: unknown): Record<string, unknown> | null {
- if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
- return value as Record<string, unknown>;
-}
+import { channelForceConfirmToolCall } from '../shared/channelToolPolicy';
/**
* DingTalk group turns carry an explicit confirmation boundary for destructive
@@ -13,32 +8,16 @@ function record(value: unknown): Record<string, unknown> | null {
* the session permission mode, matching Feishu and Telegram private chats.
* Group sessions configured with an incompatible unattended permission mode
* fail closed in maker-core.
+ *
+ * Detection is shared with WeChat / Telegram via channelForceConfirmToolCall
+ * (nested unwrap covers Claude call_tool, Codex MCP elicitation, and Pi bridged
+ * MCP / secondary-dispatch plugins).
*/
export function createDingTalkTurnPermissionPolicy(taskId: string): TurnPermissionPolicy {
return {
origin: { kind: 'im', channel: 'dingtalk', taskId },
confirmationSurface: 'channel',
confirmationTimeoutMs: 30 * 60 * 1_000,
- forceConfirmToolCall(toolName, input) {
- const direct = checkDestructiveToolCall(toolName, record(input));
- if (direct.destructive) return true;
-
- const outer = record(input);
- const nested = record(outer?.toolParams);
- const innerName =
- typeof nested?.name === 'string'
- ? nested.name
- : typeof outer?.name === 'string'
- ? outer.name
- : null;
- if (
- innerName &&
- (checkDestructiveToolCall(innerName, nested ?? outer).destructive ||
- /(?:^|_)(?:merge|system_write|overwrite)(?:_|$)/i.test(innerName))
- ) {
- return true;
- }
- return toolName === 'file_change' || toolName === 'permissions';
- },
+ forceConfirmToolCall: channelForceConfirmToolCall,
};
}
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
index 5775176f07..21df237d50 100644
--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
@@ -7,6 +7,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type {
AgentEvent,
+ InteractionDecision,
+ InteractionRequest,
MakerEvent,
Session,
SessionSendResult,
@@ -170,7 +172,10 @@ interface SessionHarness {
isTurnRunning: ReturnType<typeof vi.fn>;
/** maker-core Session.abort 的 mock — !stop 中止路径断言用。 */
abort: ReturnType<typeof vi.fn>;
+ acquireTurnLease: ReturnType<typeof vi.fn>;
+ releaseTurnLease: ReturnType<typeof vi.fn>;
emit(event: AgentEvent): void;
+ dispatchInteraction(request: InteractionRequest): Promise<InteractionDecision>;
}
function createSessionHarness(
@@ -192,12 +197,16 @@ function createSessionHarness(
});
const isTurnRunning = vi.fn(() => false);
const abort = vi.fn(async () => undefined);
+ const releaseTurnLease = vi.fn();
+ const acquireTurnLease = vi.fn(() => releaseTurnLease);
+ let interactionListener: Parameters<Session['setInteractionListener']>[0] = null;
const session = {
id: sessionId,
agentKind: 'claude-code',
send,
isTurnRunning,
abort,
+ acquireTurnLease,
onEvent(listener: (event: AgentEvent) => void) {
listeners.push(listener);
return () => {
@@ -205,7 +214,9 @@ function createSessionHarness(
if (index >= 0) listeners.splice(index, 1);
};
},
- setInteractionListener: vi.fn(),
+ setInteractionListener: vi.fn((listener) => {
+ interactionListener = listener;
+ }),
close: vi.fn(async () => undefined),
} as unknown as Session;
@@ -214,9 +225,15 @@ function createSessionHarness(
send,
isTurnRunning,
abort,
+ acquireTurnLease,
+ releaseTurnLease,
emit(event: AgentEvent) {
for (const listener of [...listeners]) listener(event);
},
+ async dispatchInteraction(request) {
+ if (!interactionListener) throw new Error('interaction listener not installed');
+ return interactionListener(request);
+ },
};
}
@@ -607,6 +624,187 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
expect(isHeadlessGhostSetupTurn('feishu-session')).toBe(false);
});
+ it('holds a host turn lease and applies channel policy timeout/state metadata', async () => {
+ const h = setupSession(async () => ({ accepted: true }));
+ const handleTextInteraction = vi.fn(async () => ({
+ kind: 'permission',
+ behavior: 'allow',
+ } as const));
+ const commitFinal = vi.fn(async () => undefined);
+ const channelAdapter: ImChannelAdapter = {
+ ...fakeAdapter,
+ channel: 'wechat',
+ output: {
+ kind: 'chunked-text',
+ im: mocks.feishuIm as unknown as ChannelIM,
+ commitFinal,
+ },
+ handleTextInteraction,
+ };
+ const localRunner = createTurnRunner(channelAdapter, fakeRepo, fakeCards);
+ const states: string[] = [];
+ try {
+ await localRunner.runAgentTurn({
+ botContextId: 'cli_test_bot',
+ userId: 'ou_user',
+ userMessageId: 'msg-policy',
+ text: 'run with policy',
+ attachments: [],
+ turnPermissionPolicy: {
+ origin: { kind: 'im', channel: 'wechat', taskId: 'task-policy' },
+ confirmationSurface: 'channel',
+ confirmationTimeoutMs: 12_345,
+ onInteractionStateChange: (state) => states.push(state),
+ forceConfirmToolCall: () => true,
+ },
+ });
+
+ expect(h.acquireTurnLease).toHaveBeenCalledOnce();
+ const request: InteractionRequest = {
+ kind: 'permission',
+ requestId: 'interaction-policy',
+ toolName: 'bash',
+ input: { command: 'pnpm test' },
+ };
+ await expect(h.dispatchInteraction(request)).resolves.toEqual({
+ kind: 'permission',
+ behavior: 'allow',
+ });
+ expect(handleTextInteraction).toHaveBeenCalledWith('ou_user', request, {
+ timeoutMs: 12_345,
+ });
+ expect(states).toEqual(['waiting', 'resolved']);
+
+ h.emit({ type: 'done', data: {} });
+ await waitForAssertion(() => expect(h.releaseTurnLease).toHaveBeenCalledOnce());
+ } finally {
+ await localRunner.disposeAllSessions();
+ }
+ });
+
+ it('hard-denies destructive actions nested inside a channel dispatch wrapper', async () => {
+ const h = setupSession(async () => ({ accepted: true }));
+ mocks.checkDestructiveToolCall.mockImplementation((toolName, input) =>
+ toolName === 'bash' &&
+ input &&
+ typeof input.command === 'string' &&
+ /\brm\b/.test(input.command)
+ ? { destructive: true, reason: 'shell command contains `rm`' }
+ : { destructive: false },
+ );
+ const handleTextInteraction = vi.fn(async () => ({
+ kind: 'permission',
+ behavior: 'allow',
+ } as const));
+ const channelAdapter: ImChannelAdapter = {
+ ...fakeAdapter,
+ channel: 'wechat',
+ output: {
+ kind: 'chunked-text',
+ im: mocks.feishuIm as unknown as ChannelIM,
+ commitFinal: vi.fn(async () => undefined),
+ },
+ handleTextInteraction,
+ };
+ const localRunner = createTurnRunner(channelAdapter, fakeRepo, fakeCards);
+ try {
+ await localRunner.runAgentTurn({
+ botContextId: 'cli_test_bot',
+ userId: 'ou_user',
+ userMessageId: 'msg-policy-hard-deny',
+ text: 'run with policy',
+ attachments: [],
+ turnPermissionPolicy: {
+ origin: { kind: 'im', channel: 'wechat', taskId: 'task-hard-deny' },
+ confirmationSurface: 'channel',
+ forceConfirmToolCall: () => true,
+ },
+ });
+
+ const decision = await h.dispatchInteraction({
+ kind: 'permission',
+ requestId: 'interaction-hard-deny',
+ toolName: 'mcp__cindy__ghost_call',
+ input: {
+ ghost_id: 'files',
+ tool: 'call_tool',
+ args: { name: 'bash', args: { command: 'rm -rf generated' } },
+ },
+ });
+ expect(decision).toMatchObject({
+ kind: 'permission',
+ behavior: 'deny',
+ });
+ expect(handleTextInteraction).not.toHaveBeenCalled();
+ } finally {
+ h.emit({ type: 'done', data: {} });
+ await localRunner.disposeAllSessions();
+ }
+ });
+
+ it('cancels channel-owned text confirmation and releases its lease on session cleanup', async () => {
+ const h = setupSession(async () => ({ accepted: true }));
+ let resolveTextInteraction!: (decision: InteractionDecision) => void;
+ const handleTextInteraction = vi.fn(
+ async () => new Promise<InteractionDecision>((resolve) => {
+ resolveTextInteraction = resolve;
+ }),
+ );
+ const cancelTextInteraction = vi.fn(
+ (_userId: string, _requestId: string, decision: InteractionDecision) => {
+ resolveTextInteraction(decision);
+ return true;
+ },
+ );
+ const channelAdapter: ImChannelAdapter = {
+ ...fakeAdapter,
+ channel: 'wechat',
+ output: {
+ kind: 'chunked-text',
+ im: mocks.feishuIm as unknown as ChannelIM,
+ commitFinal: vi.fn(async () => undefined),
+ },
+ handleTextInteraction,
+ cancelTextInteraction,
+ };
+ const localRunner = createTurnRunner(channelAdapter, fakeRepo, fakeCards);
+
+ await localRunner.runAgentTurn({
+ botContextId: 'cli_test_bot',
+ userId: 'ou_user',
+ userMessageId: 'msg-policy-cleanup',
+ text: 'run with policy',
+ attachments: [],
+ turnPermissionPolicy: {
+ origin: { kind: 'im', channel: 'wechat', taskId: 'task-policy-cleanup' },
+ confirmationSurface: 'channel',
+ confirmationTimeoutMs: 30_000,
+ forceConfirmToolCall: () => true,
+ },
+ });
+ const request: InteractionRequest = {
+ kind: 'permission',
+ requestId: 'interaction-cleanup',
+ toolName: 'bash',
+ input: { command: 'pnpm test' },
+ };
+ const decision = h.dispatchInteraction(request);
+ await waitForAssertion(() => expect(handleTextInteraction).toHaveBeenCalledOnce());
+
+ await localRunner.disposeAllSessions();
+ await expect(decision).resolves.toMatchObject({
+ kind: 'permission',
+ behavior: 'deny',
+ reason: 'session_cleanup',
+ });
+ expect(cancelTextInteraction).toHaveBeenCalledWith(
+ 'ou_user',
+ 'interaction-cleanup',
+ expect.objectContaining({ behavior: 'deny', reason: 'session_cleanup' }),
+ );
+ expect(h.releaseTurnLease).toHaveBeenCalledOnce();
+ });
+
it('does not reacquire attached IM headless state from a late acceptance callback', async () => {
let lateOnAccepted: NonNullable<Parameters<Session['send']>[1]>['onAccepted'];
const h = setupAttachedSession(async () => ({
diff --git a/apps/desktop/src/main/im/shared/channelToolPolicy.ts b/apps/desktop/src/main/im/shared/channelToolPolicy.ts
new file mode 100644
index 0000000000..280a8a1c68
--- /dev/null
+++ b/apps/desktop/src/main/im/shared/channelToolPolicy.ts
@@ -0,0 +1,124 @@
+/**
+ * channelToolPolicy.ts
+ * ---------------------------------------------------------------------------
+ * 渠道 per-turn 权限策略(个人微信 / Telegram 群 / 钉钉群)共用的
+ * `forceConfirmToolCall` 判定。三个渠道此前各自内联了一份几乎相同的嵌套解包,
+ * 且只认 Claude `call_tool`(input.name)与 Codex MCP elicitation
+ * (input.toolParams.name)两种 wrapper —— 对 Pi 的桥接 MCP 与二级分派插件
+ * (`ghost_call{tool}` / `call_tool{name}`)不覆盖,破坏性操作名藏在 input.tool /
+ * input.args.name 里时会漏判(设计方案 §7.8)。
+ *
+ * 收敛到这里一处,保证任何声明 turnPermissionPolicy 的 agent(CC/Codex/Pi)在所有
+ * 渠道用同一份工具词表判定,不会出现"为某渠道实现、别的渠道意外开闸"。
+ */
+
+import {
+ checkDestructiveToolCall,
+ type GuardResult,
+} from '../../destructiveGuard';
+
+function record(value: unknown): Record<string, unknown> | null {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ return value as Record<string, unknown>;
+}
+
+/**
+ * 二级分派 / 包装工具里,内层动作名常带这些语义 —— 它们不含 delete/remove 词根,
+ * 却同样会不可逆地改写内容,保守地强制确认。
+ */
+const DESTRUCTIVE_INNER_NAME_RE = /(?:^|_)(?:merge|system_write|overwrite)(?:_|$)/i;
+
+/** 一个待判定的内层调用:动作名 + 供 shell 命令检查的入参对象。 */
+interface InnerCall {
+ name: string;
+ args: Record<string, unknown> | null;
+}
+
+function dispatcherKind(toolName: string): 'call-tool' | 'ghost-call' | null {
+ const normalized = toolName.toLowerCase();
+ if (normalized === 'call_tool' || normalized.endsWith('__call_tool')) return 'call-tool';
+ if (normalized === 'ghost_call' || normalized.endsWith('__ghost_call')) return 'ghost-call';
+ return null;
+}
+
+/**
+ * 从一次工具调用的 input 里剥出所有可能的"内层真实动作"。覆盖:
+ * - Codex MCP elicitation:input.toolParams.name(+ toolParams.args)
+ * - Claude / Pi `call_tool`:input.name(+ input.args)
+ * - Pi `ghost_call`:input.tool(+ input.args)
+ * - 二级分派再嵌套(如 ghost_call{tool:'call_tool', args:{name}}):对 args 递归下探
+ * depth 上限防御畸形/自引用输入。
+ */
+function* unwrapInnerCalls(
+ outerToolName: string,
+ input: unknown,
+ depth = 0,
+): Generator<InnerCall> {
+ if (depth > 3) return;
+ const rec = record(input);
+ if (!rec) return;
+
+ const toolParams = record(rec.toolParams);
+ if (typeof toolParams?.name === 'string') {
+ yield { name: toolParams.name, args: record(toolParams.args) ?? toolParams };
+ if (dispatcherKind(toolParams.name)) {
+ yield* unwrapInnerCalls(toolParams.name, toolParams.args, depth + 1);
+ }
+ }
+
+ if (dispatcherKind(outerToolName) === 'call-tool' && typeof rec.name === 'string') {
+ yield { name: rec.name, args: record(rec.args) ?? rec };
+ if (dispatcherKind(rec.name)) {
+ yield* unwrapInnerCalls(rec.name, rec.args, depth + 1);
+ }
+ }
+
+ if (dispatcherKind(outerToolName) === 'ghost-call' && typeof rec.tool === 'string') {
+ yield { name: rec.tool, args: record(rec.args) ?? rec };
+ if (dispatcherKind(rec.tool)) {
+ yield* unwrapInnerCalls(rec.tool, rec.args, depth + 1);
+ }
+ }
+}
+
+/**
+ * Hard-deny check used immediately before a channel confirmation is shown.
+ * The outer wrapper name itself is not destructive, so the ordinary guard must
+ * also inspect the real action nested inside Pi/Claude/Codex dispatch wrappers.
+ * This intentionally returns only destructiveGuard results; semantic wrapper
+ * names such as `merge` remain confirmable rather than permanently denied.
+ */
+export function checkChannelDestructiveToolCall(
+ toolName: string,
+ input: unknown,
+): GuardResult {
+ const direct = checkDestructiveToolCall(toolName, record(input));
+ if (direct.destructive) return direct;
+ for (const inner of unwrapInnerCalls(toolName, input)) {
+ const nested = checkDestructiveToolCall(inner.name, inner.args);
+ if (nested.destructive) return nested;
+ }
+ return { destructive: false };
+}
+
+/**
+ * 渠道策略的强制确认判定:命中即要求用户逐次确认(无卡片渠道走文本确认)。
+ * true = 必须确认;false = 交回该渠道 agent 的常规审批链。
+ */
+export function channelForceConfirmToolCall(toolName: string, input: unknown): boolean {
+ // 1. 顶层工具名 / shell 命令(Bash/bash/PowerShell)直接命中破坏性规则。
+ if (checkChannelDestructiveToolCall(toolName, input).destructive) return true;
+
+ // 2. 包装 / 二级分派的内层动作。
+ for (const inner of unwrapInnerCalls(toolName, input)) {
+ if (
+ DESTRUCTIVE_INNER_NAME_RE.test(inner.name)
+ ) {
+ return true;
+ }
+ }
+
+ // 3. Codex 不透明写:fileChangeApproval 不带 patch 正文,permissions 升权可授权
+ // 不透明写入 —— 保守地强制确认,而不是自动放行一次可能的删除。
+ return toolName === 'file_change' || toolName === 'permissions';
+}
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index 77716d6a94..8692f957ed 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -104,7 +104,7 @@ import {
registerPendingExternal,
rejectAllPending,
} from './pendingInteractions';
-import { checkDestructiveToolCall } from '../../destructiveGuard';
+import { checkChannelDestructiveToolCall } from './channelToolPolicy';
import { readXdGatewayApiKey } from './apiKey';
import {
hasAuthForImRoute,
@@ -200,6 +200,14 @@ interface TurnState {
releaseHeadlessSetupTurn: (() => void) | null;
/** Active central interaction route; acquired at beforeProviderStart. */
interactionRouteLease: InteractionRouteLease | null;
+ /**
+ * Host turn lease held for the duration of a per-turn permission policy turn.
+ * While held, session.setPermissionMode() blocks any switch into a mode the
+ * agent lists as turnPermissionPolicy-unsupported (e.g. Pi Full Access),
+ * closing the hot-switch bypass window. Released on every terminal / requeue /
+ * cleanup path via releaseTurnInteractionRoute. Null when the turn has no policy.
+ */
+ hostTurnLeaseRelease: (() => void) | null;
/** Terminal classification consumed by chunked-text commitFinal. */
terminalKind: 'done' | 'aborted' | 'error';
terminalErrorCode: string | null;
@@ -663,6 +671,7 @@ export function createTurnRunner(
headlessSetupClosed: false,
releaseHeadlessSetupTurn: null,
interactionRouteLease: null,
+ hostTurnLeaseRelease: null,
terminalKind: 'done',
terminalErrorCode: null,
chunkedReplyBegun: false,
@@ -848,6 +857,13 @@ export function createTurnRunner(
planMode: false,
...(item.turnPermissionPolicy ? { turnPermissionPolicy: item.turnPermissionPolicy } : {}),
beforeProviderStart: async () => {
+ // 策略轮持一张 host turn lease:期间 setPermissionMode 切到 agent 声明为
+ // turnPermissionPolicy-unsupported 的档位(如 Pi Full Access)会被阻塞到本轮
+ // 终态,堵死"热切到 bypass 让 bridge 直接放行、策略连冒泡机会都没有"的绕过。
+ // 两个 surface 都需要:channel 与 desktop 的策略同样必须扛住热切。
+ if (item.turnPermissionPolicy) {
+ item.turn.hostTurnLeaseRelease = state.makerSession.acquireTurnLease();
+ }
item.turn.interactionRouteLease =
item.turnPermissionPolicy?.confirmationSurface === 'desktop'
? beginInteractionRoute(state.makerSession, {
@@ -872,11 +888,24 @@ export function createTurnRunner(
route: {
sessionId: rowId,
turnId: item.turn.turnId,
- origin: { kind: 'im', channel },
+ origin: item.turnPermissionPolicy?.origin ?? { kind: 'im', channel },
interactionSurface: 'channel-card',
+ ...(item.turnPermissionPolicy?.confirmationTimeoutMs
+ ? { timeoutMs: item.turnPermissionPolicy.confirmationTimeoutMs }
+ : {}),
+ ...(item.turnPermissionPolicy?.onInteractionStateChange
+ ? { onStateChange: item.turnPermissionPolicy.onInteractionStateChange }
+ : {}),
},
- handle: handleInteractionFor(rowId, userId, state.scopeKey),
- onCancel: (requestId) => cancelPending(requestId, 'interaction_route_released'),
+ handle: handleInteractionFor(
+ rowId,
+ userId,
+ state.scopeKey,
+ item.turnPermissionPolicy?.confirmationTimeoutMs,
+ ),
+ onCancel: (requestId, decision) =>
+ adapter.cancelTextInteraction?.(userId, requestId, decision) === true
+ || cancelPending(requestId, 'interaction_route_released'),
});
await item.beforeProviderStart?.();
acceptedAt = Date.now();
@@ -2026,6 +2055,11 @@ export function createTurnRunner(
const lease = turn.interactionRouteLease;
turn.interactionRouteLease = null;
lease?.release(reason);
+ // Release the host turn lease on the same terminal / requeue / cleanup paths
+ // so an unsupported permission-mode switch can proceed once the policy turn ends.
+ const releaseHostLease = turn.hostTurnLeaseRelease;
+ turn.hostTurnLeaseRelease = null;
+ releaseHostLease?.();
}
function settleTurnTerminal(turn: TurnState): void {
@@ -2526,7 +2560,12 @@ export function createTurnRunner(
// ── interaction handling ────────────────────────────────────────────────────
- function handleInteractionFor(localSessionId: string, userId: string, scopeKey?: string) {
+ function handleInteractionFor(
+ localSessionId: string,
+ userId: string,
+ scopeKey?: string,
+ confirmationTimeoutMs?: number,
+ ) {
return async (req: InteractionRequest): Promise<InteractionDecision> => {
log.info(
`interaction request kind=${req.kind} requestId=...${req.requestId.slice(-8)} session=...${localSessionId.slice(-8)}`,
@@ -2535,7 +2574,7 @@ export function createTurnRunner(
if (output.kind === 'chunked-text') {
if (adapter.handleTextInteraction) {
if (req.kind === 'permission') {
- const guard = checkDestructiveToolCall(req.toolName, req.input);
+ const guard = checkChannelDestructiveToolCall(req.toolName, req.input);
if (guard.destructive) {
log.warn(`destructive tool blocked: ${req.toolName} (${guard.reason})`);
return {
@@ -2545,7 +2584,9 @@ export function createTurnRunner(
};
}
}
- return adapter.handleTextInteraction(userId, req);
+ return adapter.handleTextInteraction(userId, req, {
+ ...(confirmationTimeoutMs ? { timeoutMs: confirmationTimeoutMs } : {}),
+ });
}
if (req.kind === 'ask_user_question') {
return { kind: 'ask_user_question', answers: {} };
@@ -2573,7 +2614,7 @@ export function createTurnRunner(
// Bash/PowerShell 命令含 rm/del/Remove-Item/find -delete/git clean -f 等。
// 模型收到 deny 后通常会改用 AskUserQuestion 跟用户沟通。
if (req.kind === 'permission') {
- const guard = checkDestructiveToolCall(req.toolName, req.input);
+ const guard = checkChannelDestructiveToolCall(req.toolName, req.input);
if (guard.destructive) {
log.warn(`destructive tool blocked: ${req.toolName} (${guard.reason})`);
return {
diff --git a/apps/desktop/src/main/im/shared/types.ts b/apps/desktop/src/main/im/shared/types.ts
index 6e19a60535..fbeb7e2ab7 100644
--- a/apps/desktop/src/main/im/shared/types.ts
+++ b/apps/desktop/src/main/im/shared/types.ts
@@ -140,7 +140,21 @@ export interface ImChannelAdapter {
* Text-only channels can still resolve agent interactions without rich cards.
* The callback owns channel-specific correlation and parsing.
*/
- handleTextInteraction?(userId: string, request: InteractionRequest): Promise<InteractionDecision>;
+ handleTextInteraction?(
+ userId: string,
+ request: InteractionRequest,
+ options?: { timeoutMs?: number },
+ ): Promise<InteractionDecision>;
+ /**
+ * Cancel a channel-owned text interaction when the central route times out,
+ * the turn stops, or the session closes. Return true when the adapter found
+ * and resolved the matching pending request itself.
+ */
+ cancelTextInteraction?(
+ userId: string,
+ requestId: string,
+ decision: InteractionDecision,
+ ): boolean;
/** Durable channels may promote task-scoped attachments after message persistence succeeds. */
onUserMessagePersisted?(args: {
sessionId: string;
diff --git a/apps/desktop/src/main/im/telegram/__tests__/permissionPolicy.test.ts b/apps/desktop/src/main/im/telegram/__tests__/permissionPolicy.test.ts
index 9170659403..f3d5c664f4 100644
--- a/apps/desktop/src/main/im/telegram/__tests__/permissionPolicy.test.ts
+++ b/apps/desktop/src/main/im/telegram/__tests__/permissionPolicy.test.ts
@@ -13,6 +13,7 @@ describe('telegram guest turn permission policy(一群一会话的成员轮次
});
expect(policy.confirmationSurface).toBe('channel');
expect(policy.forceConfirmToolCall('Bash', { command: 'rm -rf build' })).toBe(true);
+ expect(policy.forceConfirmToolCall('bash', { command: 'rm -rf build' })).toBe(true);
expect(
policy.forceConfirmToolCall('mcp__cindy_contacts__call_tool', {
name: 'contacts_delete',
@@ -24,6 +25,13 @@ describe('telegram guest turn permission policy(一群一会话的成员轮次
toolParams: { name: 'contacts_merge', args: { sourceId: 'a', targetId: 'b' } },
}),
).toBe(true);
+ expect(
+ policy.forceConfirmToolCall('mcp__cindy__ghost_call', {
+ ghost_id: 'files',
+ tool: 'delete_workspace',
+ args: { id: 'workspace-1' },
+ }),
+ ).toBe(true);
});
it('读/搜自动放行; Codex 不透明写(file_change/permissions)保守强确认', () => {
@@ -31,6 +39,8 @@ describe('telegram guest turn permission policy(一群一会话的成员轮次
expect(policy.forceConfirmToolCall('Read', { path: 'README.md' })).toBe(false);
expect(policy.forceConfirmToolCall('Grep', { pattern: 'foo' })).toBe(false);
+ expect(policy.forceConfirmToolCall('write', { path: 'notes.md', content: 'safe' })).toBe(false);
+ expect(policy.forceConfirmToolCall('edit', { path: 'notes.md', oldText: 'a', newText: 'b' })).toBe(false);
expect(
policy.forceConfirmToolCall('mcp:cindy_contacts', {
toolParams: { name: 'contacts_search', args: { query: 'Carol' } },
diff --git a/apps/desktop/src/main/im/telegram/permissionPolicy.ts b/apps/desktop/src/main/im/telegram/permissionPolicy.ts
index 83c9f765f8..98aa2a359c 100644
--- a/apps/desktop/src/main/im/telegram/permissionPolicy.ts
+++ b/apps/desktop/src/main/im/telegram/permissionPolicy.ts
@@ -1,11 +1,6 @@
import type { TurnPermissionPolicy } from '@cindy/maker-core';
-import { checkDestructiveToolCall } from '../../destructiveGuard';
-
-function record(value: unknown): Record<string, unknown> | null {
- if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
- return value as Record<string, unknown>;
-}
+import { channelForceConfirmToolCall } from '../shared/channelToolPolicy';
/**
* 群轮次的 per-turn 收紧(D1/D2, 2026-07-30 一群一会话版; review 修订后
@@ -14,8 +9,8 @@ function record(value: unknown): Record<string, unknown> | null {
* 不透明写(file_change / permissions 升权)强制弹确认卡, 而卡片点击只认
* owner — 即"谁都能问, 动手要主人拍板"。
*
- * 判定逻辑与个人微信的 createWechatTurnPermissionPolicy 同款(那边是无卡片
- * 渠道的文本确认版); 嵌套解包覆盖 Claude call_tool 包装与 Codex MCP elicitation。
+ * 判定逻辑与个人微信 / 钉钉共用 channelForceConfirmToolCall(嵌套解包覆盖
+ * Claude call_tool、Codex MCP elicitation 与 Pi 桥接 MCP / 二级分派插件)。
* 会话权限档为 acceptEdits/bypassPermissions 时 maker 会拒绝本策略(fail-closed):
* guest 轮次直接报错不跑, 不会放开。
*/
@@ -24,28 +19,6 @@ export function createTelegramGuestTurnPermissionPolicy(taskId: string): TurnPer
origin: { kind: 'im', channel: 'telegram', taskId },
confirmationSurface: 'channel',
confirmationTimeoutMs: 30 * 60 * 1_000,
- forceConfirmToolCall(toolName, input) {
- const direct = checkDestructiveToolCall(toolName, record(input));
- if (direct.destructive) return true;
-
- const outer = record(input);
- const nested = record(outer?.toolParams);
- const innerName =
- typeof nested?.name === 'string'
- ? nested.name
- : typeof outer?.name === 'string'
- ? outer.name
- : null;
- const innerInput = nested ?? outer;
- if (
- innerName &&
- (checkDestructiveToolCall(innerName, innerInput).destructive ||
- /(?:^|_)(?:merge|system_write|overwrite)(?:_|$)/i.test(innerName))
- ) {
- return true;
- }
-
- return toolName === 'file_change' || toolName === 'permissions';
- },
+ forceConfirmToolCall: channelForceConfirmToolCall,
};
}
diff --git a/apps/desktop/src/main/im/wechat/WechatIM.ts b/apps/desktop/src/main/im/wechat/WechatIM.ts
index f254b2199b..5565e8088c 100644
--- a/apps/desktop/src/main/im/wechat/WechatIM.ts
+++ b/apps/desktop/src/main/im/wechat/WechatIM.ts
@@ -31,6 +31,7 @@ import type { ImFinalOutput } from '@cindy/im';
import type { ImTurnRunner } from '../shared/turnRunner';
import {
createWechatTurnPermissionPolicyForMode,
+ WECHAT_INTERACTION_CONFIRM_TIMEOUT_MS,
WECHAT_TURN_PERMISSION_POLICY_UNSUPPORTED,
} from './permissionPolicy';
import {
@@ -478,6 +479,7 @@ export class WechatIM extends BaseIM implements RichChannelIM {
async handleTextInteraction(
userId: string,
request: InteractionRequest,
+ options?: { timeoutMs?: number },
): Promise<InteractionDecision> {
const previous = this.#pendingInteractions.get(userId);
if (previous) {
@@ -492,7 +494,7 @@ export class WechatIM extends BaseIM implements RichChannelIM {
const timer = setTimeout(() => {
this.#pendingInteractions.delete(userId);
resolvePending(defaultWechatInteractionDecision(request, 'wechat_interaction_timeout'));
- }, 10 * 60_000);
+ }, options?.timeoutMs ?? WECHAT_INTERACTION_CONFIRM_TIMEOUT_MS);
timer.unref?.();
this.#pendingInteractions.set(userId, { request, resolve: resolvePending, timer });
try {
@@ -511,6 +513,24 @@ export class WechatIM extends BaseIM implements RichChannelIM {
return result;
}
+ /**
+ * Resolve only the exact pending request owned by the central interaction
+ * route. Request-id matching prevents a late timeout/release from cancelling
+ * a newer one-shot confirmation for the same WeChat peer.
+ */
+ cancelTextInteraction(
+ userId: string,
+ requestId: string,
+ decision: InteractionDecision,
+ ): boolean {
+ const pending = this.#pendingInteractions.get(userId);
+ if (!pending || pending.request.requestId !== requestId) return false;
+ clearTimeout(pending.timer);
+ this.#pendingInteractions.delete(userId);
+ pending.resolve(decision);
+ return true;
+ }
+
sendMarkdownText(userId: string, markdown: string): Promise<{ messageId: string }> {
return this.sendText(userId, filterWechatMarkdown(markdown));
}
diff --git a/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts b/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts
index e6c36b9aea..f778a34746 100644
--- a/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts
+++ b/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts
@@ -156,6 +156,35 @@ describe('WechatIM host boundary', () => {
});
});
+ it('cancels only the matching one-shot interaction when its central route closes', async () => {
+ const im = new WechatIM(deps());
+ vi.spyOn(im, 'sendText').mockResolvedValue({ messageId: 'interaction-prompt' });
+ const request = {
+ kind: 'permission' as const,
+ requestId: 'request-current',
+ toolName: 'bash',
+ input: { command: 'pnpm test' },
+ };
+ const pending = im.handleTextInteraction('peer-1', request, { timeoutMs: 60_000 });
+ await Promise.resolve();
+
+ expect(im.cancelTextInteraction('peer-1', 'request-stale', {
+ kind: 'permission',
+ behavior: 'deny',
+ reason: 'stale_route',
+ })).toBe(false);
+ expect(im.cancelTextInteraction('peer-1', 'request-current', {
+ kind: 'permission',
+ behavior: 'deny',
+ reason: 'interaction_route_released',
+ })).toBe(true);
+ await expect(pending).resolves.toEqual({
+ kind: 'permission',
+ behavior: 'deny',
+ reason: 'interaction_route_released',
+ });
+ });
+
it('fails closed before authorization when the signed compatibility policy disables it', async () => {
const createTransport = vi.fn();
const im = new WechatIM(
diff --git a/apps/desktop/src/main/im/wechat/__tests__/permissionPolicy.test.ts b/apps/desktop/src/main/im/wechat/__tests__/permissionPolicy.test.ts
index 80b98d3729..dc17b321ec 100644
--- a/apps/desktop/src/main/im/wechat/__tests__/permissionPolicy.test.ts
+++ b/apps/desktop/src/main/im/wechat/__tests__/permissionPolicy.test.ts
@@ -19,6 +19,9 @@ describe('personal WeChat turn permission policy', () => {
expect(
policy.forceConfirmToolCall('Bash', { command: 'rm -rf build' }),
).toBe(true);
+ expect(
+ policy.forceConfirmToolCall('bash', { command: 'rm -rf build' }),
+ ).toBe(true);
expect(
policy.forceConfirmToolCall('mcp__cindy_contacts__call_tool', {
name: 'contacts_delete',
@@ -33,12 +36,24 @@ describe('personal WeChat turn permission policy', () => {
},
}),
).toBe(true);
+ expect(
+ policy.forceConfirmToolCall('mcp__cindy__ghost_call', {
+ ghost_id: 'files',
+ tool: 'call_tool',
+ args: {
+ name: 'bash',
+ args: { command: 'rm -rf generated' },
+ },
+ }),
+ ).toBe(true);
});
it('keeps read-only calls automatic but treats opaque Codex writes conservatively', () => {
const policy = createWechatTurnPermissionPolicy('task-2');
expect(policy.forceConfirmToolCall('Read', { path: 'README.md' })).toBe(false);
+ expect(policy.forceConfirmToolCall('write', { path: 'notes.md', content: 'safe' })).toBe(false);
+ expect(policy.forceConfirmToolCall('edit', { path: 'notes.md', oldText: 'a', newText: 'b' })).toBe(false);
expect(
policy.forceConfirmToolCall('mcp:cindy_contacts', {
toolParams: { name: 'contacts_search', args: { query: 'Carol' } },
diff --git a/apps/desktop/src/main/im/wechat/adapter.ts b/apps/desktop/src/main/im/wechat/adapter.ts
index 5d66e1776e..ca35e5200d 100644
--- a/apps/desktop/src/main/im/wechat/adapter.ts
+++ b/apps/desktop/src/main/im/wechat/adapter.ts
@@ -35,8 +35,10 @@ export function buildWechatAdapter(
},
processingEmoji: '',
buildVendorOptions: (userId) => ({ source: 'wechat', wechatPeerId: userId }),
- handleTextInteraction: (userId, request) =>
- wechatIm.handleTextInteraction(userId, request),
+ handleTextInteraction: (userId, request, options) =>
+ wechatIm.handleTextInteraction(userId, request, options),
+ cancelTextInteraction: (userId, requestId, decision) =>
+ wechatIm.cancelTextInteraction(userId, requestId, decision),
onUserMessagePersisted: (args) => wechatIm.onUserMessagePersisted(args),
};
}
diff --git a/apps/desktop/src/main/im/wechat/permissionPolicy.ts b/apps/desktop/src/main/im/wechat/permissionPolicy.ts
index 608f2c786f..f8eb42f725 100644
--- a/apps/desktop/src/main/im/wechat/permissionPolicy.ts
+++ b/apps/desktop/src/main/im/wechat/permissionPolicy.ts
@@ -4,20 +4,27 @@ import type {
TurnPermissionPolicy,
} from '@cindy/maker-core';
-import { checkDestructiveToolCall } from '../../destructiveGuard';
+import { channelForceConfirmToolCall } from '../shared/channelToolPolicy';
export const WECHAT_TURN_PERMISSION_POLICY_UNSUPPORTED =
'TURN_PERMISSION_POLICY_UNSUPPORTED';
-function record(value: unknown): Record<string, unknown> | null {
- if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
- return value as Record<string, unknown>;
-}
+/**
+ * Single source of truth for the personal-WeChat one-shot confirmation deadline.
+ * The policy advertises it as confirmationTimeoutMs AND WechatIM enforces the
+ * actual auto-deny timer from the same constant, so the declared contract and
+ * the enforced timeout can never drift (design §7.9). WeChat confirmation is a
+ * text reply from a remote human; 30 minutes matches the state machine copy.
+ */
+export const WECHAT_INTERACTION_CONFIRM_TIMEOUT_MS = 30 * 60 * 1_000;
/**
* Personal WeChat has no structured card UI. Interaction requests are rendered
* as one-shot text prompts by the channel adapter; the destructive guard still
- * blocks unsafe calls before a prompt can be approved.
+ * blocks unsafe calls before a prompt can be approved. Detection is shared with
+ * Telegram / DingTalk via channelForceConfirmToolCall (nested unwrap covers
+ * Claude call_tool, Codex MCP elicitation, and Pi bridged MCP / secondary
+ * dispatch plugins).
*/
export function createWechatTurnPermissionPolicy(
taskId: string,
@@ -28,38 +35,11 @@ export function createWechatTurnPermissionPolicy(
return {
origin: { kind: 'im', channel: 'wechat', taskId },
confirmationSurface: 'channel',
- confirmationTimeoutMs: 30 * 60 * 1_000,
+ confirmationTimeoutMs: WECHAT_INTERACTION_CONFIRM_TIMEOUT_MS,
...(options?.onInteractionStateChange
? { onInteractionStateChange: options.onInteractionStateChange }
: {}),
- forceConfirmToolCall(toolName, input) {
- const direct = checkDestructiveToolCall(toolName, record(input));
- if (direct.destructive) return true;
-
- // Claude call_tool wrappers put the inner action directly in input.name.
- // Codex MCP elicitation wraps it in input.toolParams.name.
- const outer = record(input);
- const nested = record(outer?.toolParams);
- const innerName =
- typeof nested?.name === 'string'
- ? nested.name
- : typeof outer?.name === 'string'
- ? outer.name
- : null;
- const innerInput = nested ?? outer;
- if (
- innerName &&
- (checkDestructiveToolCall(innerName, innerInput).destructive ||
- /(?:^|_)(?:merge|system_write|overwrite)(?:_|$)/i.test(innerName))
- ) {
- return true;
- }
-
- // Codex does not expose the patch body in fileChangeApproval, and a
- // permissions escalation can authorize an opaque write. Confirm these
- // conservatively rather than auto-approving a possible deletion.
- return toolName === 'file_change' || toolName === 'permissions';
- },
+ forceConfirmToolCall: channelForceConfirmToolCall,
};
}