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(remote-agent): 收口 review 指出的其余安全与恢复缺口

MagicLizie6f79c2e0fd1
diff --git a/apps/desktop/src/main/remote-agent/__tests__/hostLifecycle.test.ts b/apps/desktop/src/main/remote-agent/__tests__/hostLifecycle.test.ts
new file mode 100644
index 0000000000..799f612427
--- /dev/null
+++ b/apps/desktop/src/main/remote-agent/__tests__/hostLifecycle.test.ts
@@ -0,0 +1,183 @@
+/**
+ * 被控端任务生命周期收尾:
+ * - 影子工作目录(同步过去的项目与个人说明副本)在任务收尾后删除,替换实例还在用时保留;
+ * - 去重 / 丢弃路径上的上传载荷显式取走,不留着占暂存配额到过期。
+ */
+import { createHash } from 'node:crypto';
+import { gzipSync } from 'node:zlib';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import type { AgentEvent, AgentSessionHandle } from '@cindy/maker-core';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createRemoteAgentHost, hostSessionIdFor, type HostedStartInput } from '../host/runHost';
+
+/** 协议层 id 是 36 位 UUID 形态。 */
+const RUN_1 = '11111111-1111-4111-8111-111111111111';
+const RUN_2 = '22222222-2222-4222-8222-222222222222';
+const UPLOAD_1 = 'aaaa1111-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+const UPLOAD_2 = 'bbbb2222-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+
+let root: string;
+let runsRoot: string;
+let clock = 0;
+
+function idleHandle(input: HostedStartInput): AgentSessionHandle {
+ return {
+ id: `sdk-${input.hostSessionId}`,
+ agentKind: input.kind,
+ model: input.options.model,
+ async send() {},
+ async steer() {},
+ async abort() {},
+ async close() {},
+ events: () => ({
+ async *[Symbol.asyncIterator](): AsyncIterator<AgentEvent> {
+ // 不产生事件。
+ },
+ }),
+ getUsageSnapshot: () => ({ tokenUsage: 0, contextTokens: 0, contextWindow: 0, costUsd: 0 }),
+ setInteractionResolver() {},
+ };
+}
+
+function makeHost(started: Array<() => void>) {
+ return createRemoteAgentHost({
+ isAgentAvailable: () => true,
+ startHosted: async (input) => {
+ started.shift()?.();
+ return idleHandle(input);
+ },
+ isControllerAuthorized: () => true,
+ captureOwner: () => 'owner',
+ isOwnerCurrent: () => true,
+ runsRoot,
+ now: () => clock,
+ });
+}
+
+function openPayload(sessionId: string, projectFiles: Array<{ path: string; data: string }> = []) {
+ return {
+ sessionId,
+ options: { model: 'claude-opus' },
+ workspace: { workingDir: '/Users/me/proj', platform: 'darwin', shell: 'bash' },
+ projectFiles,
+ ancestorFiles: [],
+ personal: { files: [] },
+ mcpServers: [],
+ };
+}
+
+/** 把载荷 gzip 后经 upload op 暂存,返回引用(uploadId 分段上传的形态)。 */
+async function stageUpload(
+ host: ReturnType<typeof createRemoteAgentHost>,
+ uploadId: string,
+ value: unknown,
+): Promise<{ uploadId: string; chunks: number; bytes: number }> {
+ const gz = gzipSync(Buffer.from(JSON.stringify(value ?? null), 'utf8'));
+ await host.handle('controller-1', {
+ op: 'upload',
+ uploadId,
+ index: 0,
+ data: gz.toString('base64'),
+ });
+ return { uploadId, chunks: 1, bytes: gz.length };
+}
+
+function whenStarted(): { promise: Promise<void>; resolve: () => void } {
+ let resolve!: () => void;
+ const promise = new Promise<void>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
+async function settle(): Promise<void> {
+ for (let i = 0; i < 100; i += 1) {
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+}
+
+beforeEach(() => {
+ root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-ra-host-')));
+ runsRoot = path.join(root, 'host');
+ clock = 1_000;
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ fs.rmSync(root, { recursive: true, force: true });
+});
+
+function sessionRoot(controller: string, sessionId: string): string {
+ const controllerDir = createHash('sha256').update(controller).digest('hex').slice(0, 16);
+ return path.join(runsRoot, 'workspaces', controllerDir, hostSessionIdFor(controller, sessionId));
+}
+
+describe('hosted shadow workspace cleanup', () => {
+ it('removes the shadow workspace once the run is disposed', async () => {
+ const starts: Array<() => void> = [];
+ const first = whenStarted();
+ starts.push(first.resolve);
+ const host = makeHost(starts);
+ await host.handle('controller-1', { op: 'open', runId: RUN_1, agentKind: 'claude-code', payload: await stageUpload(host, UPLOAD_1, openPayload('task-1')) });
+ await first.promise;
+ expect(fs.existsSync(sessionRoot('controller-1', 'task-1'))).toBe(true);
+
+ host.dispose();
+ await settle();
+ expect(fs.existsSync(sessionRoot('controller-1', 'task-1'))).toBe(false);
+ });
+
+ it('keeps the workspace of a replacement run and removes it when that run ends', async () => {
+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
+ const starts: Array<() => void> = [];
+ const first = whenStarted();
+ const second = whenStarted();
+ starts.push(first.resolve, second.resolve);
+ const host = makeHost(starts);
+ await host.handle('controller-1', { op: 'open', runId: RUN_1, agentKind: 'claude-code', payload: await stageUpload(host, UPLOAD_1, openPayload('task-1', [{ path: 'CLAUDE.md', data: Buffer.from('v1').toString('base64') }])) });
+ await first.promise;
+ // 同一任务重新打开:旧实例让位给新实例,目录按新内容重建。
+ await host.handle('controller-1', { op: 'open', runId: RUN_2, agentKind: 'claude-code', payload: await stageUpload(host, UPLOAD_2, openPayload('task-1', [{ path: 'CLAUDE.md', data: Buffer.from('v2').toString('base64') }])) });
+ await second.promise;
+ const sessionRootPath = sessionRoot('controller-1', 'task-1');
+ expect(fs.readFileSync(path.join(sessionRootPath, 'fs', 'Users', 'me', 'proj', 'CLAUDE.md'), 'utf8')).toBe('v2');
+
+ // 旧实例收尾保留期到点后被清理:替换实例还在用,目录必须保留。
+ clock += 61_000;
+ await vi.advanceTimersByTimeAsync(5_000);
+ await settle();
+ expect(fs.existsSync(sessionRootPath)).toBe(true);
+ expect(fs.readFileSync(path.join(sessionRootPath, 'fs', 'Users', 'me', 'proj', 'CLAUDE.md'), 'utf8')).toBe('v2');
+
+ // 替换实例也结束后,目录随之删除。
+ await host.handle('controller-1', { op: 'close', runId: RUN_2, mode: 'close', reason: 'navigation' });
+ clock += 61_000;
+ await vi.advanceTimersByTimeAsync(5_000);
+ await settle();
+ expect(fs.existsSync(sessionRootPath)).toBe(false);
+ host.dispose();
+ });
+});
+
+describe('duplicate op payloads', () => {
+ it('discards the staged upload of a duplicate open instead of leaving it until expiry', async () => {
+ const starts: Array<() => void> = [];
+ const first = whenStarted();
+ starts.push(first.resolve);
+ const host = makeHost(starts);
+ const payload = openPayload('task-1');
+ await host.handle('controller-1', { op: 'open', runId: RUN_1, agentKind: 'claude-code', payload: await stageUpload(host, UPLOAD_1, payload) });
+ await first.promise;
+
+ // 同一 runId 重发 open(歧义交付后的重试):按 id 去重,但载荷要取走。
+ const ref2 = await stageUpload(host, UPLOAD_2, payload);
+ await host.handle('controller-1', { op: 'open', runId: RUN_1, agentKind: 'claude-code', payload: ref2 });
+ await expect(host.handle('controller-1', { op: 'open', runId: RUN_2, agentKind: 'claude-code', payload: ref2 }))
+ .rejects.toThrow(/upload is missing or expired/);
+ host.dispose();
+ });
+});
diff --git a/apps/desktop/src/main/remote-agent/__tests__/runClientReply.test.ts b/apps/desktop/src/main/remote-agent/__tests__/runClientReply.test.ts
index b8dd0707f3..d8a8db15c7 100644
--- a/apps/desktop/src/main/remote-agent/__tests__/runClientReply.test.ts
+++ b/apps/desktop/src/main/remote-agent/__tests__/runClientReply.test.ts
@@ -54,4 +54,51 @@ describe('RemoteAgentRunClient reply delivery', () => {
// 重试复用同一份载荷(同一引用):重建载荷会在对方 staging 里多留一份无人消费的上传。
expect(new Set(replyPayloads).size).toBe(1);
});
+
+ it('reuses one uploaded payload when retrying a large reply', async () => {
+ const uploadIds = new Set<string>();
+ const replyUploadIds: Array<string | undefined> = [];
+ let failuresLeft = 1;
+ const invoke = async (args: unknown[]): Promise<unknown> => {
+ const op = args[0] as { op: string; uploadId?: string; payload?: { uploadId?: string } };
+ if (op.op === 'upload' && op.uploadId) uploadIds.add(op.uploadId);
+ if (op.op === 'reply') {
+ replyUploadIds.push(op.payload?.uploadId);
+ if (failuresLeft > 0) {
+ failuresLeft -= 1;
+ throw new Error('TIMEOUT: link dropped mid-reply');
+ }
+ }
+ return {};
+ };
+ let seq = 0;
+ const client = new RemoteAgentRunClient(
+ 'run-1',
+ { invoke, unregister: () => undefined } as unknown as RemoteAgentPoller,
+ {
+ onEvent: () => undefined,
+ onState: () => undefined,
+ onWs: () => undefined,
+ onClosed: () => undefined,
+ // 大回包(超过内联上限)走分段上传。
+ onRequest: async () => ({ type: 'callback', value: 'x'.repeat(2 * 1024 * 1024) }),
+ },
+ () => `generated-${(seq += 1)}`,
+ );
+ client.onData(Buffer.from(`${JSON.stringify({
+ t: 'request',
+ requestId: '11111111-2222-4333-8444-555555555555',
+ request: { type: 'callback', name: 'onTranscriptUserEntry', args: ['call-1', 'entry-1'] },
+ })}\n`), false);
+ const deadline = Date.now() + 10_000;
+ while (replyUploadIds.length < 2 && Date.now() < deadline) {
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ // 重试复用同一份上传载荷(同一个 uploadId):每次都造新 upload 会把载荷留在对方
+ // 暂存区直到过期,反复歧义交付会占满配额、挡住无关上传。
+ expect(replyUploadIds).toHaveLength(2);
+ expect(new Set(replyUploadIds).size).toBe(1);
+ expect(replyUploadIds[0]).toBeDefined();
+ expect(uploadIds.size).toBe(1);
+ });
});
diff --git a/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts b/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts
index f2d80c0596..8490ff053e 100644
--- a/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts
+++ b/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts
@@ -233,8 +233,19 @@ export class ExecServerRelay {
try {
await this.deps.push(batch);
} catch (error) {
- this.deps.log?.warn('remote agent: exec-server frames could not be delivered', { error: String(error) });
+ // 批次已从 outbox 取出但交付失败(push 同序号重试耗尽):不能只记日志就继续发后续帧
+ // ——远端 Codex 会永久缺这条 JSON-RPC 回复卡住,丢失的中间分片还会把后续分片拼成
+ // 损坏消息。丢弃未发帧并关掉全部 exec-server 连接,让对方按连接断开明确恢复。
+ this.deps.log?.warn('remote agent: exec-server frames could not be delivered; closing connections', { error: String(error) });
+ this.dropAll();
+ return;
}
}
}
+
+ /** 交付链路断了:丢掉未发帧,关掉全部连接触发对方的明确恢复。 */
+ private dropAll(): void {
+ this.outbox = [];
+ for (const connId of [...this.connections.keys()]) this.dropConnection(connId, true);
+ }
}
diff --git a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts b/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts
index aa1878a20d..1d43f3ed6e 100644
--- a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts
+++ b/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts
@@ -175,6 +175,8 @@ export interface RemoteHandleDeps {
onPermissionMode?: (mode: string) => void;
onPlanMode?: (enabled: boolean) => void;
onExtraDirs?: (dirs: string[]) => void;
+ /** 可写目录变化时同步给执行器(在对方确认成功后调用,保持两边一致)。 */
+ onWritableDirs?: (dirs: string[]) => void;
/** 本机 MCP 身份引用的 vendorOptions 同步更新。 */
onVendorOptions?: (patch: Record<string, unknown>) => void;
/** 句柄关闭后释放本机资源(执行器、MCP 身份等)。 */
@@ -325,6 +327,9 @@ export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHand
}),
...optional('setWritableDirs', async (dirs: string[]) => {
await call('setWritableDirs', dirs);
+ // 对方成功后才更新本机执行器的根目录:新建的可写目录在本机也能过 root 判定,
+ // 撤掉的不再被本机上限当可信根;失败时两边都保持原状。
+ deps.onWritableDirs?.(dirs);
}),
// 本机 MCP 身份(协同等工具)必须立即看到改动;对方不支持时也照样更新本机这一份。
setVendorOptions: async (patch: Record<string, unknown>) => {
diff --git a/apps/desktop/src/main/remote-agent/controller/runClient.ts b/apps/desktop/src/main/remote-agent/controller/runClient.ts
index 330c27e204..3f26146954 100644
--- a/apps/desktop/src/main/remote-agent/controller/runClient.ts
+++ b/apps/desktop/src/main/remote-agent/controller/runClient.ts
@@ -5,8 +5,9 @@
* 调用方(Agent 事件、状态镜像、方法结果、反向请求、WebSocket 帧);反向请求处理完用 reply 回包。
* 大载荷先分段上传再引用。
*
- * 链路抖动由拉取器处理(poll 按游标幂等);其余 op 不自动重放(open / call / reply / push 在对方
- * 按 id 去重,结果不明时由调用方决定)。对方长时间不可达时拉取器结束任务并报告原因。
+ * 链路抖动由拉取器处理(poll 按游标幂等);reply / push 链路失败时按同一 id / 序号重试(对方按
+ * id 去重,歧义交付不会重复投递);open / call 不自动重放,结果不明时由调用方决定。对方长时间
+ * 不可达时拉取器结束任务并报告原因。
*/
import { promisify } from 'node:util';
import { gzip } from 'node:zlib';
@@ -43,6 +44,8 @@ const MAX_LINE_BYTES = 64 * 1024 * 1024;
const CLOSE_DRAIN_MS = 5_000;
/** 回包交付重试上限(链路抖动时对方一直在等同一 requestId 的回包)。 */
const MAX_REPLY_DELIVER_ATTEMPTS = 30;
+/** push 帧批次交付重试上限(对方按 seq 去重,同序号重试不会重复投递)。 */
+const MAX_PUSH_DELIVER_ATTEMPTS = 30;
export class RemoteAgentRemoteError extends Error {
constructor(readonly info: RemoteAgentErrorInfo) {
@@ -94,12 +97,11 @@ export class RemoteAgentRunClient implements PolledRun {
}
/** 把一个 JSON 值做成载荷:小的内联,大的 gzip 后分段上传。 */
- async payload(value: unknown): Promise<RemoteAgentPayload> {
+ async payload(value: unknown, uploadId = this.newId()): Promise<RemoteAgentPayload> {
const text = JSON.stringify(value ?? null);
if (text.length <= REMOTE_AGENT_MAX_INLINE_PAYLOAD_CHARS) return { json: JSON.parse(text) as unknown };
const gz = await gzipAsync(Buffer.from(text, 'utf8'));
if (gz.length > REMOTE_AGENT_MAX_PAYLOAD_BYTES) throw new Error('The request is too large to send to the other computer.');
- const uploadId = this.newId();
const chunks = Math.max(1, Math.ceil(gz.length / REMOTE_AGENT_UPLOAD_CHUNK_BYTES));
for (let index = 0; index < chunks; index += 1) {
const data = gz.subarray(index * REMOTE_AGENT_UPLOAD_CHUNK_BYTES, (index + 1) * REMOTE_AGENT_UPLOAD_CHUNK_BYTES);
@@ -146,10 +148,33 @@ export class RemoteAgentRunClient implements PolledRun {
return result;
}
+ /**
+ * 推帧:对方按 seq 去重,所以链路抖动时用同一个 seq 重试——歧义交付(对方已收到但回包
+ * 丢失)重发不会重复投递,帧序列也不会缺批。重试耗尽才抛给调用方决定后续处置。
+ */
async push(frames: RemoteAgentPushFrame[]): Promise<void> {
if (this.closed || frames.length === 0) return;
this.pushSeq += 1;
- await this.invoke([{ op: 'push', runId: this.runId, seq: this.pushSeq, frames }]);
+ const seq = this.pushSeq;
+ let delay = 500;
+ for (let attempt = 1; ; attempt += 1) {
+ if (this.closed) return;
+ try {
+ await this.invoke([{ op: 'push', runId: this.runId, seq, frames }]);
+ return;
+ } catch (error) {
+ const retryable = isRetryableLinkError(error) && attempt < MAX_PUSH_DELIVER_ATTEMPTS;
+ this.log?.warn(retryable ? 'remote agent: push failed; retrying' : 'remote agent: push failed', {
+ runId: this.runId,
+ seq,
+ attempt,
+ error: String(error),
+ });
+ if (!retryable) throw error;
+ await sleep(delay);
+ delay = Math.min(delay * 2, 5_000);
+ }
+ }
}
async close(mode: 'close' | 'detach', reason: RemoteAgentTeardownReason): Promise<void> {
@@ -278,17 +303,19 @@ export class RemoteAgentRunClient implements PolledRun {
* 的等待,只记日志不重试会让任务一直停在权限确认 / 工具请求上;对方按 id 去重,
* 重复交付无副作用。任务结束或非链路类错误(载荷过大等)才放弃。
*
- * 载荷只建一次、重试复用:重试重建会再走一遍上传,而对方对重复 reply 在 pending
- * 查询处就返回、不会消费新上传,白白占住对方的 staging 缓冲;若首份上传已被消费、
- * 只是响应丢了,复用同一载荷还能直接命中幂等返回。
+ * 载荷只建一次、重试复用,且复用同一个 uploadId(分段上传按 (uploadId, index) 幂等):
+ * 重试重建会再走一遍上传,而对方对重复 reply 在 pending 查询处就返回、不会消费新上传,
+ * 白白占住对方的 staging 缓冲;若首份上传已被消费、只是响应丢了,复用同一载荷还能直接
+ * 命中幂等返回。上传中途失败后同一 uploadId 重传,也不会多留半份暂存载荷。
*/
private async deliverReply(requestId: string, reply: RemoteAgentReply): Promise<void> {
- let delay = 500;
+ const uploadId = this.newId();
let payload: RemoteAgentPayload | undefined;
+ let delay = 500;
for (let attempt = 1; ; attempt += 1) {
if (this.closed) return;
try {
- if (!payload) payload = await this.payload(reply);
+ payload ??= await this.payload(reply, uploadId);
await this.invoke([{ op: 'reply', runId: this.runId, requestId, payload }]);
return;
} catch (error) {
diff --git a/apps/desktop/src/main/remote-agent/controller/startRemote.ts b/apps/desktop/src/main/remote-agent/controller/startRemote.ts
index 19d51d3c31..6f6f04c808 100644
--- a/apps/desktop/src/main/remote-agent/controller/startRemote.ts
+++ b/apps/desktop/src/main/remote-agent/controller/startRemote.ts
@@ -124,8 +124,12 @@ export async function startRemoteAgentSession(
deps: StartRemoteAgentDeps,
): Promise<AgentSessionHandle> {
if (!opts.sessionId) throw new Error('remote agent sessions require a session id');
- const extraDirs = [...new Set([...(opts.extraDirs ?? []), ...(opts.writableDirs ?? [])])];
- const workspace = new ExecutorWorkspace({ workingDir: opts.workingDir, extraDirs });
+ // 附加目录(只读引用)与可写目录分开跟踪,运行中任一侧变化都重算执行器根目录:
+ // 否则新授予的目录过不了本机 shell/root 判定,撤掉的还被本机上限当可信根。
+ let extraDirs = [...new Set(opts.extraDirs ?? [])];
+ let writableDirs = [...new Set(opts.writableDirs ?? [])];
+ const workspace = new ExecutorWorkspace({ workingDir: opts.workingDir, extraDirs: [...extraDirs, ...writableDirs] });
+ const applyDirs = () => workspace.setExtraDirs([...new Set([...extraDirs, ...writableDirs])]);
const gate = new ExecutorGate(workspace, executorGateModeFor(opts.permissionMode, opts.planMode === true));
const executor = new RemoteExecutor({
workspace,
@@ -196,7 +200,7 @@ export async function startRemoteAgentSession(
},
onWs: (item: Extract<RemoteAgentStreamItem, { t: 'ws' }>) => {
if (relay) relay.handle(item);
- else if (item.kind === 'open') void pushFrames?.([{ connId: item.connId, kind: 'close' }]);
+ else if (item.kind === 'open') void pushFrames?.([{ connId: item.connId, kind: 'close' }])?.catch(() => undefined);
},
onClosed: (reason, error) => {
if (controller) controller.onClosed(reason, error?.message);
@@ -259,7 +263,14 @@ export async function startRemoteAgentSession(
planMode = enabled;
executor.setGateMode(executorGateModeFor(permissionMode, planMode));
},
- onExtraDirs: (dirs) => workspace.setExtraDirs([...new Set([...dirs, ...(opts.writableDirs ?? [])])]),
+ onExtraDirs: (dirs) => {
+ extraDirs = [...new Set(dirs)];
+ applyDirs();
+ },
+ onWritableDirs: (dirs) => {
+ writableDirs = [...new Set(dirs)];
+ applyDirs();
+ },
onVendorOptions: (patch) => {
Object.assign(vendorOptions, patch);
},
diff --git a/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts b/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts
index 750de17aa3..0969122d19 100644
--- a/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts
+++ b/apps/desktop/src/main/remote-agent/executor/__tests__/executor.test.ts
@@ -111,6 +111,28 @@ describe('permission ceiling', () => {
expect(gate.authorize({ kind: 'exec', command: risky, cwd: project }).ok).toBe(false);
});
+ it('holds writes and recursive reads outside the workspace until confirmed on this computer', () => {
+ const workspace = new ExecutorWorkspace({ workingDir: project });
+ const gate = new ExecutorGate(workspace, 'normal');
+ const outsideFile = path.join(outside, 'x.txt');
+ // 反向请求不能只信发起方(同账号电脑也可能被攻破)的权限逻辑:区外写在本机任务里也是
+ // 必问项(auto-review 对区外写返回 prompt),这里只认本机用户刚批准过的同一操作。
+ expect(gate.authorize({ kind: 'write', path: outsideFile }).ok).toBe(false);
+ gate.recordApproval({ kind: 'write', path: outsideFile });
+ expect(gate.authorize({ kind: 'write', path: outsideFile }).ok).toBe(true);
+ // 可写根内的写不受影响。
+ expect(gate.authorize({ kind: 'write', path: path.join(project, 'a.ts') }).ok).toBe(true);
+ // 单文件区外读按本机语义放行;递归读(搜索 / 列举)根在区外能遍历到区外凭证子路径,要批准。
+ expect(gate.authorize({ kind: 'read', path: outsideFile }).ok).toBe(true);
+ expect(gate.authorize({ kind: 'read', path: outside, scope: 'tree' }).ok).toBe(false);
+ gate.recordApproval({ kind: 'read', path: outside });
+ expect(gate.authorize({ kind: 'read', path: outside, scope: 'tree' }).ok).toBe(true);
+ // 全权(用户在本机为这个任务选了全权)不受此限。
+ const full = new ExecutorGate(workspace, executorGateModeFor('bypassPermissions'));
+ expect(full.authorize({ kind: 'write', path: outsideFile }).ok).toBe(true);
+ expect(full.authorize({ kind: 'read', path: outside, scope: 'tree' }).ok).toBe(true);
+ });
+
it('keeps plan mode read-only and full access unrestricted', () => {
const workspace = new ExecutorWorkspace({ workingDir: project });
const plan = new ExecutorGate(workspace, executorGateModeFor('default', true));
diff --git a/apps/desktop/src/main/remote-agent/executor/executor.ts b/apps/desktop/src/main/remote-agent/executor/executor.ts
index 5bc9fed36c..da38853590 100644
--- a/apps/desktop/src/main/remote-agent/executor/executor.ts
+++ b/apps/desktop/src/main/remote-agent/executor/executor.ts
@@ -206,7 +206,7 @@ export class RemoteExecutor {
}
case 'fs.glob': {
const cwd = this.resolvePath(str(body, 'cwd'));
- this.authorize({ kind: 'read', path: cwd });
+ this.authorize({ kind: 'read', path: cwd, scope: 'tree' });
const limit = Math.max(1, Math.floor(optionalNumber(body, 'limit') ?? 1000));
return { paths: await rawGlob(this.rg, str(body, 'pattern'), cwd, limit, signal) };
}
@@ -219,7 +219,7 @@ export class RemoteExecutor {
const params = record(body.params) as unknown as PiGrepInput;
if (typeof params.pattern !== 'string' || !params.pattern) throw new ExecutorRequestError('INVALID', 'pattern is required');
const root = this.resolvePath(typeof params.path === 'string' && params.path ? params.path : '.');
- this.authorize({ kind: 'read', path: root });
+ this.authorize({ kind: 'read', path: root, scope: 'tree' });
return await piGrep(this.opts.rgPath, root, params, signal);
}
case 'exec.run': {
diff --git a/apps/desktop/src/main/remote-agent/executor/gate.ts b/apps/desktop/src/main/remote-agent/executor/gate.ts
index 18bbb8f746..978bff9ac5 100644
--- a/apps/desktop/src/main/remote-agent/executor/gate.ts
+++ b/apps/desktop/src/main/remote-agent/executor/gate.ts
@@ -7,6 +7,9 @@
* - 全权:一律放行(用户在本机为这个任务选了全权);
* - 凭证类路径、静态可证的高危命令:本机任务这类操作总是逐次问用户,执行器只认本机用户
* 刚批准过的同一操作;
+ * - 可写根外的写与工作区外的递归读:本机任务同样必问(auto-review 对区外写返回 prompt),
+ * 执行器只认本机用户批准过的同一操作 —— 反向请求按本机策略与规范批准重建,发起方那台
+ * 电脑不可信时也不能绕过本机用户的目录授权;
* - 计划模式:只允许读取和静态可证只读的命令,其余同样要本机用户批准过。
* 批准记录只在短时间内有效;命令批准用一次即失效,路径批准在有效期内覆盖同一路径的读写
* (编辑会先读后写)。
@@ -24,7 +27,7 @@ import type { ExecutorWorkspace } from './workspace';
export type ExecutorGateMode = 'full' | 'plan' | 'normal';
export type ExecutorAction =
- | { kind: 'read'; path: string }
+ | { kind: 'read'; path: string; scope?: 'tree' }
| { kind: 'write'; path: string }
| { kind: 'exec'; command: string; cwd: string };
@@ -107,7 +110,15 @@ export class ExecutorGate {
return this.mode === 'plan' && verdict !== 'auto-approve';
}
if (this.workspace.isSensitive(action.path)) return true;
- return action.kind === 'write' && this.mode === 'plan';
+ if (action.kind === 'write') {
+ // 本机任务里「可写根外的写必问用户」(auto-review 对区外写返回 prompt):反向请求不能
+ // 只信发起方(同账号电脑也可能被攻破)的权限逻辑代答,区外写只认本机用户刚批准过的同一
+ // 操作,否则对方可在 Ask / Auto / accept-edits 下覆盖本机任意非凭证路径。
+ return this.mode === 'plan' || !this.workspace.contains(action.path);
+ }
+ // 目录级递归读(搜索 / 列举)的根在工作区外 → 能遍历到区外的凭证子路径(如在 ~ 上 grep
+ // 密钥),与本机任务同样升级为必问;单文件读仍按本机语义放行。
+ return action.scope === 'tree' && !this.workspace.contains(action.path);
}
private consume(action: ExecutorAction): boolean {
diff --git a/apps/desktop/src/main/remote-agent/host/runHost.ts b/apps/desktop/src/main/remote-agent/host/runHost.ts
index f5b7d2d74b..4e518c00a5 100644
--- a/apps/desktop/src/main/remote-agent/host/runHost.ts
+++ b/apps/desktop/src/main/remote-agent/host/runHost.ts
@@ -319,6 +319,16 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {
return JSON.parse(raw.toString('utf8')) as unknown;
}
+ /**
+ * 去重路径上的载荷丢弃:重复 / 过期 op 的上传载荷若不取走,会一直占着暂存配额到过期,
+ * 歧义交付下反复重试的大载荷会把无关上传挡在门外。
+ */
+ function discardPayload(controller: string, payload: RemoteAgentPayload): void {
+ if ('json' in payload) return;
+ uploads.delete(key(controller, payload.uploadId));
+ stopSweepIfIdle();
+ }
+
function append(run: Run, item: unknown): void {
if (run.log.append(item)) return;
if (!run.closing) {
@@ -394,6 +404,12 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {
return file;
}
+ /** 影子工作目录根:`<会话根>/fs/<控制端镜像>` 的上级,按控制端 + 本机侧任务 id 定址。 */
+ function shadowSessionRoot(controller: string, hostSessionId: string): string {
+ const controllerDir = createHash('sha256').update(controller).digest('hex').slice(0, 16);
+ return path.join(deps.runsRoot, 'workspaces', controllerDir, hostSessionId);
+ }
+
/**
* 影子目录:`<会话根>/fs/<控制端真实路径逐级镜像>`。逐级镜像让上级目录里的说明文件落在对应的
* 上级目录,Agent 照本机方式沿目录向上加载;路径对同一任务固定(恢复会话依赖工作目录不变)。
@@ -404,8 +420,7 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {
payload: RemoteAgentOpenPayload,
hostSessionId: string,
): Promise<{ shadowDir: string; mirrorRoot: string; sessionRoot: string }> {
- const controllerDir = createHash('sha256').update(controller).digest('hex').slice(0, 16);
- const sessionRoot = path.join(deps.runsRoot, 'workspaces', controllerDir, hostSessionId);
+ const sessionRoot = shadowSessionRoot(controller, hostSessionId);
const mirrorRoot = path.join(sessionRoot, 'fs');
const segments = mirrorSegments(payload.workspace.workingDir);
const shadowDir = path.join(mirrorRoot, ...segments);
@@ -555,13 +570,28 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {
await fsp.rm(run.attachmentsDir, { recursive: true, force: true }).catch(() => undefined);
// 影子工作区(项目说明类文件的副本)在任务收尾后一并清理,不长期留在本机;同一任务的
// 新旧实例共用同一份目录,只有没有其它实例还在用时才删,避免删掉新实例正在用的目录。
- if (run.workspaceDir && run.hostSessionId !== undefined
- && ![...runs.values()].some((other) => other.hostSessionId === run.hostSessionId)) {
- await fsp.rm(run.workspaceDir, { recursive: true, force: true }).catch(() => undefined);
- }
+ await cleanupShadow(run);
stopSweepIfIdle();
}
+ /**
+ * 影子工作区里是同步过去的项目与个人说明副本,任务收尾后没有恢复价值,留着只会把
+ * 敏感项目上下文堆到下一个任务、退出登录与换账号之后。删除与 prepareShadow 共用同一把
+ * 影子锁,且同一(控制端, 本机侧任务)还有实例在时保留:否则「扫描到没人用 → 删目录」
+ * 与「替换实例重建目录」之间存在竞态,可能删掉替换实例刚建好的目录。
+ */
+ async function cleanupShadow(run: Run): Promise<void> {
+ const hostSessionId = run.hostSessionId;
+ if (!hostSessionId) return;
+ const workspaceDir = run.workspaceDir ?? shadowSessionRoot(run.controller, hostSessionId);
+ await withShadowLock(hostSessionId, async () => {
+ for (const other of runs.values()) {
+ if (other !== run && other.controller === run.controller && other.hostSessionId === hostSessionId) return;
+ }
+ await fsp.rm(workspaceDir, { recursive: true, force: true }).catch(() => undefined);
+ });
+ }
+
function requireRun(controller: string, runId: string): Run {
const run = runs.get(key(controller, runId));
if (!run) fail('REMOTE_AGENT_NOT_FOUND', 'task is not running on this computer');
@@ -693,7 +723,10 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {
}
case 'open': {
const existing = runs.get(key(controller, request.runId));
- if (existing) return {};
+ if (existing) {
+ discardPayload(controller, request.payload);
+ return {};
+ }
if (!deps.isAgentAvailable(request.agentKind)) fail('REMOTE_AGENT_UNSUPPORTED', `${request.agentKind} is not available on this computer`);
const active = [...runs.values()].filter((run) => run.controller === controller && run.closedAt === undefined).length;
if (active >= REMOTE_AGENT_MAX_RUNS_PER_CONTROLLER) fail('REMOTE_AGENT_BUSY', 'too many tasks are running from this computer');
@@ -721,7 +754,10 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {
case 'call': {
const run = requireRun(controller, request.runId);
if (run.closing) fail('REMOTE_AGENT_EXPIRED', 'task has ended');
- if (run.calls.has(request.callId)) return {};
+ if (run.calls.has(request.callId)) {
+ discardPayload(controller, request.payload);
+ return {};
+ }
run.calls.set(request.callId, 'running');
void call(run, request.callId, request.method, request.payload);
return {};
@@ -731,7 +767,11 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {
case 'reply': {
const run = requireRun(controller, request.runId);
const pending = run.pending.get(request.requestId);
- if (!pending) return {};
+ if (!pending) {
+ // 重复 / 已取消的回包:载荷要显式丢掉,不能留在暂存区占配额到过期。
+ discardPayload(controller, request.payload);
+ return {};
+ }
const reply = parseRemoteAgentReply(await resolvePayload(controller, request.payload));
run.pending.delete(request.requestId);
pending.resolve(reply);
@@ -784,7 +824,8 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {
dispose(): void {
if (sweepTimer) clearInterval(sweepTimer);
sweepTimer = null;
- for (const run of runs.values()) void finishRun(run, 'aborted', 'app-quit');
+ // 退出前尽力收尾:影子工作目录含同步过去的项目与个人说明,不能留到下次启动。
+ for (const run of runs.values()) void finishRun(run, 'aborted', 'app-quit').then(() => disposeRun(run));
},
};
}
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index 77fbb0d902..6b7362f179 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -1984,8 +1984,12 @@ export class ClaudeCodeAgent extends BaseAgent {
if (input.hook_event_name === 'PreToolUse') {
const pre = input as PreToolUseHookInput & { agent_id?: string; agent_type?: string };
const builtin = deviceHostedBuiltinToolName(pre.tool_name);
+ // 参数化规则(Bash(git diff:*) 之类)要按本次命令判范围,不能当成整个工具放行。
+ const toolInput = pre.tool_input as Record<string, unknown> | undefined;
+ const command = typeof toolInput?.command === 'string' ? toolInput.command : undefined;
if (builtin && pre.agent_id && pre.agent_type
- && !deviceHostedSubagentAllows(pre.agent_type, builtin, await loadHostedAgentRules())) {
+ && !deviceHostedSubagentAllows(pre.agent_type, builtin, await loadHostedAgentRules(),
+ command !== undefined ? { command } : undefined)) {
return {
continue: true,
hookSpecificOutput: {
diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
index 9ad21020a7..a50e50eb68 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -4310,9 +4310,12 @@ export default async function cindyBridge(pi: any) {
// 目标存在 → realpath 目标;目标不存在 → realpath 最近的**存在的父目录**,
// 用真实父目录判定(父目录链上的 symlink 一并解析)。
// 设备托管:目标在任务所在电脑上,本机文件系统无从解析,按真实工作目录词法解析
- // (那台电脑的执行器会按真实路径再守一道凭证与高危上限)。
- const writeTargetResolved = CINDY_HOSTED
- ? (targetPath ? path.resolve(CINDY_HOSTED.cwd, targetPath) : null)
+ // (那台电脑的执行器会按真实路径再守一道凭证与高危上限)。路径实现按那台电脑的平台
+ // 选(path.win32 / path.posix),与提示改写一致 —— 用本机 path.resolve 解析异构平台
+ // 路径(如 macOS 上解析 C:\project\file)会得到畸形路径,写证据与可写根对不上。
+ const hostedRealPath = CINDY_HOSTED ? (CINDY_HOSTED.platform === 'win32' ? path.win32 : path.posix) : null;
+ const writeTargetResolved = CINDY_HOSTED && hostedRealPath
+ ? (targetPath ? hostedRealPath.resolve(CINDY_HOSTED.cwd, targetPath) : null)
: resolveFileWriteTargetPath(targetPath);
if (
targetPath
diff --git a/packages/maker-core/src/agents/shared/device-hosted.test.ts b/packages/maker-core/src/agents/shared/device-hosted.test.ts
index 609a8ed502..1d5198d999 100644
--- a/packages/maker-core/src/agents/shared/device-hosted.test.ts
+++ b/packages/maker-core/src/agents/shared/device-hosted.test.ts
@@ -105,13 +105,39 @@ describe('deviceHostedSubagentAllows', () => {
['star', { tools: ['*'] }],
]);
expect(deviceHostedSubagentAllows('reader', 'Read', rules)).toBe(true);
- expect(deviceHostedSubagentAllows('reader', 'Bash', rules)).toBe(true);
expect(deviceHostedSubagentAllows('reader', 'Write', rules)).toBe(false);
expect(deviceHostedSubagentAllows('prefixed', 'Edit', rules)).toBe(true);
expect(deviceHostedSubagentAllows('prefixed', 'Read', rules)).toBe(false);
expect(deviceHostedSubagentAllows('star', 'Write', rules)).toBe(true);
});
+ it('scopes parameterised entries to the command of this call', () => {
+ const rules = new Map<string, DeviceHostedAgentToolRule>([
+ ['reader', { tools: ['Read', 'Bash(git log:*)'] }],
+ ]);
+ // 范围内放行;范围外不放行 —— 参数化条目不能当成整个 Bash 的通行证。
+ expect(deviceHostedSubagentAllows('reader', 'Bash', rules, { command: 'git log --oneline' })).toBe(true);
+ expect(deviceHostedSubagentAllows('reader', 'Bash', rules, { command: 'git log' })).toBe(true);
+ expect(deviceHostedSubagentAllows('reader', 'Bash', rules, { command: 'git push origin' })).toBe(false);
+ expect(deviceHostedSubagentAllows('reader', 'Bash', rules, { command: 'rm -rf /' })).toBe(false);
+ // 拿不到本次命令时不放行(无法证明在范围内)。
+ expect(deviceHostedSubagentAllows('reader', 'Bash', rules)).toBe(false);
+ expect(deviceHostedSubagentAllows('reader', 'Bash', rules, {})).toBe(false);
+ // 参数化条目不覆盖跟随 Bash 的后台壳工具;非参数化条目才覆盖。
+ expect(deviceHostedSubagentAllows('reader', 'BashOutput', rules, { command: 'git log' })).toBe(false);
+ });
+
+ it('applies parameterised deny entries only to matching commands', () => {
+ const rules = new Map<string, DeviceHostedAgentToolRule>([
+ ['no-push', { disallowedTools: ['Bash(git push:*)'] }],
+ ]);
+ expect(deviceHostedSubagentAllows('no-push', 'Bash', rules, { command: 'git push origin main' })).toBe(false);
+ expect(deviceHostedSubagentAllows('no-push', 'Bash', rules, { command: 'git diff' })).toBe(true);
+ expect(deviceHostedSubagentAllows('no-push', 'BashOutput', rules)).toBe(true);
+ // 无法证明不命中时按拦下处理。
+ expect(deviceHostedSubagentAllows('no-push', 'Bash', rules)).toBe(false);
+ });
+
it('lets background shell helpers follow Bash', () => {
const rules = new Map<string, DeviceHostedAgentToolRule>([
['no-shell', { disallowedTools: ['Bash'] }],
diff --git a/packages/maker-core/src/agents/shared/device-hosted.ts b/packages/maker-core/src/agents/shared/device-hosted.ts
index d8993e197a..a1e831734a 100644
--- a/packages/maker-core/src/agents/shared/device-hosted.ts
+++ b/packages/maker-core/src/agents/shared/device-hosted.ts
@@ -98,7 +98,9 @@ export function deviceHostedClaudeNote(hosted: DeviceHostedSession, localWorking
* 子代理的工具限制(设备托管)。本机任务里 Claude Code 按子代理定义收窄自带工具;顶替成 Cindy
* 工具后 SDK 不再按名字收窄(MCP 工具一律放行),这里按同样的定义判一次:
* - 自带的只读子代理(Explore / Plan)不能写文件;
- * - 自定义子代理写了 tools 时只能用列出的工具,写了 disallowedTools 时不能用列出的工具。
+ * - 自定义子代理写了 tools 时只能用列出的工具,写了 disallowedTools 时不能用列出的工具;
+ * - 参数化条目(如 `Bash(git diff:*)`)只覆盖范围内的调用:必须按本次 `input.command` 判定,
+ * 不能当成整个工具的放行 —— 否则被 MCP 顶替后子代理可执行任意命令,与本机不一致。
* 不认识的子代理不额外限制(与本机一致:没有定义就继承全部工具)。
*/
export interface DeviceHostedAgentToolRule {
@@ -106,6 +108,12 @@ export interface DeviceHostedAgentToolRule {
disallowedTools?: string[];
}
+/** 本次顶替工具调用的参数(参数化工具规则按它收窄范围)。 */
+export interface DeviceHostedToolCall {
+ /** Bash 本次执行的命令;没有命令(BashOutput / KillShell 或拿不到参数)时缺省。 */
+ command?: string;
+}
+
const READ_ONLY_BUILTIN_AGENTS: Record<string, DeviceHostedAgentToolRule> = {
Explore: { disallowedTools: ['Write', 'Edit', 'NotebookEdit'] },
Plan: { disallowedTools: ['Write', 'Edit', 'NotebookEdit'] },
@@ -138,18 +146,55 @@ export function parseClaudeAgentToolRule(markdown: string): { name: string; rule
};
}
-/** 子代理能否用某个顶替工具(自带工具名)。BashOutput / KillShell 跟随 Bash。 */
+/** 子代理能否用某个顶替工具(自带工具名)。BashOutput / KillShell 跟随 Bash 的非参数化条目。 */
export function deviceHostedSubagentAllows(
agentType: string,
builtin: string,
customRules: ReadonlyMap<string, DeviceHostedAgentToolRule>,
+ call?: DeviceHostedToolCall,
): boolean {
const rule = customRules.get(agentType) ?? READ_ONLY_BUILTIN_AGENTS[agentType];
if (!rule) return true;
const name = builtin === 'BashOutput' || builtin === 'KillShell' ? 'Bash' : builtin;
- const matches = (entry: string) => entry === name || entry === builtin || entry === deviceHostedExecToolName(builtin)
- || entry.startsWith(`${name}(`);
- if (rule.disallowedTools?.some(matches)) return false;
- if (rule.tools && !rule.tools.some((entry) => entry === '*' || matches(entry))) return false;
+ const coversTool = (tool: string) => tool === name || tool === builtin || tool === deviceHostedExecToolName(builtin);
+ /** 参数化条目只约束 Bash 命令本身;BashOutput / KillShell 不执行命令,不被它覆盖。 */
+ const entryCovers = (entry: string, side: 'allow' | 'deny'): boolean => {
+ const split = splitToolEntry(entry);
+ if (!coversTool(split.tool)) return false;
+ if (split.scope === null) return true;
+ if (builtin !== 'Bash') return false;
+ const verdict = toolScopeVerdict(split.scope, call);
+ // allow 侧只有证明确在范围内才放行;deny 侧拿不准就拦(fail-closed)。
+ return side === 'allow' ? verdict === 'match' : verdict !== 'no-match';
+ };
+ if (rule.disallowedTools?.some((entry) => entryCovers(entry, 'deny'))) return false;
+ if (rule.tools && !rule.tools.some((entry) => entry === '*' || entryCovers(entry, 'allow'))) return false;
return true;
}
+
+/** `Bash(git diff:*)` → 工具名 `Bash` + 参数范围 `git diff:*`;不是参数化条目时 scope 为 null。 */
+function splitToolEntry(entry: string): { tool: string; scope: string | null } {
+ const open = entry.indexOf('(');
+ if (open <= 0 || !entry.endsWith(')')) return { tool: entry, scope: null };
+ return { tool: entry.slice(0, open), scope: entry.slice(open + 1, -1) };
+}
+
+type ScopeVerdict = 'match' | 'no-match' | 'unknown';
+
+/**
+ * 参数化条目的范围与本次命令的匹配:`:*` 结尾按前缀匹配(与 Claude Code 同语义的保守
+ * 实现),其余整串精确匹配。范围为空、含不移植的通配符或拿不到本次命令时返回 unknown,
+ * 由调用方按 allow / deny 侧各自的安全方向解释。
+ */
+function toolScopeVerdict(scope: string, call: DeviceHostedToolCall | undefined): ScopeVerdict {
+ const spec = scope.trim();
+ const command = call?.command?.trim();
+ if (!spec || !command) return 'unknown';
+ if (spec.endsWith(':*')) {
+ const prefix = spec.slice(0, -2).trim();
+ if (!prefix) return 'unknown';
+ return command === prefix || command.startsWith(prefix) ? 'match' : 'no-match';
+ }
+ if (/[?*[\]{}]/.test(spec)) return 'unknown';
+ return command === spec ? 'match' : 'no-match';
+}