Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(remote-agent): add transparent virtual workspace
Lizifa16b2747a99
diff --git a/apps/desktop/src/main/remote-agent/__tests__/claudeHosted.e2e.test.ts b/apps/desktop/src/main/remote-agent/__tests__/claudeHosted.e2e.test.tsindex 1196fe1a13..fc1f0f9cca 100644--- a/apps/desktop/src/main/remote-agent/__tests__/claudeHosted.e2e.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/claudeHosted.e2e.test.ts@@ -227,11 +227,13 @@ describe.skipIf(!available)('remote agent with a real Claude Code', () => {'mcp__cindy_exec__NotebookEdit', 'mcp__cindy_exec__BashOutput', 'mcp__cindy_exec__KillShell',]));// 系统提示说明了项目的真实位置;项目说明来自同步的影子目录。- expect(first.system).toContain(`The project lives on the user's computer at \`${project}\``);+ expect(first.system).not.toContain(project);+ expect(first.system).toContain('# Workspace');expect(`${first.system}\n${first.firstUser}`).toContain('Always answer briefly.');const last = requests.at(-1)!;expect(last.results.map((result) => result.isError)).toEqual([false, false, false, false]);- expect(last.results[0].text).toContain(project);+ expect(last.results[0].text).not.toContain(project);+ expect(last.results[0].text).toContain(hostRoot);expect(last.results[0].text).toContain('hello.txt');expect(last.results[2].text).toContain('hello from the controller');expect(fs.readFileSync(path.join(project, 'made.txt'), 'utf8')).toBe('two\n');diff --git a/apps/desktop/src/main/remote-agent/__tests__/codexHosted.e2e.test.ts b/apps/desktop/src/main/remote-agent/__tests__/codexHosted.e2e.test.tsindex 431d78e589..3f7c28b45b 100644--- a/apps/desktop/src/main/remote-agent/__tests__/codexHosted.e2e.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/codexHosted.e2e.test.ts@@ -173,10 +173,12 @@ describe.skipIf(!available)('remote agent with a real Codex', () => {expect(fs.readFileSync(path.join(project, 'made-by-codex.txt'), 'utf8')).toBe('hello codex\n');const last = bodies.at(-1)!;// 命令在控制端的项目目录执行。- expect(last).toContain(project);+ expect(last).not.toContain(project);+ expect(last).toContain(hostRoot);expect(last).toContain('hello.txt');// 模型看到的工作目录与项目说明都来自控制端。- expect(bodies[0]).toContain(project);+ expect(bodies[0]).not.toContain(project);+ expect(bodies[0]).toContain(hostRoot);expect(bodies[0]).toContain('Keep answers short.');const hostFiles = fs.readdirSync(hostRoot, { recursive: true }).map(String);expect(hostFiles.some((file) => file.endsWith('made-by-codex.txt'))).toBe(false);diff --git a/apps/desktop/src/main/remote-agent/__tests__/execServerProjection.e2e.test.ts b/apps/desktop/src/main/remote-agent/__tests__/execServerProjection.e2e.test.tsnew file mode 100644index 0000000000..c358e09f34--- /dev/null+++ b/apps/desktop/src/main/remote-agent/__tests__/execServerProjection.e2e.test.ts@@ -0,0 +1,68 @@+import fs from 'node:fs';+import fsp from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { pathToFileURL } from 'node:url';+import { describe, expect, it } from 'vitest';++import { ExecServerRelay } from '../controller/execServerRelay';+import { ExecutorWorkspace } from '../executor/workspace';+import type { ExecutorAction } from '../executor/gate';++const REPO = path.resolve(__dirname, '../../../../../..');+const CODEX = path.join(REPO, 'apps', 'codex-package-bin', process.platform + '-' + process.arch, 'bin', process.platform === 'win32' ? 'codex.exe' : 'codex');++describe.skipIf(!fs.existsSync(CODEX))('native exec-server workspace projection', () => {+ it('initializes and executes with virtual paths while the file and authorization stay on this computer', async () => {+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-exec-projection-')));+ const project = path.join(root, 'project');+ fs.mkdirSync(project);+ const virtual = '/Users/agent/workspace';+ const workspace = new ExecutorWorkspace({ workingDir: project, aliases: [{ from: virtual, to: project }] });+ workspace.setVirtualRoot('/Users/agent');+ const messages: Array<Record<string, any>> = [];+ const actions: ExecutorAction[] = [];+ let parts = '';+ const relay = new ExecServerRelay({+ codexPath: CODEX,+ cwd: project,+ workspace,+ authorize: (action) => { actions.push(action); return { ok: true }; },+ push: async (frames) => {+ for (const frame of frames) {+ if (frame.kind !== 'message') continue;+ parts += frame.data;+ if (!frame.more) { messages.push(JSON.parse(parts)); parts = ''; }+ }+ },+ });+ const send = (message: unknown) => relay.handle({ t: 'ws', connId: 'c1', kind: 'message', data: JSON.stringify(message) });+ try {+ relay.handle({ t: 'ws', connId: 'c1', kind: 'open', path: '/ws/exec-server' });+ send({ id: 1, method: 'initialize', params: { clientName: 'cindy-test', clientVersion: '1' } });+ await expect.poll(() => messages.find((item) => item.id === 1), { timeout: 5000 }).toBeDefined();+ const init = messages.find((item) => item.id === 1)!;+ expect(init.result.environmentInfo.cwd).toBe('file:///Users/agent/workspace');+ expect(init.result.environmentInfo.userHomeDir).not.toBe(pathToFileURL(os.homedir()).href);+ send({ method: 'initialized', params: {} });+ send({ id: 2, method: 'process/start', params: {+ processId: 'p1',+ argv: [process.execPath, '-e', 'require("node:fs").writeFileSync(process.argv[1], "correct computer"); console.log(process.cwd());', virtual + '/made.txt'],+ cwd: 'file:///Users/agent/workspace',+ env: process.platform === 'win32' ? { SystemRoot: process.env.SystemRoot, TEMP: os.tmpdir() } : {},+ tty: false,+ } });+ await expect.poll(() => messages.some((item) => item.method === 'process/closed'), { timeout: 5000 }).toBe(true);+ expect(messages.find((item) => item.id === 2)?.error).toBeUndefined();+ expect(fs.readFileSync(path.join(project, 'made.txt'), 'utf8')).toBe('correct computer');+ const output = messages.filter((item) => item.method === 'process/output')+ .map((item) => Buffer.from(item.params.chunk, 'base64').toString()).join('');+ expect(output.trim()).toBe(virtual);+ expect(actions).toEqual([expect.objectContaining({ kind: 'exec', cwd: project })]);+ expect(JSON.stringify(messages)).not.toContain(project.replace(/\\/g, '\\\\'));+ } finally {+ relay.close();+ await fsp.rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });+ }+ });+});diff --git a/apps/desktop/src/main/remote-agent/__tests__/hostLifecycle.test.ts b/apps/desktop/src/main/remote-agent/__tests__/hostLifecycle.test.tsindex 799f612427..fc939e96d3 100644--- a/apps/desktop/src/main/remote-agent/__tests__/hostLifecycle.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/hostLifecycle.test.ts@@ -128,7 +128,7 @@ describe('hosted shadow workspace cleanup', () => {host.dispose();await settle();- expect(fs.existsSync(sessionRoot('controller-1', 'task-1'))).toBe(false);+ await vi.waitFor(() => 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 () => {@@ -158,7 +158,7 @@ describe('hosted shadow workspace cleanup', () => {clock += 61_000;await vi.advanceTimersByTimeAsync(5_000);await settle();- expect(fs.existsSync(sessionRootPath)).toBe(false);+ await vi.waitFor(() => expect(fs.existsSync(sessionRootPath)).toBe(false));host.dispose();});});diff --git a/apps/desktop/src/main/remote-agent/__tests__/mirror.test.ts b/apps/desktop/src/main/remote-agent/__tests__/mirror.test.tsindex b307ebf7d1..75ccf2f895 100644--- a/apps/desktop/src/main/remote-agent/__tests__/mirror.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/mirror.test.ts@@ -18,6 +18,8 @@ import {} from '../controller/projectFiles';import { shadowAliases, startRemoteAgentSession } from '../controller/startRemote';import { createRemoteAgentHost, mirrorSegments, type HostedStartInput } from '../host/runHost';+import { hostedStartOptions } from '../host/service';+import { ExecutorWorkspace } from '../executor/workspace';import { MAX_ANCESTOR_LEVELS } from '../wire';const RG = path.resolve(__dirname, '../../../../../ripgrep-bin', `${process.platform}-${process.arch}`, process.platform === 'win32' ? 'rg.exe' : 'rg');@@ -102,16 +104,36 @@ describe('collectAncestorInstructionFiles', () => {});describe('collectProjectInstructionFiles', () => {- it('rejects symlinks so a checkout cannot smuggle files from outside the project', async () => {+ it('rejects directory links so a checkout cannot smuggle files from outside the project', async () => {+ const project = path.join(root, 'proj');+ const outside = path.join(root, 'outside');+ write(path.join(project, 'CLAUDE.md'), 'real rules');+ write(path.join(outside, 'SKILL.md'), 'secret leak');+ fs.mkdirSync(path.join(project, '.claude', 'skills'), { recursive: true });+ // Windows junction 不需要文件 symlink 的管理员权限,目录越界检查仍实跑。+ fs.symlinkSync(outside, path.join(project, '.claude', 'skills', 'leak'), process.platform === 'win32' ? 'junction' : 'dir');+ const files = await collectProjectInstructionFiles(project);+ expect(files.map((file) => file.path)).toEqual(['CLAUDE.md']);+ expect(files.map((file) => Buffer.from(file.data, 'base64').toString())).toEqual(['real rules']);+ });++ it('rejects file symlinks when the filesystem supports creating them', async (context) => {const project = path.join(root, 'proj');const outside = path.join(root, 'outside');write(path.join(project, 'CLAUDE.md'), 'real rules');write(path.join(outside, 'leak.md'), 'secret leak');write(path.join(outside, '.env'), 'SECRET=1');fs.mkdirSync(path.join(project, '.claude', 'skills'), { recursive: true });- // 同名文件、目录与独立文件三种符号链接借道都不跟随。- fs.symlinkSync(path.join(outside, '.env'), path.join(project, 'CLAUDE.local.md'));- fs.symlinkSync(outside, path.join(project, '.claude', 'skills', 'leak'));+ // 实际探测文件 symlink 能力;有权限的 Windows 与 macOS/Linux 均保留真实覆盖。+ try {+ fs.symlinkSync(path.join(outside, '.env'), path.join(project, 'CLAUDE.local.md'), 'file');+ } catch (error) {+ if (['EPERM', 'EACCES', 'ENOTSUP'].includes((error as NodeJS.ErrnoException).code ?? '')) {+ context.skip();+ return;+ }+ throw error;+ }fs.symlinkSync(path.join(outside, 'leak.md'), path.join(project, '.claude', 'skills', 'leak.md'));const files = await collectProjectInstructionFiles(project);expect(files.map((file) => file.path)).toEqual(['CLAUDE.md']);@@ -211,7 +233,10 @@ describe('shadow on the other computer', () => {const handle = await startRemoteAgentSession('claude-code', {sessionId: 'task-1',workingDir: project,+ extraDirs: [path.join(project, 'src'), path.join(root, 'external')],+ writableDirs: [path.join(root, 'external')],model: 'claude-opus',+ userPrompt: `Please inspect ${path.join(project, 'src', 'index.ts')}.`,permissionMode: 'default',}, {invoke: async (args) => JSON.parse(JSON.stringify(await host.handle('controller-1', JSON.parse(JSON.stringify(args[0]))) ?? null)),@@ -238,7 +263,8 @@ describe('shadow on the other computer', () => {const [input] = inputs;const read = (file: string) => fs.readFileSync(file, 'utf8');expect(input.shadowDir.startsWith(`${input.mirrorRoot}${path.sep}`)).toBe(true);- expect(input.shadowDir.endsWith(path.join('work', 'team', 'proj'))).toBe(true);+ expect(input.shadowDir).not.toContain(project);+ expect(path.relative(input.mirrorRoot, input.shadowDir).split(path.sep)).toHaveLength(MAX_ANCESTOR_LEVELS + 1);expect(read(path.join(input.shadowDir, 'CLAUDE.md'))).toBe('project rules');expect(read(path.join(path.dirname(input.shadowDir), 'AGENTS.md'))).toBe('team rules');expect(read(path.join(path.dirname(path.dirname(input.shadowDir)), 'CLAUDE.md'))).toBe('work rules');@@ -251,6 +277,24 @@ describe('shadow on the other computer', () => {permissions: { allow: ['Bash(ls:*)', 'Bash(npm test:*)'] },});expect(input.personalInstructions).toBe('personal instructions');+ expect(input.extraDirs?.[0]).toBe(path.join(input.shadowDir, 'src'));+ expect(input.extraDirs?.[1]).toBe(path.join(input.mirrorRoot, 'additional', 'dir-1'));+ expect(input.writableDirs?.[0]).toBe(input.extraDirs?.[1]);+ expect(input.workspace.homeDir).toBe(os.homedir());+ expect(input.options.userPrompt).toBe(`Please inspect ${path.join(input.shadowDir, 'src', 'index.ts')}.`);+ const opts = hostedStartOptions(input);+ expect(opts.deviceHosted?.workingDir).toBe(input.shadowDir);+ expect(opts.deviceHosted?.pathPlatform).toBe(process.platform);+ expect(opts.deviceHosted?.homeDir).toBeUndefined();+ expect(opts.extraDirs).toEqual(input.extraDirs);+ expect(opts.writableDirs).toEqual(input.writableDirs);+ const workspace = new ExecutorWorkspace({ workingDir: project });+ workspace.setAliases(shadowAliases({ ...input }, project, [], {+ extraDirs: [path.join(project, 'src'), path.join(root, 'external')], writableDirs: [path.join(root, 'external')],+ }));+ workspace.setVirtualRoot(input.mirrorRoot);+ expect(workspace.resolve(input.extraDirs![1])).toBe(path.join(root, 'external'));+ expect(workspace.toAgentPath(path.join(root, 'external', 'a.ts'))).toBe(path.join(input.extraDirs![1], 'a.ts'));await handle.close({ reason: 'navigation' });host.dispose();diff --git a/apps/desktop/src/main/remote-agent/__tests__/piHosted.e2e.test.ts b/apps/desktop/src/main/remote-agent/__tests__/piHosted.e2e.test.tsindex 489a56f9b6..13fb511528 100644--- a/apps/desktop/src/main/remote-agent/__tests__/piHosted.e2e.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/piHosted.e2e.test.ts@@ -16,6 +16,7 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest';import { startRemoteAgentSession } from '../controller/startRemote';import { createRemoteAgentHost } from '../host/runHost';+import { hostedStartOptions } from '../host/service';const REPO = path.resolve(__dirname, '../../../../../..');const ARCH = `${process.platform}-${process.arch}`;@@ -146,20 +147,7 @@ describe.skipIf(!available)('remote agent with a real Pi', () => {const agent = new PiAgent(piDeps(path.join(root, 'pi-home')));const host = createRemoteAgentHost({isAgentAvailable: (kind) => kind === 'pi',- startHosted: (input) => agent.startSession({- sessionId: input.hostSessionId,- workingDir: input.shadowDir,- model: input.options.model,- permissionMode: input.options.permissionMode as never,- extraDirs: input.workspace.extraDirs,- writableDirs: input.workspace.writableDirs,- deviceHosted: {- ...input.workspace,- tunnelUrl: input.tunnel.url,- tunnelToken: input.tunnel.token,- mcpServers: input.mcpServers,- },- }),+ startHosted: (input) => agent.startSession(hostedStartOptions(input)),isControllerAuthorized: () => true,captureOwner: () => 'owner',isOwnerCurrent: () => true,@@ -202,7 +190,8 @@ describe.skipIf(!available)('remote agent with a real Pi', () => {const last = requests.at(-1)!;const [bash, write, read, edit, grep, ls, find] = last.results;// 命令在控制端的项目目录执行,看得到控制端的文件。- expect(bash).toContain(project);+ expect(bash).not.toContain(project);+ expect(bash).toContain(hostRoot);expect(bash).toContain('hello.txt');expect(write).toMatch(/made-by-pi\.txt/);expect(read).toContain('hello from the controller');@@ -217,9 +206,10 @@ describe.skipIf(!available)('remote agent with a real Pi', () => {expect(hostFiles.some((file) => file.endsWith('made-by-pi.txt'))).toBe(false);expect(hostFiles.some((file) => file.endsWith('AGENTS.md'))).toBe(true);// 模型看到的是控制端的真实目录与项目说明。- expect(requests[0].system).toContain(`<cwd>\n${project}\n</cwd>`);- expect(requests[0].system).not.toContain(hostRoot);- expect(requests[0].system).toContain(`<project_instructions path="${path.join(project, 'AGENTS.md')}">`);+ expect(requests[0].system).not.toContain(project);+ expect(requests[0].system).toContain('# Workspace');+ expect(requests[0].system).toContain(hostRoot);+ expect(requests[0].system).toContain('AGENTS.md');expect(requests[0].system).toContain('Always be precise.');// 工具清单与本机任务一致(读写编辑也有提示片段)。expect(requests[0].system).toMatch(/- read: /);@@ -249,13 +239,7 @@ describe.skipIf(!available)('remote agent with a real Pi', () => {const agent = new PiAgent(piDeps(path.join(root, 'pi-home-ask')));const host = createRemoteAgentHost({isAgentAvailable: () => true,- startHosted: (input) => agent.startSession({- sessionId: input.hostSessionId,- workingDir: input.shadowDir,- model: input.options.model,- permissionMode: input.options.permissionMode as never,- deviceHosted: { ...input.workspace, tunnelUrl: input.tunnel.url, tunnelToken: input.tunnel.token, mcpServers: input.mcpServers },- }),+ startHosted: (input) => agent.startSession(hostedStartOptions(input)),isControllerAuthorized: () => true,captureOwner: () => 'owner',isOwnerCurrent: () => true,diff --git a/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts b/apps/desktop/src/main/remote-agent/controller/execServerRelay.tsindex 8490ff053e..9938dfb7e7 100644--- a/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts+++ b/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts@@ -10,7 +10,7 @@*/import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';import path from 'node:path';-import { fileURLToPath } from 'node:url';+import { fileURLToPath, pathToFileURL } from 'node:url';import {REMOTE_AGENT_MAX_INLINE_PAYLOAD_CHARS,@@ -21,6 +21,7 @@ import {} from '@cindy/device-link';import type { ExecutorAction, ExecutorGateDecision } from '../executor/gate';+import type { ExecutorWorkspace } from '../executor/workspace';export const EXEC_SERVER_WS_PATH = '/ws/exec-server';/** exec-server 单行(一条 JSON-RPC 消息)上限:大文件读写的 base64 也在这里面。 */@@ -31,6 +32,7 @@ const FRAME_CHARS = REMOTE_AGENT_MAX_INLINE_PAYLOAD_CHARS - 1024;export interface ExecServerRelayDeps {codexPath: string;cwd: string;+ workspace: ExecutorWorkspace;authorize(action: ExecutorAction): ExecutorGateDecision;push(frames: RemoteAgentPushFrame[]): Promise<void>;env?: NodeJS.ProcessEnv;@@ -85,6 +87,61 @@ export function execServerActions(method: string, params: unknown, cwd: string):return paths.map((target) => ({ kind, path: target }) as ExecutorAction);}+/** 仅映射协议路径和命令,绝不改写 fs/writeFile 的文件数据。 */+export function mapExecServerParams(value: unknown, workspace: ExecutorWorkspace): unknown {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return value;+ const result = { ...value as Record<string, unknown> };+ for (const key of ['cwd', 'path', 'sourcePath', 'destinationPath', 'source', 'destination', 'from', 'to', 'target']) {+ const item = result[key];+ if (typeof item !== 'string') continue;+ if (item.startsWith('file://')) {+ const url = new URL(item);+ const foreign = decodeURIComponent(url.pathname).replace(/^\/([A-Za-z]:)/, '$1');+ result[key] = pathToFileURL(workspace.resolve(foreign)).href;+ } else result[key] = workspace.resolve(item);+ }+ if (Array.isArray(result.argv)) result.argv = result.argv.map((part) => typeof part === 'string' ? workspace.mapCommand(part) : part);+ if (typeof result.command === 'string') result.command = workspace.mapCommand(result.command);+ return result;+}++/** JSON 层逐字符串投影,文件 base64 数据原样返回;进程输出单独解码。 */+export function mapExecServerResult(value: unknown, workspace: ExecutorWorkspace, method?: string): unknown {+ if (typeof value === 'string') {+ if (value.startsWith('file://')) {+ try {+ const uri = new URL(value);+ const real = fileURLToPath(uri);+ const virtual = workspace.toAgentPath(real);+ if (virtual === real) return value;+ uri.host = '';+ uri.pathname = virtual.replace(/\\/g, '/');+ return uri.href;+ } catch { return value; }+ }+ return workspace.mapTextForAgent(value);+ }+ if (Array.isArray(value)) return value.map((item) => mapExecServerResult(item, workspace, method));+ if (!value || typeof value !== 'object') return value;+ const record = value as Record<string, unknown>;+ // 初始化里的 HOME / temp 同样只暴露本机虚拟目录;这些别名不增加执行权限。+ if (record.environmentInfo && typeof record.environmentInfo === 'object') {+ const info = record.environmentInfo as Record<string, unknown>;+ const directories = [info.userHomeDir, info.tempDir, ...(Array.isArray(info.temporaryDirectories) ? info.temporaryDirectories : [])];+ workspace.virtualizeDirs(directories.flatMap((dir) => {+ if (typeof dir !== 'string') return [];+ try { return [dir.startsWith('file://') ? fileURLToPath(dir) : dir]; } catch { return []; }+ }));+ }+ const currentMethod = typeof record.method === 'string' ? record.method : method;+ return Object.fromEntries(Object.entries(record).map(([key, item]) => {+ if (currentMethod === 'process/output' && key === 'chunk' && typeof item === 'string') {+ return [key, workspace.mapOutputForAgent(Buffer.from(item, 'base64')).toString('base64')];+ }+ return [key, mapExecServerResult(item, workspace, currentMethod)];+ }));+}+export class ExecServerRelay {private readonly connections = new Map<string, Connection>();private outbox: RemoteAgentPushFrame[] = [];@@ -142,7 +199,7 @@ export class ExecServerRelay {if (index < 0) break;const line = connection.buffer.slice(0, index);connection.buffer = connection.buffer.slice(index + 1);- if (line.trim()) this.sendMessage(connId, line);+ if (line.trim()) this.sendMessage(connId, this.projectOutbound(line));}if (connection.buffer.length > MAX_LINE_CHARS) {this.deps.log?.warn('remote agent: exec-server line too long; closing', { connId });@@ -166,12 +223,14 @@ export class ExecServerRelay {message = null;}if (message && typeof message.method === 'string' && message.id !== undefined) {+ message.params = mapExecServerParams(message.params, this.deps.workspace);+ data = JSON.stringify(message);for (const action of execServerActions(message.method, message.params, this.deps.cwd)) {const decision = this.deps.authorize(action);if (!decision.ok) {this.sendMessage(connId, JSON.stringify({id: message.id,- error: { code: -32001, message: decision.reason ?? 'Not allowed on this computer.' },+ error: { code: -32001, message: this.deps.workspace.mapTextForAgent(decision.reason ?? 'Not allowed in this workspace.') },}));return;}@@ -180,6 +239,14 @@ export class ExecServerRelay {connection.child.stdin.write(`${data}\n`);}+ private projectOutbound(line: string): string {+ try {+ return JSON.stringify(mapExecServerResult(JSON.parse(line), this.deps.workspace));+ } catch {+ return this.deps.workspace.mapTextForAgent(line);+ }+ }+private dropConnection(connId: string, notifyRemote: boolean): void {const connection = this.connections.get(connId);if (!connection || connection.closed) return;diff --git a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts b/apps/desktop/src/main/remote-agent/controller/proxyHandle.tsindex 1d43f3ed6e..8740bff171 100644--- a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts+++ b/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts@@ -37,8 +37,11 @@ export interface RemoteStartedInfo {agentKind: AgentKind;model: string;shadowDir: string;- /** 影子目录按真实路径镜像时的镜像根(那台电脑上的路径)。 */+ /** Agent 主机上的虚拟镜像根。 */mirrorRoot?: string;+ extraDirs?: string[];+ writableDirs?: string[];+ virtualWorkspace?: boolean;methods: string[];state: Record<string, unknown>;requestSessionId?: string;@@ -58,7 +61,10 @@ export function parseStartedInfo(value: Record<string, unknown>, kind: AgentKindagentKind: kind,model: str(value.model) ?? '',shadowDir: str(value.shadowDir) ?? '',+ virtualWorkspace: value.virtualWorkspace === true,...(str(value.mirrorRoot) ? { mirrorRoot: str(value.mirrorRoot) } : {}),+ extraDirs: Array.isArray(value.extraDirs) ? value.extraDirs.filter((item): item is string => typeof item === 'string') : [],+ writableDirs: Array.isArray(value.writableDirs) ? value.writableDirs.filter((item): item is string => typeof item === 'string') : [],methods: Array.isArray(value.methods) ? value.methods.filter((m): m is string => typeof m === 'string') : [],state: value.state && typeof value.state === 'object' ? value.state as Record<string, unknown> : {},...(str(value.requestSessionId) ? { requestSessionId: str(value.requestSessionId) } : {}),@@ -216,6 +222,16 @@ export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHandasync function sendLike(method: 'send' | 'steer', message: UserMessage, opts?: SendOptions): Promise<void> {const encoded = await encodeSendOptions(opts, readImage);const wireMessage = await encodeUserMessage(message, readImage);+ const projectMessage = (wire: typeof wireMessage) => {+ if (typeof wire.content === 'string') wire.content = deps.workspace.mapTextForAgent(wire.content);+ else wire.content = wire.content.map((block) => {+ if (block.type === 'text') return { ...block, text: deps.workspace.mapTextForAgent(block.text) };+ if (block.type === 'file' || block.type === 'mention') return { ...block, path: deps.workspace.toAgentPath(block.path) };+ return block;+ });+ };+ projectMessage(wireMessage);+ if (encoded.wire.cindy?.autoReviewSourceContent) projectMessage(encoded.wire.cindy.autoReviewSourceContent);const callId = deps.newId();if (encoded.onTranscriptUserEntry || encoded.onInteractionStateChange) {sendCallbacks.set(callId, {@@ -323,10 +339,10 @@ export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHand}),...optional('setExtraDirs', async (dirs: string[], libraryRoot?: string | null) => {deps.onExtraDirs?.(dirs);- await call('setExtraDirs', dirs, libraryRoot ?? null);+ await call('setExtraDirs', deps.workspace.virtualizeDirs(dirs), libraryRoot ? deps.workspace.virtualizeDirs([libraryRoot])[0] : null);}),...optional('setWritableDirs', async (dirs: string[]) => {- await call('setWritableDirs', dirs);+ await call('setWritableDirs', deps.workspace.virtualizeDirs(dirs));// 对方成功后才更新本机执行器的根目录:新建的可写目录在本机也能过 root 判定,// 撤掉的不再被本机上限当可信根;失败时两边都保持原状。deps.onWritableDirs?.(dirs);diff --git a/apps/desktop/src/main/remote-agent/controller/router.ts b/apps/desktop/src/main/remote-agent/controller/router.tsindex 41222620bf..033f0fb999 100644--- a/apps/desktop/src/main/remote-agent/controller/router.ts+++ b/apps/desktop/src/main/remote-agent/controller/router.ts@@ -59,6 +59,24 @@ function errorStatus(code: string): number {export function createReverseHttpRouter(deps: ReverseHttpRouterDeps) {const doFetch = deps.fetch ?? fetch;+ const workspace = deps.executor.workspace;++ const mapArguments = (value: unknown, key = ''): unknown => {+ if (typeof value === 'string') {+ if (/^(?:cmd|command)$/.test(key)) return workspace.mapCommand(value);+ if (/^(?:path|filePath|file_path|directory|workingDir|cwd|root|libraryRoot|sourcePath|destinationPath)$/i.test(key)) return workspace.mapAlias(value);+ return value;+ }+ if (Array.isArray(value)) return value.map((item) => mapArguments(item, key));+ if (!value || typeof value !== 'object') return value;+ return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, mapArguments(item, name)]));+ };+ const projectResult = (value: unknown): unknown => {+ if (typeof value === 'string') return workspace.mapTextForAgent(value);+ if (Array.isArray(value)) return value.map(projectResult);+ if (!value || typeof value !== 'object') return value;+ return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, projectResult(item)]));+ };async function forwardMcp(target: LocalMcpTarget,@@ -76,10 +94,24 @@ export function createReverseHttpRouter(deps: ReverseHttpRouterDeps) {const response = await doFetch(target.url, {method,headers: outgoing,- ...(body && method !== 'GET' && method !== 'HEAD' ? { body: new Uint8Array(body) } : {}),+ ...(body && method !== 'GET' && method !== 'HEAD' ? { body: new Uint8Array((() => {+ try {+ const message = JSON.parse(body.toString('utf8'));+ if (message.method === 'tools/call' && message.params?.arguments) message.params.arguments = mapArguments(message.params.arguments);+ return Buffer.from(JSON.stringify(message));+ } catch { return body; }+ })()) } : {}),signal,});- const data = Buffer.from(await response.arrayBuffer());+ let data = Buffer.from(await response.arrayBuffer());+ if (response.headers.get('content-type')?.includes('application/json')) {+ try { data = Buffer.from(JSON.stringify(projectResult(JSON.parse(data.toString('utf8'))))); } catch { /* 非 JSON 原样透传。 */ }+ } else if (response.headers.get('content-type')?.includes('text/event-stream')) {+ data = Buffer.from(data.toString('utf8').split('\n').map((line) => {+ if (!line.startsWith('data:')) return line;+ try { return 'data: ' + JSON.stringify(projectResult(JSON.parse(line.slice(5).trim()))); } catch { return line; }+ }).join('\n'));+ }const replyHeaders: Array<[string, string]> = [];response.headers.forEach((value, name) => {if (FORWARD_RESPONSE_HEADERS.has(name.toLowerCase())) replyHeaders.push([name, value]);diff --git a/apps/desktop/src/main/remote-agent/controller/startRemote.ts b/apps/desktop/src/main/remote-agent/controller/startRemote.tsindex 6f6f04c808..d824284291 100644--- a/apps/desktop/src/main/remote-agent/controller/startRemote.ts+++ b/apps/desktop/src/main/remote-agent/controller/startRemote.ts@@ -84,27 +84,42 @@ function parentOf(value: string): string | null {}/**- * 影子目录(对方电脑上的路径) → 本机真实路径的映射。影子目录按真实路径逐级镜像,所以每一级- * 上级目录都一一对应;同步过去的个人 Skill 等映射回你这台的个人配置目录。越具体的放越前面。+ * 影子目录(对方电脑上的路径) → 本机真实路径的映射。虚拟工作区使用固定 opaque 层级,旧协议+ * 仍按真实路径逐级镜像;同步过去的个人 Skill 等映射回你这台的个人配置目录。越具体的放越前面。*/export function shadowAliases(- started: { shadowDir: string; mirrorRoot?: string },+ started: { shadowDir: string; mirrorRoot?: string; extraDirs?: string[]; writableDirs?: string[]; virtualWorkspace?: boolean },workingDir: string,personalRoots: ReadonlyArray<{ relative: string; local: string }>,+ directories?: { extraDirs: readonly string[]; writableDirs: readonly string[] },): Array<{ from: string; to: string }> {if (!started.shadowDir) return [];const aliases: Array<{ from: string; to: string }> = personalRoots.map((root) => ({from: `${started.shadowDir.replace(/[\\/]+$/, '')}/${root.relative}`,to: root.local,}));+ if (started.virtualWorkspace && directories) {+ for (const key of ['extraDirs', 'writableDirs'] as const) {+ for (const [index, from] of (started[key] ?? []).entries()) {+ const to = directories[key][index];+ if (to) aliases.push({ from, to });+ }+ }+ }+ if (started.virtualWorkspace && started.mirrorRoot) {+ const native = /^[A-Za-z]:|^\\\\/.test(started.mirrorRoot) ? path.win32 : path.posix;+ aliases.push({ from: native.join(started.mirrorRoot, 'home'), to: os.homedir() });+ aliases.push({ from: native.join(started.mirrorRoot, 'tmp'), to: os.tmpdir() });+ }const mirrorRoot = started.mirrorRoot?.replace(/\\/g, '/').replace(/\/+$/, '');let shadow = started.shadowDir;let real = workingDir;+ const realPath = /^[A-Za-z]:|^\\\\/.test(workingDir) ? path.win32 : path.posix;aliases.push({ from: shadow, to: real });if (!mirrorRoot) return aliases;for (;;) {const nextShadow = parentOf(shadow);- const nextReal = path.dirname(real);+ const nextReal = realPath.dirname(real);if (!nextShadow || nextReal === real || !nextShadow.startsWith(`${mirrorRoot}/`)) break;shadow = nextShadow;real = nextReal;@@ -148,6 +163,8 @@ export async function startRemoteAgentSession(const router = createReverseHttpRouter({ executor, mcpTarget: (name) => mcp.servers.get(name) });let controller: RemoteAgentHandleController | null = null;+ let personalRoots: Array<{ relative: string; local: string }> = [];+ let projectionReady = false;const early: Array<{ type: 'event' | 'state'; value: unknown }> = [];let closedEarly: { reason: string; message?: string } | null = null;// Codex:对方的 Codex 把本机当作 exec-server 执行环境。客户端在下面创建,帧推送时再取。@@ -157,6 +174,7 @@ export async function startRemoteAgentSession(? new ExecServerRelay({codexPath,cwd: workspace.workingDir,+ workspace,authorize: (action) => executor.check(action),push: async (frames) => {await pushFrames?.(frames);@@ -182,6 +200,15 @@ export async function startRemoteAgentSession(else early.push({ type: 'event', value: event });},onState: (state) => {+ const projection = state.workspaceProjection as Parameters<typeof shadowAliases>[0] | undefined;+ if (projection?.virtualWorkspace === true && typeof projection.shadowDir === 'string') {+ workspace.setAliases(shadowAliases(projection, workspace.workingDir, personalRoots, { extraDirs, writableDirs }));+ workspace.setVirtualRoot(projection.mirrorRoot);+ projectionReady = true;+ state = { ...state };+ delete state.workspaceProjection;+ if (!Object.keys(state).length) return;+ }if (controller) controller.onState(state);else early.push({ type: 'state', value: state });},@@ -216,8 +243,10 @@ export async function startRemoteAgentSession(const ancestorFiles = await (deps.collectAncestorFiles?.(opts.workingDir) ?? Promise.resolve([])).catch(() => []);const collectedPersonal = await (deps.collectPersonal?.(kind, projectFiles) ?? Promise.resolve(null)).catch(() => null);+ personalRoots = collectedPersonal?.roots ?? [];const payload: RemoteAgentOpenPayload = {sessionId: opts.sessionId,+ virtualWorkspace: true,options: encodeStartOptions(opts),workspace: {workingDir: opts.workingDir,@@ -226,6 +255,7 @@ export async function startRemoteAgentSession(platform: process.platform,shell: shellName(),osVersion: `${os.type()} ${os.release()}`,+ // 仅供被控端把项目说明中的本机 Home 路径投影到虚拟工作区;不会进入 deviceHosted。homeDir: os.homedir(),isGitRepo: await deps.isGitRepo(opts.workingDir).catch(() => false),},@@ -245,7 +275,10 @@ export async function startRemoteAgentSession(}if (closedEarly) throw new Error((closedEarly as { message?: string }).message ?? '[REMOTE_AGENT_UNAVAILABLE] The agent stopped right after starting.');const started = parseStartedInfo(startedRaw, kind);- workspace.setAliases(shadowAliases(started, workspace.workingDir, collectedPersonal?.roots ?? []));+ if (!projectionReady) {+ workspace.setAliases(shadowAliases(started, workspace.workingDir, collectedPersonal?.roots ?? [], { extraDirs, writableDirs }));+ workspace.setVirtualRoot(started.virtualWorkspace ? started.mirrorRoot : undefined);+ }controller = createRemoteAgentHandle({client,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.tsindex 0969122d19..53e1a0f378 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@@ -72,14 +72,14 @@ describe('workspace', () => {// 直接 path.resolve(输入) 会拿到当前进程盘符、与实现语义不一致。expect(workspace.resolve('/remote/shadow/projX/y')).toBe(path.resolve(project, '/remote/shadow/projX/y'));expect(workspace.mapCommand('cat /remote/shadow/proj/a.txt && ls /remote/shadow/projX'))- .toBe(`cat ${project}/a.txt && ls /remote/shadow/projX`);+ .toBe(`cat ${process.platform === 'win32' ? project.replace(/\\/g, '/') : project}/a.txt && ls /remote/shadow/projX`);expect(() => workspace.resolve('')).toThrow();expect(() => workspace.resolve('a\0b')).toThrow();});it('judges containment by real path so symlinks cannot borrow their way out', () => {const workspace = new ExecutorWorkspace({ workingDir: project });- fs.symlinkSync(outside, path.join(project, 'link'));+ fs.symlinkSync(outside, path.join(project, 'link'), process.platform === 'win32' ? 'junction' : 'dir');expect(workspace.contains(path.join(project, 'x.txt'))).toBe(true);expect(workspace.contains(path.join(project, 'link', 'x.txt'))).toBe(false);expect(workspace.contains(path.join(project, '..', 'outside'))).toBe(false);diff --git a/apps/desktop/src/main/remote-agent/executor/__tests__/virtualWorkspace.test.ts b/apps/desktop/src/main/remote-agent/executor/__tests__/virtualWorkspace.test.tsnew file mode 100644index 0000000000..9388c7e1ae--- /dev/null+++ b/apps/desktop/src/main/remote-agent/executor/__tests__/virtualWorkspace.test.ts@@ -0,0 +1,111 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { pathToFileURL } from 'node:url';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { mapExecServerParams, mapExecServerResult, execServerActions } from '../../controller/execServerRelay';+import { RemoteExecutor } from '../executor';+import { ExecutorGate } from '../gate';+import { ExecutorWorkspace, projectPathText } from '../workspace';+import { createReverseHttpRouter } from '../../controller/router';++let root: string;+beforeEach(() => { root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-virtual-workspace-'))); });+afterEach(() => { fs.rmSync(root, { recursive: true, force: true }); });++function setup(virtual: string) {+ const project = path.join(root, 'real project');+ fs.mkdirSync(project);+ const workspace = new ExecutorWorkspace({ workingDir: project, aliases: [{ from: virtual, to: project }] });+ workspace.setVirtualRoot(virtual);+ const gate = new ExecutorGate(workspace, 'normal');+ const executor = new RemoteExecutor({ workspace, gate, rgPath: 'unused' });+ return { project, workspace, executor, gate };+}++describe('virtual workspace', () => {+ it.each(['/Users/agent/workspace', '/home/agent/workspace', 'C:\\Agent\\workspace'])('round-trips paths from %s and keeps authorization on real paths', async (virtual) => {+ const { project, workspace, executor, gate } = setup(virtual);+ const api = virtual.startsWith('C:') ? path.win32 : path.posix;+ const target = api.join(virtual, 'made.txt');+ const written = await executor.callTool('Write', { file_path: target, content: 'literal ' + project });+ expect(JSON.stringify(written)).toContain(target.replace(/\\/g, '\\\\'));+ expect(fs.readFileSync(path.join(project, 'made.txt'), 'utf8')).toBe('literal ' + project);+ expect(workspace.resolve(target)).toBe(path.join(project, 'made.txt'));+ const read = await executor.callTool('Read', { file_path: target });+ // 文件内容不做路径替换,否则精确 Edit 将失去原始字符串。+ expect(read.content).toEqual([{ type: 'text', text: '1\tliteral ' + project }]);+ const edited = await executor.callTool('Edit', { file_path: target, old_string: project, new_string: 'updated' });+ expect(JSON.stringify(edited)).not.toContain(project.replace(/\\/g, '\\\\'));+ expect(fs.readFileSync(path.join(project, 'made.txt'), 'utf8')).toBe('literal updated');+ const outside = path.join(root, 'outside');+ const mapped = workspace.virtualizeDirs([outside])[0];+ expect(workspace.resolve(mapped)).toBe(outside);+ expect(gate.authorize({ kind: 'write', path: workspace.resolve(mapped) }).ok).toBe(false);+ await executor.close();+ });++ it('projects command paths with boundaries, Windows separators and Git Bash pwd', async () => {+ expect(projectPathText('cat C:\\virtual\\project\\src\\x.ts; C:\\virtual\\project2', [{ from: 'C:\\virtual\\project', to: '/real/project' }]))+ .toBe('cat /real/project/src/x.ts; C:\\virtual\\project2');+ expect(projectPathText('pwd /real/project/src /real/project2', [{ from: '/real/project', to: '/virtual/project' }]))+ .toBe('pwd /virtual/project/src /real/project2');+ const { workspace, project, executor } = setup('/Users/agent/workspace');+ expect(workspace.mapCommand('cd "/Users/agent/workspace"')).toContain(project.replace(/\\/g, '/'));+ expect(workspace.mapTextForAgent(project)).toBe('/Users/agent/workspace');+ if (process.platform === 'win32') {+ const bashPath = '/' + project[0].toLowerCase() + project.slice(2).replace(/\\/g, '/');+ expect(workspace.mapTextForAgent(bashPath)).toBe('/Users/agent/workspace');+ }+ const result = await executor.handle('exec.run', { command: 'pwd', cwd: '/Users/agent/workspace' }) as { output: string };+ expect(Buffer.from(result.output, 'base64').toString()).toContain('/Users/agent/workspace');+ const binary = Buffer.from([0xff, 0x00, 0x80, 0x41]);+ expect(workspace.mapOutputForAgent(binary)).toEqual(binary);+ await executor.close();+ });++ it('maps Codex request paths and commands before permission checks, without touching file bytes', async () => {+ const { workspace, project, executor } = setup('/Users/agent/workspace');+ const params = mapExecServerParams({ path: 'file:///Users/agent/workspace/a.txt', dataBase64: Buffer.from(project).toString('base64') }, workspace);+ expect(params).toEqual({ path: pathToFileURL(path.join(project, 'a.txt')).href, dataBase64: Buffer.from(project).toString('base64') });+ expect(execServerActions('fs/writeFile', params, project)).toEqual([{ kind: 'write', path: path.join(project, 'a.txt') }]);+ const result = mapExecServerResult({ result: { cwd: pathToFileURL(project).href } }, workspace);+ expect(JSON.stringify(result)).toContain('file:///Users/agent/workspace');+ const output = mapExecServerResult({ method: 'process/output', params: { chunk: Buffer.from(project).toString('base64') } }, workspace) as any;+ expect(Buffer.from(output.params.chunk, 'base64').toString()).toBe('/Users/agent/workspace');+ const fileData = { result: { dataBase64: Buffer.from(project).toString('base64') } };+ expect(mapExecServerResult(fileData, workspace)).toEqual(fileData);+ await executor.close();+ });++ it('projects Cindy MCP path arguments and JSON/SSE results while leaving file content arguments intact', async () => {+ const { workspace, project, executor } = setup('/Users/agent/workspace');+ let received: any;+ for (const sse of [false, true]) {+ const router = createReverseHttpRouter({+ executor,+ mcpTarget: () => ({ url: 'http://unused', headers: {} }),+ fetch: async (_url, options) => {+ received = JSON.parse(Buffer.from(options!.body as Uint8Array).toString());+ const result = { result: { content: [{ type: 'text', text: 'File: ' + path.join(project, 'a.txt') }] } };+ return new Response(sse ? 'data: ' + JSON.stringify(result) + '\n\n' : JSON.stringify(result), {+ headers: { 'content-type': sse ? 'text/event-stream' : 'application/json' },+ });+ },+ });+ const reply = await router({ method: 'POST', path: '/mcp/cindy_helper', headers: [], body: Buffer.from(JSON.stringify({+ method: 'tools/call', params: { name: 'file_tool', arguments: { path: '/Users/agent/workspace/a.txt', content: '/Users/agent/workspace' } },+ })).toString('base64') });+ expect(received.params.arguments.path).toBe(path.join(project, 'a.txt'));+ expect(received.params.arguments.content).toBe('/Users/agent/workspace');+ expect(reply.type).toBe('http');+ if (reply.type === 'http') {+ const body = Buffer.from(reply.body!, 'base64').toString();+ expect(body).toContain('/Users/agent/workspace/a.txt');+ expect(body).not.toContain(project.replace(/\\/g, '\\\\'));+ }+ }+ await executor.close();+ });+});diff --git a/apps/desktop/src/main/remote-agent/executor/executor.ts b/apps/desktop/src/main/remote-agent/executor/executor.tsindex da38853590..e3e81618a7 100644--- a/apps/desktop/src/main/remote-agent/executor/executor.ts+++ b/apps/desktop/src/main/remote-agent/executor/executor.ts@@ -208,7 +208,7 @@ export class RemoteExecutor {const cwd = this.resolvePath(str(body, '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) };+ return { paths: (await rawGlob(this.rg, str(body, 'pattern'), cwd, limit, signal)).map((item) => this.workspace.toAgentPath(item)) };}case 'fs.mime': {const target = this.resolvePath(str(body, 'path'));@@ -220,7 +220,8 @@ export class RemoteExecutor {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, scope: 'tree' });- return await piGrep(this.opts.rgPath, root, params, signal);+ const result = await piGrep(this.opts.rgPath, root, params, signal);+ return { ...result, text: this.workspace.mapTextForAgent(result.text) };}case 'exec.run': {const command = this.workspace.mapCommand(str(body, 'command'));@@ -233,7 +234,7 @@ export class RemoteExecutor {try {const result = await runOnce(command, { cwd, timeoutMs, signal });return {- output: result.output.toString('base64'),+ output: this.workspace.mapOutputForAgent(result.output).toString('base64'),exitCode: result.exitCode,...(result.timedOut ? { timedOut: true } : {}),...(result.aborted ? { aborted: true } : {}),@@ -247,13 +248,14 @@ export class RemoteExecutor {}} catch (error) {if (error instanceof ExecutorRequestError) throw error;- throw new ExecutorRequestError(errorCode(error), (error as Error)?.message ?? String(error));+ throw new ExecutorRequestError(errorCode(error), this.workspace.mapTextForAgent((error as Error)?.message ?? String(error)));}}// ─── Claude Code 风格工具 ──────────────────────────────────────async callTool(name: string, rawArgs: unknown, signal?: AbortSignal): Promise<ToolResult> {+ this.workspace.virtualizeDirs([this.shell.getTempDir()]);if (this.closed) return textResult('The task has ended on the computer where it runs.', true);let args: Record<string, unknown>;try {@@ -269,13 +271,13 @@ export class RemoteExecutor {const id = optionalString(args, 'bash_id') ?? optionalString(args, 'task_id') ?? optionalString(args, 'shell_id');if (!id) return textResult('bash_id is required.', true);const result = await this.shell.readBackground(id, optionalString(args, 'filter'));- return textResult(result.text, result.isError);+ return textResult(this.workspace.mapTextForAgent(result.text), result.isError);}case 'KillShell': {const id = optionalString(args, 'shell_id') ?? optionalString(args, 'task_id') ?? optionalString(args, 'bash_id');if (!id) return textResult('shell_id is required.', true);const result = this.shell.killBackground(id);- return textResult(result.text, result.isError);+ return textResult(this.workspace.mapTextForAgent(result.text), result.isError);}case 'Read': {const target = this.resolvePath(str(args, 'file_path'), this.shell.getCwd());@@ -285,14 +287,14 @@ export class RemoteExecutor {offset: optionalNumber(args, 'offset'),limit: optionalNumber(args, 'limit'),pages: optionalString(args, 'pages'),- }, this.readState, this.workspace.workingDir, this.opts.extractPdfText);+ }, this.readState, this.workspace.toAgentPath(this.workspace.workingDir), this.opts.extractPdfText, this.workspace.toAgentPath(target));}case 'Write': {const target = this.resolvePath(str(args, 'file_path'), this.shell.getCwd());const content = args.content;if (typeof content !== 'string') return textResult('content must be a string.', true);this.authorizeTool({ kind: 'write', path: target });- return await ccWrite(target, content, this.readState, this.writeHooks);+ return await ccWrite(target, content, this.readState, this.writeHooks, this.workspace.toAgentPath(target));}case 'Edit': {const target = this.resolvePath(str(args, 'file_path'), this.shell.getCwd());@@ -304,7 +306,7 @@ export class RemoteExecutor {old_string: args.old_string,new_string: args.new_string,replace_all: args.replace_all === true,- }, this.readState, this.writeHooks);+ }, this.readState, this.writeHooks, this.workspace.toAgentPath(target));}case 'NotebookEdit': {const target = this.resolvePath(str(args, 'notebook_path'), this.shell.getCwd());@@ -324,11 +326,11 @@ export class RemoteExecutor {return textResult(`Unknown tool: ${name}`, true);}} catch (error) {- if (error instanceof ExecutorDenied) return textResult(error.message, true);- if (error instanceof ExecutorRequestError) return textResult(error.message, true);+ if (error instanceof ExecutorDenied) return textResult(this.workspace.mapTextForAgent(error.message), true);+ if (error instanceof ExecutorRequestError) return textResult(this.workspace.mapTextForAgent(error.message), true);const code = (error as NodeJS.ErrnoException)?.code;- if (code === 'EACCES' || code === 'EPERM') return textResult(`Permission denied: ${(error as Error).message}`, true);- return textResult((error as Error)?.message ?? String(error), true);+ if (code === 'EACCES' || code === 'EPERM') return textResult(this.workspace.mapTextForAgent(`Permission denied: ${(error as Error).message}`), true);+ return textResult(this.workspace.mapTextForAgent((error as Error)?.message ?? String(error)), true);}}@@ -347,7 +349,7 @@ export class RemoteExecutor {const result = args.run_in_background === true? await this.shell.startBackground(command): await this.shell.run(command, timeout, signal);- return textResult(result.text, result.isError);+ return textResult(this.workspace.mapTextForAgent(result.text), result.isError);} finally {this.opts.capture?.noteOpaqueWrite();}@@ -367,7 +369,7 @@ export function executorCcToolDefinitions(platform: NodeJS.Platform = process.pldescription: string;inputSchema: Record<string, unknown>;}> {- const where = 'on the user\'s computer, where the project lives';+ const where = 'in the current workspace';const shellNote = platform === 'win32'? 'Commands run in Git Bash when available, otherwise cmd.exe.': `Commands run with ${path.basename(process.env.SHELL || 'bash')}.`;diff --git a/apps/desktop/src/main/remote-agent/executor/files.ts b/apps/desktop/src/main/remote-agent/executor/files.tsindex 2a56ca2bc6..56fbeb87e1 100644--- a/apps/desktop/src/main/remote-agent/executor/files.ts+++ b/apps/desktop/src/main/remote-agent/executor/files.ts@@ -257,6 +257,7 @@ async function readPdfText(absPath: string,pages: string | undefined,extract: PdfTextExtractor | undefined,+ displayPath = absPath,): Promise<ToolResult> {if (!extract) {return textResult('Reading PDF files is not available here. Extract the text with Bash (for example pdftotext) instead.', true);@@ -281,7 +282,7 @@ async function readPdfText(return [`--- Page ${match[1]} ---\n${section.slice(match[0].length)}`];});const notes = [- `PDF ${absPath}: ${extracted.numPages} page(s). Text of pages ${range.first}-${lastRead} follows; images, layout and scanned pages are not included.`,+ `PDF ${displayPath}: ${extracted.numPages} page(s). Text of pages ${range.first}-${lastRead} follows; images, layout and scanned pages are not included.`,];if (!requested && extracted.numPages > lastRead) {notes.push(`Use the pages parameter (for example "${lastRead + 1}-${Math.min(extracted.numPages, lastRead + CC_PDF_MAX_PAGES_PER_READ)}") to read more.`);@@ -297,13 +298,14 @@ export async function ccRead(readState: ReadStateTracker,cwd: string,extractPdfText?: PdfTextExtractor,+ displayPath = absPath,): Promise<ToolResult> {const stat = await statOrNull(absPath);if (!stat) {return textResult(`File does not exist. Note: your current working directory is ${cwd}.`, true);}if (stat.isDirectory()) {- return textResult(`EISDIR: illegal operation on a directory, read '${absPath}'. Use Bash with ls to list a directory.`, true);+ return textResult(`EISDIR: illegal operation on a directory, read '${displayPath}'. Use Bash with ls to list a directory.`, true);}const ext = path.extname(absPath).toLowerCase();if (IMAGE_MIME[ext] || CONVERTIBLE_IMAGE_EXTENSIONS.has(ext)) {@@ -313,7 +315,7 @@ export async function ccRead(}if (ext === '.pdf') {if (stat.size > CC_PDF_MAX_BYTES) return textResult(`PDF is too large to read (${stat.size} bytes).`, true);- const result = await readPdfText(absPath, input.pages, extractPdfText);+ const result = await readPdfText(absPath, input.pages, extractPdfText, displayPath);if (!result.isError) readState.record(absPath, stat.mtimeMs);return result;}@@ -446,9 +448,10 @@ export async function ccWrite(content: string,readState: ReadStateTracker,hooks: FileWriteHooks,+ displayPath = absPath,): Promise<ToolResult> {const stat = await statOrNull(absPath);- if (stat?.isDirectory()) return textResult(`EISDIR: illegal operation on a directory, write '${absPath}'`, true);+ if (stat?.isDirectory()) return textResult(`EISDIR: illegal operation on a directory, write '${displayPath}'`, true);if (stat) {const problem = await readState.check(absPath);if (problem) return textResult(problem, true);@@ -458,7 +461,7 @@ export async function ccWrite(await fsp.writeFile(absPath, content, 'utf8');const after = await fsp.stat(absPath);readState.record(absPath, after.mtimeMs);- return textResult(stat ? `The file ${absPath} has been updated successfully.` : `File created successfully at: ${absPath}`);+ return textResult(stat ? `The file ${displayPath} has been updated successfully.` : `File created successfully at: ${displayPath}`);}export interface CcEditInput {@@ -482,20 +485,21 @@ export async function ccEdit(input: CcEditInput,readState: ReadStateTracker,hooks: FileWriteHooks,+ displayPath = absPath,): Promise<ToolResult> {const { old_string: oldString, new_string: newString } = input;if (oldString === newString) {return textResult('No changes to make: old_string and new_string are exactly the same.', true);}const stat = await statOrNull(absPath);- if (stat?.isDirectory()) return textResult(`EISDIR: illegal operation on a directory, edit '${absPath}'`, true);+ if (stat?.isDirectory()) return textResult(`EISDIR: illegal operation on a directory, edit '${displayPath}'`, true);if (!stat) {- if (oldString !== '') return textResult(`File does not exist: ${absPath}`, true);+ if (oldString !== '') return textResult(`File does not exist: ${displayPath}`, true);await hooks.beforeWrite(absPath);await fsp.mkdir(path.dirname(absPath), { recursive: true });await fsp.writeFile(absPath, newString, 'utf8');readState.record(absPath, (await fsp.stat(absPath)).mtimeMs);- return textResult(`File created successfully at: ${absPath}`);+ return textResult(`File created successfully at: ${displayPath}`);}const problem = await readState.check(absPath);if (problem) return textResult(problem, true);@@ -505,7 +509,7 @@ export async function ccEdit(await hooks.beforeWrite(absPath);await fsp.writeFile(absPath, newString, 'utf8');readState.record(absPath, (await fsp.stat(absPath)).mtimeMs);- return textResult(`The file ${absPath} has been updated successfully.`);+ return textResult(`The file ${displayPath} has been updated successfully.`);}// 文件用 CRLF 时按 LF 匹配,写回时恢复原换行风格。const crlf = original.includes('\r\n');@@ -526,7 +530,7 @@ export async function ccEdit(await hooks.beforeWrite(absPath);await fsp.writeFile(absPath, crlf ? updated.replace(/\n/g, '\r\n') : updated, 'utf8');readState.record(absPath, (await fsp.stat(absPath)).mtimeMs);- return textResult(`The file ${absPath} has been updated successfully.`);+ return textResult(`The file ${displayPath} has been updated successfully.`);}export interface CcNotebookEditInput {diff --git a/apps/desktop/src/main/remote-agent/executor/shell.ts b/apps/desktop/src/main/remote-agent/executor/shell.tsindex 5726b13380..adf24a7117 100644--- a/apps/desktop/src/main/remote-agent/executor/shell.ts+++ b/apps/desktop/src/main/remote-agent/executor/shell.ts@@ -296,6 +296,14 @@ export interface ShellSessionOptions {tempDir?: string;}+/** Git Bash 的 pwd 使用 MSYS 挂载路径,权限与后续文件工具必须回到 Windows 本机路径。 */+export function normalizeShellCwd(cwd: string): string {+ if (process.platform !== 'win32') return cwd;+ if (/^\/tmp(?:\/|$)/.test(cwd)) return path.join(os.tmpdir(), cwd.slice(4));+ const drive = /^\/([A-Za-z])(?:\/|$)/.exec(cwd);+ return drive ? path.win32.normalize(drive[1].toUpperCase() + ':/' + cwd.slice(drive[0].length)) : cwd;+}+export class ShellSession {private cwd: string;private readonly jobs = new Map<string, BackgroundJob>();@@ -311,6 +319,10 @@ export class ShellSession {return this.cwd;}+ getTempDir(): string {+ return this.tempDir;+ }+/** 执行一条命令;命令结束后记下它所在的目录,下一条命令从那里开始。 */async run(command: string, timeoutMs: number | undefined, signal?: AbortSignal): Promise<ShellCommandResult> {if (this.closed) return { text: 'The shell session has ended.', isError: true };@@ -334,7 +346,7 @@ export class ShellSession {}let resetNote = '';try {- const next = (await fsp.readFile(cwdFile, 'utf8')).trim();+ const next = normalizeShellCwd((await fsp.readFile(cwdFile, 'utf8')).trim());if (next) {if (this.opts.isAllowedCwd(next)) this.cwd = next;else {diff --git a/apps/desktop/src/main/remote-agent/executor/workspace.ts b/apps/desktop/src/main/remote-agent/executor/workspace.tsindex 9944050a0a..d63164c1a5 100644--- a/apps/desktop/src/main/remote-agent/executor/workspace.ts+++ b/apps/desktop/src/main/remote-agent/executor/workspace.ts@@ -7,6 +7,7 @@* 本机项目里。*/import fs from 'node:fs';+import os from 'node:os';import path from 'node:path';import { isSensitiveCredentialPath } from '@cindy/maker-core';@@ -61,16 +62,37 @@ function stripAliasPrefix(input: string, from: string): string | null {const normalizedInput = input.replace(/\\/g, '/');const normalizedFrom = from.replace(/\\/g, '/').replace(/\/+$/, '');if (!normalizedFrom) return null;- if (normalizedInput === normalizedFrom) return '';- if (normalizedInput.startsWith(`${normalizedFrom}/`)) return normalizedInput.slice(normalizedFrom.length + 1);+ const windows = /^[A-Za-z]:|^\/\//.test(normalizedFrom);+ const comparedInput = windows ? normalizedInput.toLowerCase() : normalizedInput;+ const comparedFrom = windows ? normalizedFrom.toLowerCase() : normalizedFrom;+ if (comparedInput === comparedFrom) return '';+ if (comparedInput.startsWith(`${comparedFrom}/`)) return normalizedInput.slice(normalizedFrom.length + 1);return null;}+/** 对已知目录做单次双向投影,最长前缀先匹配,防止替换结果再次被短祖先别名改写。 */+export function projectPathText(text: string, aliases: readonly ExecutorPathAlias[]): string {+ const entries = aliases.filter((alias) => alias.from.replace(/[\\/]+$/, '').length > 2)+ .sort((a, b) => b.from.length - a.from.length);+ if (!entries.length) return text;+ const patterns = entries.map((alias) => alias.from.replace(/[\\/]+$/, '').split(/[\\/]/)+ .map((part) => part.replace(/[.*+?^$()|[\]{}]/g, '\\$&')).join('[/\\\\]'));+ // 左右都要求边界,避免修改 longer/project2 或文本里的同前缀标识符。+ const pattern = new RegExp('(^|[\\s\'"=([{:,>+])(' + patterns.join('|') + ')(?=$|[/\\\\\\s\'";:|&)<>.,}\\]])([/\\\\][^\\s\'";:|&)<>]*|)', 'gi');+ return text.replace(pattern, (match: string, left: string, prefix: string, suffix: string) => {+ const alias = entries.find((entry) => stripAliasPrefix(prefix, entry.from) === '');+ if (!alias) return match;+ const separator = alias.to.includes('\\') ? '\\' : '/';+ return left + alias.to.replace(/[\\/]+$/, '') + suffix.replace(/[\\/]/g, separator);+ });+}+export class ExecutorWorkspace {readonly workingDir: string;private roots: string[];private extraDirs: string[];private aliases: ExecutorPathAlias[];+ private virtualRoot?: string;constructor(roots: ExecutorWorkspaceRoots) {if (!path.isAbsolute(roots.workingDir)) throw new ExecutorPathError('working directory must be absolute');@@ -84,7 +106,26 @@ export class ExecutorWorkspace {/** Agent 启动后才知道它那边的影子目录,届时设置。 */setAliases(aliases: readonly ExecutorPathAlias[]): void {- this.aliases = aliases.filter((alias) => alias.from && path.isAbsolute(alias.to));+ this.aliases = aliases.filter((alias) => alias.from && path.isAbsolute(alias.to))+ .sort((a, b) => b.from.length - a.from.length);+ }++ setVirtualRoot(root?: string): void {+ this.virtualRoot = root;+ }++ /** 运行中新增的目录分配新的 opaque 别名,撤销授权不撤销路径身份。 */+ virtualizeDirs(dirs: readonly string[]): string[] {+ if (!this.virtualRoot) return [...dirs];+ const native = /^[A-Za-z]:|^\\\\/.test(this.virtualRoot) ? path.win32 : path.posix;+ return dirs.map((dir) => {+ const real = this.resolve(dir);+ const exact = this.aliases.find((alias) => path.resolve(alias.to) === real);+ if (exact) return exact.from;+ const virtual = native.join(this.virtualRoot!, 'additional', 'runtime-' + this.aliases.length);+ this.setAliases([...this.aliases, { from: virtual, to: real }]);+ return virtual;+ });}/** 任务运行中附加目录变化时更新。 */@@ -107,17 +148,52 @@ export class ExecutorWorkspace {return input;}+ /** 本机真实路径投影到 Agent 主机上的路径;仅匹配完整路径段。 */+ toAgentPath(input: string): string {+ if (!this.virtualRoot) return input;+ const aliases = [...this.aliases].sort((a, b) => b.to.length - a.to.length);+ for (const alias of aliases) {+ const rest = stripAliasPrefix(input, alias.to);+ if (rest === null) continue;+ const native = /^[A-Za-z]:|^\\\\/.test(alias.from) ? path.win32 : path.posix;+ return rest ? native.join(alias.from, ...rest.split('/')) : alias.from;+ }+ return input;+ }++ /** 工具的命令输出/诊断使用虚拟路径,文件内容与读写字节不经过文本替换。 */+ mapTextForAgent(text: string): string {+ if (!this.virtualRoot) return text;+ const aliases = this.aliases.flatMap((alias) => {+ const real = alias.to.replace(/\\/g, '/');+ const entries = [{ from: real, to: alias.from }];+ // Git Bash / MSYS 的 pwd 和诊断使用 /c/...,而 Node 返回 C:\...。+ if (/^[A-Za-z]:\//.test(real)) entries.push({ from: '/' + real[0].toLowerCase() + real.slice(2), to: alias.from });+ if (process.platform === 'win32') {+ const temporary = os.tmpdir().replace(/\\/g, '/').replace(/\/+$/, '');+ const relative = stripAliasPrefix(real, temporary);+ if (relative !== null) entries.push({ from: '/tmp' + (relative ? '/' + relative : ''), to: alias.from });+ }+ return entries;+ });+ return projectPathText(text, aliases);+ }++ mapOutputForAgent(data: Buffer): Buffer {+ const text = data.toString('utf8');+ // 二进制 stdout 不做 UTF-8 往返,避免 exec.run / process/output 改变原始字节。+ if (!Buffer.from(text, 'utf8').equals(data)) return data;+ const projected = this.mapTextForAgent(text);+ return projected === text ? data : Buffer.from(projected, 'utf8');+ }+/** 命令文本里出现的影子目录前缀替换成本机目录(按完整路径段)。 */mapCommand(command: string): string {- let next = command;- for (const alias of this.aliases) {- const from = alias.from.replace(/\/+$/, '');- if (!from) continue;- // 只在后面是路径边界时替换,避免误伤更长的同前缀路径。- const pattern = new RegExp(`${from.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?=$|[/\\s'"\`;:|&)<>])`, 'g');- next = next.replace(pattern, () => alias.to);- }- return next;+ // Windows 上的 Bash 使用正斜杠,避免未引用的反斜杠被 shell 当成转义。+ return projectPathText(command, this.aliases.map((alias) => ({+ from: alias.from,+ to: process.platform === 'win32' ? alias.to.replace(/\\/g, '/') : alias.to,+ })));}/** 把 Agent 给的路径解析成本机绝对路径(相对路径以 baseDir / 工作目录为基准)。 */diff --git a/apps/desktop/src/main/remote-agent/host/runHost.ts b/apps/desktop/src/main/remote-agent/host/runHost.tsindex 042443569c..5aae8147be 100644--- a/apps/desktop/src/main/remote-agent/host/runHost.ts+++ b/apps/desktop/src/main/remote-agent/host/runHost.ts@@ -43,6 +43,7 @@ import {import type { AgentSessionHandle, InteractionRequest } from '@cindy/maker-core';import { EventLog, waitForAny } from '../eventLog';+import { projectPathText } from '../executor/workspace';import {MAX_ANCESTOR_LEVELS,decodeOpenPayload,@@ -75,8 +76,13 @@ export interface HostedStartInput {hostSessionId: string;/** 影子目录:只放项目说明类文件,作为 Agent 进程的工作目录。 */shadowDir: string;- /** 影子目录按控制端真实路径逐级镜像的根(上级目录里的说明文件放在对应的上级)。 */+ /** Agent 主机上的 opaque 虚拟工作区根。 */mirrorRoot: string;+ /** 虚拟附加目录,与 workspace.extraDirs 按顺序对应。 */+ extraDirs?: string[];+ /** 虚拟可写目录,与 workspace.writableDirs 按顺序对应。 */+ writableDirs?: string[];+ virtualWorkspace?: boolean;/** 控制端的个人说明(写进给 Agent 的环境说明)。 */personalInstructions?: string;options: RemoteAgentWireStartOptions;@@ -140,6 +146,7 @@ interface Run {attachmentsDir: string;/** 影子工作区根(按 hostSessionId 复用,任务收尾后清理)。 */workspaceDir?: string;+ virtualRoot?: string;pending: Map<string, PendingReverse>;calls: Map<string, 'running' | 'done'>;pushSeq: Set<number>;@@ -244,7 +251,7 @@ export function snapshotHandleState(handle: AgentSessionHandle): Record<string,}/** 启动结果里给控制端的会话描述(静态部分 + 支持哪些可选方法)。 */-function describeHandle(handle: AgentSessionHandle, shadowDir: string, mirrorRoot: string): Record<string, unknown> {+function describeHandle(handle: AgentSessionHandle, shadowDir: string, mirrorRoot: string, extraDirs: readonly string[], writableDirs: readonly string[], virtualWorkspace: boolean): Record<string, unknown> {const methods = REMOTE_AGENT_METHODS.filter((method) => typeof (handle as unknown as Record<string, unknown>)[method] === 'function');return {id: handle.id,@@ -252,6 +259,9 @@ function describeHandle(handle: AgentSessionHandle, shadowDir: string, mirrorRoomodel: handle.model,shadowDir,mirrorRoot,+ extraDirs,+ writableDirs,+ virtualWorkspace,methods,...(handle.requestSessionId ? { requestSessionId: handle.requestSessionId } : {}),...(handle.codexProxyActive !== undefined ? { codexProxyActive: handle.codexProxyActive } : {}),@@ -435,13 +445,62 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {controller: string,payload: RemoteAgentOpenPayload,hostSessionId: string,- ): Promise<{ shadowDir: string; mirrorRoot: string; sessionRoot: string }> {+ ): Promise<{ shadowDir: string; mirrorRoot: string; sessionRoot: string; extraDirs: string[]; writableDirs: string[]; projectText(text: string): string }> {const sessionRoot = shadowSessionRoot(controller, hostSessionId);const mirrorRoot = path.join(sessionRoot, 'fs');- const segments = mirrorSegments(payload.workspace.workingDir);+ // 固定短层级承载最多 MAX_ANCESTOR_LEVELS 个上级说明文件,不带控制端目录名。+ const segments = payload.virtualWorkspace+ ? ['workspace', ...Array.from({ length: MAX_ANCESTOR_LEVELS }, () => 'p')]+ : mirrorSegments(payload.workspace.workingDir);const shadowDir = path.join(mirrorRoot, ...segments);await fsp.rm(sessionRoot, { recursive: true, force: true });await fsp.mkdir(shadowDir, { recursive: true });+ if (payload.virtualWorkspace) await Promise.all(['home', 'tmp'].map((name) => fsp.mkdir(path.join(mirrorRoot, name), { recursive: true })));+ const foreignPath = payload.workspace.platform === 'win32' ? path.win32 : path.posix;+ const realWorkspace = foreignPath.resolve(payload.workspace.workingDir);+ const virtualByReal = new Map<string, string>();+ const virtualFor = (raw: string, index: number): string => {+ const resolved = foreignPath.resolve(raw);+ const key = payload.workspace.platform === 'win32' ? resolved.toLowerCase() : resolved;+ const existing = virtualByReal.get(key);+ if (existing) return existing;+ const relative = foreignPath.relative(realWorkspace, resolved);+ const insideWorkspace = relative === '' || (!relative.startsWith('..') && !foreignPath.isAbsolute(relative));+ const virtual = insideWorkspace+ ? path.join(shadowDir, ...relative.split(/[\\/]+/).filter(Boolean))+ : path.join(mirrorRoot, 'additional', 'dir-' + index);+ virtualByReal.set(key, virtual);+ return virtual;+ };+ const virtualAll = [...payload.workspace.extraDirs, ...payload.workspace.writableDirs]+ .map((dir, index) => payload.virtualWorkspace ? virtualFor(dir, index) : dir);+ if (payload.virtualWorkspace) await Promise.all([...new Set(virtualAll)].map((dir) => fsp.mkdir(dir, { recursive: true })));+ const extraCount = payload.workspace.extraDirs.length;+ const pathAliases = [{ from: payload.workspace.workingDir, to: shadowDir }];+ if (payload.virtualWorkspace && payload.workspace.homeDir) {+ pathAliases.push({ from: payload.workspace.homeDir, to: path.join(mirrorRoot, 'home') });+ }+ let realParent = payload.workspace.workingDir;+ let virtualParent = shadowDir;+ for (let up = 1; up <= MAX_ANCESTOR_LEVELS; up += 1) {+ const nextReal = foreignPath.dirname(realParent);+ if (nextReal === realParent) break;+ realParent = nextReal;+ virtualParent = path.dirname(virtualParent);+ pathAliases.push({ from: realParent, to: virtualParent });+ }+ [...payload.workspace.extraDirs, ...payload.workspace.writableDirs].forEach((from, index) => {+ pathAliases.push({ from, to: virtualAll[index] });+ });+ const projectText = (text: string) => payload.virtualWorkspace ? projectPathText(text, pathAliases) : text;+ const projectBytes = (data: Buffer): Buffer => {+ // Skill 目录允许随包携带非文本资源;只投影有效的文本字节,避免 UTF-8 转换损坏二进制。+ if (!payload.virtualWorkspace || data.includes(0)) return data;+ const text = data.toString('utf8');+ if (!Buffer.from(text, 'utf8').equals(data)) return data;+ const projected = projectText(text);+ return projected === text ? data : Buffer.from(projected, 'utf8');+ };const inside = (target: string, root: string) => target.startsWith(`${root}${path.sep}`);const writeNew = async (target: string, data: Buffer) => {await fsp.mkdir(path.dirname(target), { recursive: true });@@ -453,32 +512,32 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {const target = path.join(shadowDir, ...file.path.split('/'));if (!inside(target, shadowDir)) continue;await fsp.mkdir(path.dirname(target), { recursive: true });- await fsp.writeFile(target, Buffer.from(file.data, 'base64'));+ await fsp.writeFile(target, projectBytes(Buffer.from(file.data, 'base64')));}for (const file of payload.ancestorFiles) {if (file.up > segments.length - 1) continue;let dir = shadowDir;for (let level = 0; level < file.up; level += 1) dir = path.dirname(dir);if (!inside(dir, mirrorRoot)) continue;- await writeNew(path.join(dir, file.name), Buffer.from(file.data, 'base64'));+ await writeNew(path.join(dir, file.name), projectBytes(Buffer.from(file.data, 'base64')));}const { personal } = payload;- if (personal.memory) await writeNew(path.join(sessionRoot, 'CLAUDE.md'), Buffer.from(personal.memory, 'utf8'));+ if (personal.memory) await writeNew(path.join(sessionRoot, 'CLAUDE.md'), Buffer.from(projectText(personal.memory), 'utf8'));// 项目里已有同名文件时以项目为准(只写不存在的)。for (const file of personal.files) {const target = path.join(shadowDir, ...file.path.split('/'));if (!inside(target, shadowDir)) continue;- await writeNew(target, Buffer.from(file.data, 'base64'));+ await writeNew(target, projectBytes(Buffer.from(file.data, 'base64')));}- if (personal.permissions) await mergeLocalPermissions(path.join(shadowDir, '.claude', 'settings.local.json'), personal.permissions);- return { shadowDir, mirrorRoot, sessionRoot };+ if (personal.permissions) await mergeLocalPermissions(path.join(shadowDir, '.claude', 'settings.local.json'), Object.fromEntries(Object.entries(personal.permissions).map(([key, rules]) => [key, rules?.map(projectText)])));+ return { shadowDir, mirrorRoot, sessionRoot, extraDirs: virtualAll.slice(0, extraCount), writableDirs: virtualAll.slice(extraCount), projectText };}async function startRun(run: Run, payload: RemoteAgentOpenPayload): Promise<void> {try {const hostSessionId = hostSessionIdFor(run.controller, payload.sessionId);run.hostSessionId = hostSessionId;- const { shadowDir, mirrorRoot, sessionRoot } = await withShadowLock(hostSessionId, async () => {+ const { shadowDir, mirrorRoot, sessionRoot, extraDirs, writableDirs, projectText } = await withShadowLock(hostSessionId, async () => {// 断线后旧实例还没清理就重新打开同一任务时,新旧实例共用同一个影子目录:// 先结束旧实例再重建,避免删掉旧 Agent 还在使用的目录,或两个实例争用重建后的目录。for (const other of runs.values()) {@@ -489,6 +548,7 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {return prepareShadow(run.controller, payload, hostSessionId);});run.workspaceDir = sessionRoot;+ run.virtualRoot = payload.virtualWorkspace ? mirrorRoot : undefined;const tunnel = await createRunTunnel({http: (request, signal) => reverseHttp(run, request, signal),wsOpen: (connId, wsPath) => append(run, { t: 'ws', connId, kind: 'open', path: wsPath }),@@ -497,13 +557,20 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {});run.tunnel = tunnel;if (run.closing) return;+ // 必须先发布映射,再启动 Agent。Codex startSession 会在 started 之前读取 exec-server 环境。+ if (payload.virtualWorkspace) append(run, { t: 'state', state: {+ workspaceProjection: { shadowDir, mirrorRoot, extraDirs, writableDirs, virtualWorkspace: true },+ } });const handle = await deps.startHosted({kind: run.kind,hostSessionId,shadowDir,mirrorRoot,- ...(payload.personal.instructions ? { personalInstructions: payload.personal.instructions } : {}),- options: payload.options,+ extraDirs,+ writableDirs,+ virtualWorkspace: payload.virtualWorkspace === true,+ ...(payload.personal.instructions ? { personalInstructions: projectText(payload.personal.instructions) } : {}),+ options: Object.fromEntries(Object.entries(payload.options).map(([key, value]) => [key, typeof value === 'string' ? projectText(value) : value])) as unknown as RemoteAgentWireStartOptions,workspace: payload.workspace,tunnel: { url: tunnel.url, token: tunnel.token },mcpServers: payload.mcpServers,@@ -526,7 +593,7 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {if (reply.type === 'interaction') return reply.result as Awaited<ReturnType<Parameters<AgentSessionHandle['setInteractionResolver']>[0]>>;throw new Error(reply.type === 'error' ? reply.error.message : 'interaction failed');});- append(run, { t: 'started', handle: describeHandle(handle, shadowDir, mirrorRoot) });+ append(run, { t: 'started', handle: describeHandle(handle, shadowDir, mirrorRoot, extraDirs, writableDirs, payload.virtualWorkspace === true) });run.lastState = JSON.stringify(snapshotHandleState(handle));run.stateTimer = setInterval(() => emitState(run), STATE_INTERVAL_MS);(run.stateTimer as { unref?: () => void }).unref?.();@@ -623,6 +690,13 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {const target = (handle as unknown as Record<string, unknown>)[method];if (typeof target !== 'function') fail('REMOTE_AGENT_UNSUPPORTED', `${method} is not supported by this agent`);let callArgs: unknown[] = args;+ if (run.virtualRoot && (method === 'setExtraDirs' || method === 'setWritableDirs')) {+ const dirs = Array.isArray(args[0]) ? args[0] : [];+ await Promise.all(dirs.filter((dir): dir is string => typeof dir === 'string').map(async (dir) => {+ const relative = path.relative(run.virtualRoot!, dir);+ if (!relative.startsWith('..') && !path.isAbsolute(relative)) await fsp.mkdir(dir, { recursive: true });+ }));+ }// 供应商授权:新一轮对话前复核(关掉后不再开始新的一轮,进行中的这一轮照常结束);// 换模型时显式换来源(含 null = 默认)要落到开放的供应商上,只换模型则沿用当前来源。let nextProviderId: string | undefined;diff --git a/apps/desktop/src/main/remote-agent/host/service.ts b/apps/desktop/src/main/remote-agent/host/service.tsindex 98c46cd0a9..1a0e04d438 100644--- a/apps/desktop/src/main/remote-agent/host/service.ts+++ b/apps/desktop/src/main/remote-agent/host/service.ts@@ -46,10 +46,17 @@ export function hostedStartOptions(input: HostedStartInput): StartSessionOptions...(options.resumeSessionId ? { resumeSessionId: options.resumeSessionId } : {}),...(options.codexHistoryHasProductPrompt !== undefined ? { codexHistoryHasProductPrompt: options.codexHistoryHasProductPrompt } : {}),...(options.vendorOptions ? { vendorOptions: { ...options.vendorOptions } } : {}),- extraDirs: [...workspace.extraDirs],- writableDirs: [...workspace.writableDirs],+ extraDirs: [...(input.extraDirs ?? workspace.extraDirs)],+ writableDirs: [...(input.writableDirs ?? workspace.writableDirs)],deviceHosted: {...workspace,+ workingDir: input.virtualWorkspace ? input.shadowDir : workspace.workingDir,+ // 旧协议把控制端真实路径直接交给 Agent;只有虚拟工作区才采用 Agent 主机的路径风格。+ pathPlatform: input.virtualWorkspace ? process.platform : workspace.platform,+ extraDirs: [...(input.extraDirs ?? workspace.extraDirs)],+ writableDirs: [...(input.writableDirs ?? workspace.writableDirs)],+ // HOME 属于 Agent 主机;不能把控制端的个人目录带入 Agent 上下文。+ homeDir: undefined,tunnelUrl: input.tunnel.url,tunnelToken: input.tunnel.token,mcpServers: [...input.mcpServers],diff --git a/apps/desktop/src/main/remote-agent/wire.ts b/apps/desktop/src/main/remote-agent/wire.tsindex 3fd3b87be1..90c23c5fb1 100644--- a/apps/desktop/src/main/remote-agent/wire.ts+++ b/apps/desktop/src/main/remote-agent/wire.ts@@ -139,6 +139,8 @@ export interface RemoteAgentWirePersonal {export interface RemoteAgentOpenPayload {/** 控制端任务 id。 */sessionId: string;+ /** 可选增量能力:Agent 使用本机虚拟工作区,旧控制端不传时沿用原路径合同。 */+ virtualWorkspace?: boolean;options: RemoteAgentWireStartOptions;workspace: RemoteAgentWireWorkspace;projectFiles: RemoteAgentWireFile[];@@ -263,6 +265,7 @@ export function decodeOpenPayload(value: unknown): RemoteAgentOpenPayload {});return {sessionId,+ ...(value.virtualWorkspace === true ? { virtualWorkspace: true } : {}),options: decodeStartOptions(value.options),workspace: decodeWorkspace(value.workspace),projectFiles,diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 1993a8697c..142ca4c1a9 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -466,6 +466,13 @@ handler 无 sender 依赖;不加入共享任务访客白名单,不进入自里的权限规则;Codex 的 `AGENTS(.override).md`;不含 hooks / env)。两者缺省按空处理。B 把影子目录按A 的真实路径逐级镜像在 `<runs>/workspaces/<控制端>/<任务>/fs/` 下,`open` 回包的 `mirrorRoot` 告诉 A镜像根,A 据此把影子路径逐级映射回真实路径;项目里已有的同名文件以项目为准。+- **本机虚拟工作区**:新版 A 的 open 载荷携带可选 virtualWorkspace: true,新版 B 回包回显+ virtualWorkspace、extraDirs、writableDirs。双方支持时,B 使用不含 A 真实目录名的固定短父级+ 层级,继续承载最多 24 级祖先说明文件。Agent prompt、文件引用、工具路径诊断与命令输出使用+ B 本机虚拟路径;文件读写字节保持原样。A 的真实目录继续用于权限 gate、执行与变更抓取,路径+ 别名不增加授权。执行平台与 shell 保留 A 的实际值,以免跨 macOS / Windows / Linux 选错命令。+ 旧 A 不传字段,新 B 沿用原镜像合同;旧 B 忽略字段且不回显,新 A 保留原合同,不投影返回值。+ 此增量不修改 channel、relay、协议版本或服务器,也不是 OS 虚拟化。- **回退**:`REMOTE_AGENT_METHODS` 含 `previewRewindFiles` / `commitRewindFiles`,B 在 `describeHandle`里声明支持后 A 才提供回退;文件按 A 本机的保存点链回退,对话由 B 截断。B 不支持时 A 关闭回退并提示升级那台的 Cindy。diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex 33731c6e96..7ff4b8f00c 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -1734,12 +1734,14 @@ export class TurnDispatchRejectedError extends Error {/** 设备托管会话的描述(见 StartSessionOptions.deviceHosted)。 */export interface DeviceHostedSession {- /** 任务所在电脑上的真实工作目录:模型看到的、工具使用的都是这个路径。 */+ /** Agent 主机上的虚拟工作目录,执行器映射到任务真实目录;旧协议兼容真实路径。 */workingDir: string;extraDirs: string[];writableDirs: string[];/** 任务所在电脑的平台与 shell(写进给模型的环境说明)。 */platform: NodeJS.Platform;+ /** 虚拟工作区路径采用 Agent 进程所在主机的路径风格;缺省按当前进程判断。 */+ pathPlatform?: NodeJS.Platform;shell: string;osVersion?: string;homeDir?: string;@@ -1750,8 +1752,7 @@ export interface DeviceHostedSession {/** 经隧道可用的 Cindy MCP 服务名(`<tunnelUrl>/mcp/<name>`)。 */mcpServers: string[];/**- * 本机影子目录按任务所在电脑的真实路径逐级镜像时的镜像根:其下每一级目录都对应那台电脑上的- * 同一级目录(上级目录里的项目说明放在对应位置,Agent 照常向上加载)。+ * 本机虚拟工作区根:父目录层级对应执行端的上级说明文件,Agent 照常向上加载。*/mirrorRoot?: string;/** 任务所在电脑上用户的个人说明(该 Agent 的用户级说明文件),写进给模型的环境说明。 */diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex 6b7362f179..8142e255f3 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -2677,7 +2677,8 @@ export class ClaudeCodeAgent extends BaseAgent {// 设备托管:cindy_exec 工具按对应的自带工具名走同一套权限判断(确认卡、会话规则、自动审查、// IM 等每轮策略看到的都是 Bash / Read 等原名);本机任务里 Claude Code 自己就免确认的操作// (工作区内读取、静态可证只读的命令、自动接受编辑档下的工作区写入)这里同样免确认。- const hostedPath = hosted?.platform === 'win32' ? path.win32 : path.posix;+ // 工具参数是 Agent 主机上的虚拟路径;执行命令的语法仍按 hosted.platform 判断。+ const hostedPath = hosted?.pathPlatform === 'win32' ? path.win32 : path.posix;const hostedInside = (target: unknown, roots: readonly string[]): boolean => {if (!hosted || typeof target !== 'string' || !target) return false;const resolved = hostedPath.resolve(hosted.workingDir, target);diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.tsindex a50e50eb68..11e75ca5ce 100644--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts@@ -3854,25 +3854,11 @@ function registerCindyHostedTools(pi.on('before_agent_start', async (event: any) => {const hosted = CINDY_HOSTED!;const prompt = typeof event.systemPrompt === 'string' ? event.systemPrompt : '';- // 影子目录里的项目说明就是那台电脑上同一目录的副本,提示里一律换成真实目录。影子目录按真实- // 路径逐级镜像,上级目录(放着上级目录的说明文件)也逐级换回真实路径;先换最深的一级。- let replaced = prompt;- let shadow = process.cwd();- let real = hosted.cwd;- const realPath = hosted.platform === 'win32' ? path.win32 : path.posix;- for (let level = 0; level < 32; level += 1) {- replaced = replaced.split(shadow).join(real);- const nextShadow = path.dirname(shadow);- const nextReal = realPath.dirname(real);- if (!hosted.mirrorRoot || nextShadow === shadow || nextReal === real) break;- if (!nextShadow.startsWith(hosted.mirrorRoot + path.sep)) break;- shadow = nextShadow;- real = nextReal;- }+ const replaced = prompt;const note = ['',- '# Where this task runs',- 'The project lives on the user\'s computer at ' + hosted.cwd + ' (' + hosted.platform + ', shell: ' + hosted.shell + '). Every file and shell tool operates on that computer.',+ '# Workspace',+ 'The current workspace is ' + hosted.cwd + ' (' + hosted.platform + ', shell: ' + hosted.shell + '). File and shell tools operate in this workspace. Relative paths resolve against it.',].join('\n');return { systemPrompt: replaced + '\n' + note };});@@ -4313,7 +4299,7 @@ export default async function cindyBridge(pi: any) {// (那台电脑的执行器会按真实路径再守一道凭证与高危上限)。路径实现按那台电脑的平台// 选(path.win32 / path.posix),与提示改写一致 —— 用本机 path.resolve 解析异构平台// 路径(如 macOS 上解析 C:\project\file)会得到畸形路径,写证据与可写根对不上。- const hostedRealPath = CINDY_HOSTED ? (CINDY_HOSTED.platform === 'win32' ? path.win32 : path.posix) : null;+ const hostedRealPath = CINDY_HOSTED ? path : null;const writeTargetResolved = CINDY_HOSTED && hostedRealPath? (targetPath ? hostedRealPath.resolve(CINDY_HOSTED.cwd, targetPath) : null): resolveFileWriteTargetPath(targetPath);diff --git a/packages/maker-core/src/agents/shared/device-hosted.test.ts b/packages/maker-core/src/agents/shared/device-hosted.test.tsindex 1d5198d999..d850c108ad 100644--- a/packages/maker-core/src/agents/shared/device-hosted.test.ts+++ b/packages/maker-core/src/agents/shared/device-hosted.test.ts@@ -36,6 +36,13 @@ describe('deviceHostedPiEnvValue', () => {});describe('deviceHostedEnvironmentNote', () => {+ it('uses an agent-local workspace while preserving the execution platform and shell', () => {+ const note = deviceHostedEnvironmentNote(hosted({ workingDir: '/Users/agent/ws', platform: 'win32', shell: 'bash', extraDirs: ['/Users/agent/additional'] }), '/Users/agent/ws');+ expect(note).toContain('/Users/agent/ws');+ expect(note).toContain('win32, shell: bash');+ expect(note).not.toContain('computer');+ expect(note).not.toContain('only holds a copy');+ });it('has no personal section without personal instructions', () => {expect(deviceHostedEnvironmentNote(hosted(), '/shadow')).not.toContain('personal instructions');expect(deviceHostedEnvironmentNote(hosted({ personalInstructions: ' \n ' }), '/shadow'))@@ -44,7 +51,7 @@ describe('deviceHostedEnvironmentNote', () => {it("appends the user's personal instructions from their computer", () => {const note = deviceHostedEnvironmentNote(hosted({ personalInstructions: ' Always answer in Chinese.\n' }), '/shadow');- expect(note).toContain("# The user's personal instructions (from their computer)\nAlways answer in Chinese.");+ expect(note).toContain("# The user's personal instructions\nAlways answer in Chinese.");expect(note.indexOf('Is a git repository')).toBeLessThan(note.indexOf('personal instructions'));});});diff --git a/packages/maker-core/src/agents/shared/device-hosted.ts b/packages/maker-core/src/agents/shared/device-hosted.tsindex a1e831734a..fdb60c2be1 100644--- a/packages/maker-core/src/agents/shared/device-hosted.ts+++ b/packages/maker-core/src/agents/shared/device-hosted.ts@@ -4,7 +4,7 @@*/import type { DeviceHostedSession, PiExtraSpawnConfig } from '../base-agent.js';-/** 交给 Pi 内 cindy-bridge 的托管配置(隧道地址、令牌、真实工作目录)。 */+/** 交给 Pi 内 cindy-bridge 的托管配置(隧道地址、令牌、Agent 主机上的工作目录)。 */export const DEVICE_HOSTED_PI_ENV = 'CINDY_PI_HOSTED';/**@@ -66,21 +66,20 @@ export function deviceHostedExecToolName(builtin: string): string {}/**- * 给模型的环境说明:项目在哪台电脑、哪个目录,工具在哪执行。只陈述事实,让模型使用真实路径。+ * 给模型的环境说明:模型只看到 Agent 主机上的虚拟工作区路径;执行端平台与 shell 保留真实值。*/-export function deviceHostedEnvironmentNote(hosted: DeviceHostedSession, localWorkingDir: string): string {+export function deviceHostedEnvironmentNote(hosted: DeviceHostedSession, _localWorkingDir: string): string {const lines = [- '# Where this task runs',- `The project lives on the user's computer at \`${hosted.workingDir}\` (${hosted.platform}, shell: ${hosted.shell}${hosted.osVersion ? `, ${hosted.osVersion}` : ''}).`,- `Every file and shell tool operates on that computer. Use paths under \`${hosted.workingDir}\`; relative paths resolve against it.`,- `The local working directory \`${localWorkingDir}\` only holds a copy of the project instructions; do not use it.`,+ '# Workspace',+ `The current workspace is \`${hosted.workingDir}\` (${hosted.platform}, shell: ${hosted.shell}${hosted.osVersion ? `, ${hosted.osVersion}` : ''}).`,+ `File and shell tools operate in this workspace. Use paths under \`${hosted.workingDir}\`; relative paths resolve against it.`,];if (hosted.extraDirs.length || hosted.writableDirs.length) {- lines.push(`Additional directories on that computer: ${[...new Set([...hosted.extraDirs, ...hosted.writableDirs])].map((dir) => `\`${dir}\``).join(', ')}.`);+ lines.push(`Additional workspace directories: ${[...new Set([...hosted.extraDirs, ...hosted.writableDirs])].map((dir) => `\`${dir}\``).join(', ')}.`);}lines.push(`Is a git repository: ${hosted.isGitRepo ? 'yes' : 'no'}.`);if (hosted.personalInstructions?.trim()) {- lines.push('', "# The user's personal instructions (from their computer)", hosted.personalInstructions.trim());+ lines.push('', "# The user's personal instructions", hosted.personalInstructions.trim());}return lines.join('\n');}