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): isolate hosted workspace paths

Lizic551b15aa2b8
diff --git a/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts b/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts
index 9938dfb7e7..70ded70b2b 100644
--- a/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts
+++ b/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts
@@ -21,6 +21,7 @@ import {
} from '@cindy/device-link';
import type { ExecutorAction, ExecutorGateDecision } from '../executor/gate';
+import { createExecutorEnv, resolveExecutorShell } from '../executor/shell';
import type { ExecutorWorkspace } from '../executor/workspace';
export const EXEC_SERVER_WS_PATH = '/ws/exec-server';
@@ -35,7 +36,7 @@ export interface ExecServerRelayDeps {
workspace: ExecutorWorkspace;
authorize(action: ExecutorAction): ExecutorGateDecision;
push(frames: RemoteAgentPushFrame[]): Promise<void>;
- env?: NodeJS.ProcessEnv;
+ env?: NodeJS.ProcessEnv | (() => NodeJS.ProcessEnv);
log?: { warn(message: string, meta?: Record<string, unknown>): void };
}
@@ -87,8 +88,8 @@ 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 {
+/** 映射协议路径、命令和可逆的 UTF-8 文件数据;二进制内容保持原样。 */
+export function mapExecServerParams(value: unknown, workspace: ExecutorWorkspace, method?: string): 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']) {
@@ -100,12 +101,15 @@ export function mapExecServerParams(value: unknown, workspace: ExecutorWorkspace
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);
+ if (Array.isArray(result.argv)) result.argv = result.argv.map((part) => typeof part === 'string' ? workspace.mapCommand(part, resolveExecutorShell().dialect) : part);
+ if (typeof result.command === 'string') result.command = workspace.mapCommand(result.command, resolveExecutorShell().dialect);
+ if (method?.startsWith('fs/write') && typeof result.dataBase64 === 'string') {
+ result.dataBase64 = workspace.mapInputFromAgent(Buffer.from(result.dataBase64, 'base64')).toString('base64');
+ }
return result;
}
-/** JSON 层逐字符串投影,文件 base64 数据原样返回;进程输出单独解码。 */
+/** JSON 层逐字符串投影;文件 base64 数据保持原始字节,进程输出单独解码。 */
export function mapExecServerResult(value: unknown, workspace: ExecutorWorkspace, method?: string): unknown {
if (typeof value === 'string') {
if (value.startsWith('file://')) {
@@ -180,7 +184,9 @@ export class ExecServerRelay {
try {
child = spawn(this.deps.codexPath, ['exec-server', '--listen', 'stdio://'], {
cwd: this.deps.cwd,
- env: this.deps.env ?? process.env,
+ env: typeof this.deps.env === 'function'
+ ? this.deps.env()
+ : createExecutorEnv(this.deps.env ?? process.env),
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
});
@@ -223,7 +229,7 @@ export class ExecServerRelay {
message = null;
}
if (message && typeof message.method === 'string' && message.id !== undefined) {
- message.params = mapExecServerParams(message.params, this.deps.workspace);
+ message.params = mapExecServerParams(message.params, this.deps.workspace, message.method);
data = JSON.stringify(message);
for (const action of execServerActions(message.method, message.params, this.deps.cwd)) {
const decision = this.deps.authorize(action);
diff --git a/apps/desktop/src/main/remote-agent/controller/router.ts b/apps/desktop/src/main/remote-agent/controller/router.ts
index 033f0fb999..1391b5fda9 100644
--- a/apps/desktop/src/main/remote-agent/controller/router.ts
+++ b/apps/desktop/src/main/remote-agent/controller/router.ts
@@ -8,10 +8,12 @@
* 查询参数一律丢弃,不能借它冒用别的任务)。
* 其余路径一律 404。
*/
+import { fileURLToPath } from 'node:url';
import type { RemoteAgentReply } from '@cindy/device-link';
import { CINDY_EXEC_MCP_SERVER, handleExecMcpRequest } from '../executor/ccMcp';
import { ExecutorRequestError, type RemoteExecutor } from '../executor/executor';
+import { resolveExecutorShell } from '../executor/shell';
/** 本任务可用的一个本机 MCP 服务:完整地址(已带本任务身份)与要附加的请求头。 */
export interface LocalMcpTarget {
@@ -63,7 +65,7 @@ export function createReverseHttpRouter(deps: ReverseHttpRouterDeps) {
const mapArguments = (value: unknown, key = ''): unknown => {
if (typeof value === 'string') {
- if (/^(?:cmd|command)$/.test(key)) return workspace.mapCommand(value);
+ if (/^(?:cmd|command)$/.test(key)) return workspace.mapCommand(value, resolveExecutorShell().dialect);
if (/^(?:path|filePath|file_path|directory|workingDir|cwd|root|libraryRoot|sourcePath|destinationPath)$/i.test(key)) return workspace.mapAlias(value);
return value;
}
@@ -72,7 +74,20 @@ export function createReverseHttpRouter(deps: ReverseHttpRouterDeps) {
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 (typeof value === 'string') {
+ if (value.startsWith('file://')) {
+ try {
+ const uri = new URL(value);
+ const virtual = workspace.toAgentPath(fileURLToPath(uri));
+ if (virtual !== fileURLToPath(uri)) {
+ uri.host = '';
+ uri.pathname = virtual.replace(/\\/g, '/');
+ return uri.href;
+ }
+ } catch { /* 普通字符串或非本机 file URL,交给文本投影。 */ }
+ }
+ 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)]));
diff --git a/apps/desktop/src/main/remote-agent/controller/startRemote.ts b/apps/desktop/src/main/remote-agent/controller/startRemote.ts
index d824284291..d87df77216 100644
--- a/apps/desktop/src/main/remote-agent/controller/startRemote.ts
+++ b/apps/desktop/src/main/remote-agent/controller/startRemote.ts
@@ -175,6 +175,7 @@ export async function startRemoteAgentSession(
codexPath,
cwd: workspace.workingDir,
workspace,
+ env: () => workspace.hostedProcessEnv(path.join(os.tmpdir(), 'cindy-remote-agent')),
authorize: (action) => executor.check(action),
push: async (frames) => {
await pushFrames?.(frames);
@@ -267,6 +268,10 @@ export async function startRemoteAgentSession(
let startedRaw: Record<string, unknown>;
try {
+ const caps = await RemoteAgentRunClient.caps(deps.invoke);
+ if (caps.virtualWorkspace !== true) {
+ throw new Error('[REMOTE_AGENT_UNSUPPORTED] The other computer does not support the virtual workspace required to protect local paths.');
+ }
startedRaw = await client.open(kind, payload);
} catch (error) {
client.abandon('start-failed');
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 53e1a0f378..dbc359f545 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
@@ -8,7 +8,7 @@ import { handleExecMcpRequest } from '../ccMcp';
import { RemoteExecutor } from '../executor';
import { EXECUTOR_APPROVAL_TTL_MS, ExecutorGate, executorGateModeFor } from '../gate';
import type { PdfTextExtractor } from '../files';
-import { findWindowsGitBash, truncateOutput } from '../shell';
+import { createExecutorEnv, findWindowsGitBash, truncateOutput } from '../shell';
import { ExecutorWorkspace } from '../workspace';
const RG = path.resolve(__dirname, '../../../../../../ripgrep-bin', `${process.platform}-${process.arch}`, process.platform === 'win32' ? 'rg.exe' : 'rg');
@@ -63,6 +63,50 @@ afterEach(() => {
});
describe('workspace', () => {
+ it('filters credentials and real user directories from child environments while keeping PATH', () => {
+ const env = createExecutorEnv({
+ PATH: 'tool-path',
+ HOME: 'C:/Users/real',
+ USERPROFILE: 'C:/Users/real',
+ TEMP: 'C:/Users/real/AppData/Local/Temp',
+ OPENAI_API_KEY: 'secret',
+ SESSION_TOKEN: 'secret',
+ SAFE_FLAG: '1',
+ });
+ expect(env).toEqual({ PATH: 'tool-path', SAFE_FLAG: '1' });
+ });
+
+ it('gives hosted processes virtual home and temp paths without dropping command search', () => {
+ const workspace = new ExecutorWorkspace({ workingDir: project });
+ workspace.setVirtualRoot('/Users/agent');
+ const env = workspace.hostedProcessEnv(path.join(root, 'hosted-temp'));
+ expect(env.PATH).toBeTruthy();
+ expect(env.HOME).not.toBe(os.homedir());
+ expect(workspace.resolve('~/.config')).toBe(path.join(env.HOME!, '.config'));
+ expect(workspace.mapTextForAgent(env.HOME!)).not.toContain(os.homedir());
+ expect(workspace.mapTextForAgent(env.TMP!)).not.toContain(os.tmpdir());
+ });
+
+ it('passes the isolated environment to Claude shell commands', async () => {
+ const workspace = new ExecutorWorkspace({ workingDir: project });
+ workspace.setVirtualRoot('/Users/agent');
+ const executor = new RemoteExecutor({
+ workspace,
+ gate: new ExecutorGate(workspace, 'normal'),
+ rgPath: RG,
+ tempDir: path.join(root, 'shell-temp'),
+ });
+ const bash = process.platform === 'win32' && !findWindowsGitBash()
+ ? 'node -p "process.env.HOME"'
+ : "node -p 'process.env.HOME'";
+ const result = await executor.callTool('Bash', { command: bash });
+ const output = text(result);
+ expect(result.isError).not.toBe(true);
+ expect(output).toContain('/Users/agent');
+ expect(output).not.toContain(os.homedir());
+ await executor.close();
+ });
+
it('resolves relative paths against the working directory and maps shadow paths back', () => {
const workspace = new ExecutorWorkspace({ workingDir: project, aliases: [{ from: '/remote/shadow/proj', to: project }] });
expect(workspace.resolve('a/b.txt')).toBe(path.join(project, 'a/b.txt'));
@@ -107,6 +151,9 @@ describe('permission ceiling', () => {
expect(gate.authorize({ kind: 'exec', command: risky, cwd: project }).ok).toBe(false);
gate.recordApproval({ kind: 'exec', command: risky, cwd: project });
expect(gate.authorize({ kind: 'exec', command: risky, cwd: project }).ok).toBe(true);
+ const cwdBound = 'rm -rf build';
+ gate.recordApproval({ kind: 'exec', command: cwdBound, cwd: project });
+ expect(gate.authorize({ kind: 'exec', command: cwdBound, cwd: outside }).ok).toBe(false);
// 命令批准用一次即失效。
expect(gate.authorize({ kind: 'exec', command: risky, cwd: project }).ok).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.ts
index 9388c7e1ae..230ef1d695 100644
--- a/apps/desktop/src/main/remote-agent/executor/__tests__/virtualWorkspace.test.ts
+++ b/apps/desktop/src/main/remote-agent/executor/__tests__/virtualWorkspace.test.ts
@@ -34,8 +34,8 @@ describe('virtual workspace', () => {
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 }]);
+ // 文本文件内容也投影;写回时会还原,避免 Agent 通过中间文件读出本机路径。
+ expect(read.content).toEqual([{ type: 'text', text: '1 literal ' + virtual }]);
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');
@@ -51,6 +51,8 @@ describe('virtual workspace', () => {
.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');
+ expect(projectPathText(';`/real/project`? /real/project&x', [{ from: '/real/project', to: '/virtual/project' }]))
+ .toBe(';`/virtual/project`? /virtual/project&x');
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');
@@ -65,7 +67,7 @@ describe('virtual workspace', () => {
await executor.close();
});
- it('maps Codex request paths and commands before permission checks, without touching file bytes', async () => {
+ it('maps Codex request paths and commands before permission checks and projects text 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') });
@@ -75,7 +77,7 @@ describe('virtual 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);
+ expect(Buffer.from((mapExecServerResult(fileData, workspace) as any).result.dataBase64, 'base64').toString()).toBe(project);
await executor.close();
});
@@ -88,7 +90,7 @@ describe('virtual workspace', () => {
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') }] } };
+ const result = { result: { content: [{ type: 'text', text: 'File: ' + path.join(project, 'a.txt') }], file: pathToFileURL(path.join(project, 'a.txt')).href } };
return new Response(sse ? 'data: ' + JSON.stringify(result) + '\n\n' : JSON.stringify(result), {
headers: { 'content-type': sse ? 'text/event-stream' : 'application/json' },
});
@@ -103,6 +105,7 @@ describe('virtual workspace', () => {
if (reply.type === 'http') {
const body = Buffer.from(reply.body!, 'base64').toString();
expect(body).toContain('/Users/agent/workspace/a.txt');
+ expect(body).toContain('file:///Users/agent/workspace/a.txt');
expect(body).not.toContain(project.replace(/\\/g, '\\\\'));
}
}
diff --git a/apps/desktop/src/main/remote-agent/executor/executor.ts b/apps/desktop/src/main/remote-agent/executor/executor.ts
index e3e81618a7..ab4c6d4cd0 100644
--- a/apps/desktop/src/main/remote-agent/executor/executor.ts
+++ b/apps/desktop/src/main/remote-agent/executor/executor.ts
@@ -7,6 +7,7 @@
* NotebookEdit(Claude Code 的自带文件与命令工具关掉后由它顶替)。
* 写文件前通知「每轮改动对比」抓取改前内容;命令执行后登记一次无法预知范围的改动。
*/
+import os from 'node:os';
import path from 'node:path';
import {
@@ -32,7 +33,7 @@ import {
} from './files';
import type { ExecutorAction, ExecutorGate, ExecutorGateDecision, ExecutorGateMode } from './gate';
import { piGrep, type PiGrepInput } from './search';
-import { runOnce, ShellSession } from './shell';
+import { resolveExecutorShell, runOnce, ShellSession } from './shell';
import { ExecutorPathError, type ExecutorWorkspace } from './workspace';
/** Pi bash 的超时(秒)上限,与 Pi 侧 Cindy 桥的上限一致。 */
@@ -107,11 +108,17 @@ export class RemoteExecutor {
constructor(private readonly opts: RemoteExecutorOptions) {
this.workspace = opts.workspace;
this.gate = opts.gate;
- this.rg = createRipgrepRunner(opts.rgPath);
+ const tempDir = opts.tempDir ?? path.join(os.tmpdir(), 'cindy-remote-agent');
+ // Initialize the task-local home before any Read/Write path is resolved; later calls refresh
+ // its virtual alias once the host mirror root is known.
+ opts.workspace.hostedProcessEnv(tempDir);
+ const rg = createRipgrepRunner(opts.rgPath);
+ this.rg = (args, cwd, runOptions) => rg(args, cwd, { ...runOptions, env: opts.workspace.hostedProcessEnv(tempDir) });
this.shell = new ShellSession({
workingDir: opts.workspace.workingDir,
isAllowedCwd: (cwd) => opts.workspace.contains(cwd),
- tempDir: opts.tempDir,
+ tempDir,
+ env: () => opts.workspace.hostedProcessEnv(tempDir),
});
this.writeHooks = {
beforeWrite: async (absPath) => {
@@ -140,6 +147,7 @@ export class RemoteExecutor {
if (this.closed) return;
this.closed = true;
await this.shell.close();
+ await this.workspace.cleanupHostedProcessEnv();
}
private ensureOpen(): void {
@@ -170,7 +178,7 @@ export class RemoteExecutor {
case 'fs.read': {
const target = this.resolvePath(str(body, 'path'));
this.authorize({ kind: 'read', path: target });
- return { data: (await rawReadFile(target)).toString('base64') };
+ return { data: this.workspace.mapOutputForAgent(await rawReadFile(target)).toString('base64') };
}
case 'fs.access': {
const target = this.resolvePath(str(body, 'path'));
@@ -183,7 +191,7 @@ export class RemoteExecutor {
const target = this.resolvePath(str(body, 'path'));
this.authorize({ kind: 'write', path: target });
if (typeof body.data !== 'string') throw new ExecutorRequestError('INVALID', 'data must be a base64 string');
- const data = Buffer.from(body.data, 'base64');
+ const data = this.workspace.mapInputFromAgent(Buffer.from(body.data, 'base64'));
await this.writeHooks.beforeWrite(target);
await rawWriteFile(target, data);
return {};
@@ -201,7 +209,7 @@ export class RemoteExecutor {
}
case 'fs.readdir': {
const target = this.resolvePath(str(body, 'path'));
- this.authorize({ kind: 'read', path: target });
+ this.authorize({ kind: 'read', path: target, scope: 'tree' });
return { entries: await rawReaddir(target) };
}
case 'fs.glob': {
@@ -220,11 +228,12 @@ 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' });
- const result = await piGrep(this.opts.rgPath, root, params, signal);
+ const result = await piGrep(this.opts.rgPath, root, params, signal, this.workspace.hostedProcessEnv(this.shell.getTempDir()));
return { ...result, text: this.workspace.mapTextForAgent(result.text) };
}
case 'exec.run': {
- const command = this.workspace.mapCommand(str(body, 'command'));
+ this.workspace.virtualizeDirs([this.shell.getTempDir()]);
+ const command = this.workspace.mapCommand(str(body, 'command'), resolveExecutorShell().dialect);
const cwd = this.resolvePath(optionalString(body, 'cwd') ?? this.workspace.workingDir);
this.authorize({ kind: 'exec', command, cwd });
const timeoutSeconds = optionalNumber(body, 'timeout');
@@ -232,7 +241,12 @@ export class RemoteExecutor {
? Math.min(timeoutSeconds, PI_BASH_MAX_TIMEOUT_SECONDS) * 1000
: undefined;
try {
- const result = await runOnce(command, { cwd, timeoutMs, signal });
+ const result = await runOnce(command, {
+ cwd,
+ timeoutMs,
+ signal,
+ env: this.workspace.hostedProcessEnv(this.shell.getTempDir()),
+ });
return {
output: this.workspace.mapOutputForAgent(result.output).toString('base64'),
exitCode: result.exitCode,
@@ -282,19 +296,19 @@ export class RemoteExecutor {
case 'Read': {
const target = this.resolvePath(str(args, 'file_path'), this.shell.getCwd());
this.authorizeTool({ kind: 'read', path: target });
- return await ccRead(target, {
+ return this.mapToolResult(await ccRead(target, {
file_path: target,
offset: optionalNumber(args, 'offset'),
limit: optionalNumber(args, 'limit'),
pages: optionalString(args, 'pages'),
- }, this.readState, this.workspace.toAgentPath(this.workspace.workingDir), this.opts.extractPdfText, this.workspace.toAgentPath(target));
+ }, 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, this.workspace.toAgentPath(target));
+ return this.mapToolResult(await ccWrite(target, this.workspace.mapTextFromAgent(content), this.readState, this.writeHooks, this.workspace.toAgentPath(target)));
}
case 'Edit': {
const target = this.resolvePath(str(args, 'file_path'), this.shell.getCwd());
@@ -302,11 +316,11 @@ export class RemoteExecutor {
return textResult('old_string and new_string must be strings.', true);
}
this.authorizeTool({ kind: 'write', path: target });
- return await ccEdit(target, {
- old_string: args.old_string,
- new_string: args.new_string,
+ return this.mapToolResult(await ccEdit(target, {
+ old_string: this.workspace.mapTextFromAgent(args.old_string),
+ new_string: this.workspace.mapTextFromAgent(args.new_string),
replace_all: args.replace_all === true,
- }, this.readState, this.writeHooks, this.workspace.toAgentPath(target));
+ }, this.readState, this.writeHooks, this.workspace.toAgentPath(target)));
}
case 'NotebookEdit': {
const target = this.resolvePath(str(args, 'notebook_path'), this.shell.getCwd());
@@ -315,12 +329,12 @@ export class RemoteExecutor {
const editMode = args.edit_mode === 'insert' || args.edit_mode === 'delete' || args.edit_mode === 'replace'
? args.edit_mode : undefined;
this.authorizeTool({ kind: 'write', path: target });
- return await ccNotebookEdit(target, {
+ return this.mapToolResult(await ccNotebookEdit(target, {
cell_id: optionalString(args, 'cell_id'),
- new_source: args.new_source,
+ new_source: this.workspace.mapTextFromAgent(args.new_source),
cell_type: cellType,
edit_mode: editMode,
- }, this.readState, this.writeHooks);
+ }, this.readState, this.writeHooks));
}
default:
return textResult(`Unknown tool: ${name}`, true);
@@ -339,10 +353,19 @@ export class RemoteExecutor {
if (!decision.ok) throw new ExecutorDenied(decision.reason ?? 'Not allowed.');
}
+ private mapToolResult(result: ToolResult): ToolResult {
+ return {
+ ...result,
+ content: result.content.map((item) => item.type === 'text'
+ ? { ...item, text: this.workspace.mapTextForAgent(item.text) }
+ : item),
+ };
+ }
+
private async bash(args: Record<string, unknown>, signal?: AbortSignal): Promise<ToolResult> {
const rawCommand = args.command;
if (typeof rawCommand !== 'string' || !rawCommand.trim()) return textResult('command is required.', true);
- const command = this.workspace.mapCommand(rawCommand);
+ const command = this.workspace.mapCommand(rawCommand, resolveExecutorShell().dialect);
this.authorizeTool({ kind: 'exec', command, cwd: this.shell.getCwd() });
const timeout = optionalNumber(args, 'timeout');
try {
diff --git a/apps/desktop/src/main/remote-agent/executor/files.ts b/apps/desktop/src/main/remote-agent/executor/files.ts
index 56fbeb87e1..2c3c2211ff 100644
--- a/apps/desktop/src/main/remote-agent/executor/files.ts
+++ b/apps/desktop/src/main/remote-agent/executor/files.ts
@@ -127,12 +127,12 @@ export async function detectImageMime(absPath: string): Promise<string | null> {
export interface RipgrepRunner {
/** 返回 rg 的 stdout 行;达到 maxLines 时提前结束。退出码 1(无匹配)视为正常。 */
- (args: string[], cwd: string, opts: { maxLines: number; signal?: AbortSignal }): Promise<string[]>;
+ (args: string[], cwd: string, opts: { maxLines: number; signal?: AbortSignal; env?: NodeJS.ProcessEnv }): Promise<string[]>;
}
export function createRipgrepRunner(rgPath: string): RipgrepRunner {
- return (args, cwd, { maxLines, signal }) => new Promise((resolve, reject) => {
- const child = spawn(rgPath, args, { cwd, stdio: ['ignore', 'pipe', 'pipe'], signal });
+ return (args, cwd, { maxLines, signal, env }) => new Promise((resolve, reject) => {
+ const child = spawn(rgPath, args, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'], signal });
const lines: string[] = [];
let stderr = '';
let stopped = false;
diff --git a/apps/desktop/src/main/remote-agent/executor/gate.ts b/apps/desktop/src/main/remote-agent/executor/gate.ts
index 978bff9ac5..9dfeca3919 100644
--- a/apps/desktop/src/main/remote-agent/executor/gate.ts
+++ b/apps/desktop/src/main/remote-agent/executor/gate.ts
@@ -59,6 +59,10 @@ function pathKey(target: string): string {
return path.resolve(target);
}
+function execKey(command: string, cwd: string): string {
+ return `${path.resolve(cwd)}\\0${command}`;
+}
+
export class ExecutorGate {
private mode: ExecutorGateMode;
private approvals: Approval[] = [];
@@ -83,7 +87,7 @@ export class ExecutorGate {
recordApproval(action: ExecutorAction): void {
this.prune();
this.approvals.push(action.kind === 'exec'
- ? { kind: 'exec', key: action.command, expiresAt: this.now() + EXECUTOR_APPROVAL_TTL_MS }
+ ? { kind: 'exec', key: execKey(action.command, action.cwd), expiresAt: this.now() + EXECUTOR_APPROVAL_TTL_MS }
: { kind: 'path', key: pathKey(action.path), expiresAt: this.now() + EXECUTOR_APPROVAL_TTL_MS });
if (this.approvals.length > MAX_APPROVALS) this.approvals.splice(0, this.approvals.length - MAX_APPROVALS);
}
@@ -124,7 +128,7 @@ export class ExecutorGate {
private consume(action: ExecutorAction): boolean {
this.prune();
const kind = action.kind === 'exec' ? 'exec' : 'path';
- const key = action.kind === 'exec' ? action.command : pathKey(action.path);
+ const key = action.kind === 'exec' ? execKey(action.command, action.cwd) : pathKey(action.path);
const index = this.approvals.findIndex((approval) => approval.kind === kind && approval.key === key);
if (index < 0) return false;
if (kind === 'exec') this.approvals.splice(index, 1);
diff --git a/apps/desktop/src/main/remote-agent/executor/search.ts b/apps/desktop/src/main/remote-agent/executor/search.ts
index 77711cd31f..d055e4d542 100644
--- a/apps/desktop/src/main/remote-agent/executor/search.ts
+++ b/apps/desktop/src/main/remote-agent/executor/search.ts
@@ -55,6 +55,7 @@ export async function piGrep(
root: string,
input: PiGrepInput,
signal?: AbortSignal,
+ env?: NodeJS.ProcessEnv,
): Promise<PiGrepResult> {
const stat = await fsp.stat(root);
const rootIsDirectory = stat.isDirectory();
@@ -77,7 +78,7 @@ export async function piGrep(
let lastLine = -1;
await new Promise<void>((resolve, reject) => {
- const child = spawn(rgPath, args, { cwd, stdio: ['ignore', 'pipe', 'pipe'], signal });
+ const child = spawn(rgPath, args, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'], signal });
const reader = readline.createInterface({ input: child.stdout });
let stopped = false;
reader.on('line', (raw) => {
diff --git a/apps/desktop/src/main/remote-agent/executor/shell.ts b/apps/desktop/src/main/remote-agent/executor/shell.ts
index adf24a7117..cd6740e75b 100644
--- a/apps/desktop/src/main/remote-agent/executor/shell.ts
+++ b/apps/desktop/src/main/remote-agent/executor/shell.ts
@@ -17,6 +17,26 @@ import path from 'node:path';
export const CC_BASH_DEFAULT_TIMEOUT_MS = 120_000;
export const CC_BASH_MAX_TIMEOUT_MS = 600_000;
export const CC_BASH_MAX_OUTPUT_CHARS = 30_000;
+
+const HIDDEN_EXECUTOR_ENV_NAMES = new Set([
+ 'HOME', 'USERPROFILE', 'HOMEDRIVE', 'HOMEPATH', 'PWD', 'OLDPWD', 'TMP', 'TEMP', 'TMPDIR',
+ 'APPDATA', 'LOCALAPPDATA', 'XDG_CONFIG_HOME', 'XDG_CACHE_HOME', 'XDG_DATA_HOME',
+ 'CLAUDE_CONFIG_DIR', 'CODEX_HOME', 'CINDY_CONFIG_DIR', 'CLAUDE_CODE_GIT_BASH_PATH',
+ 'SSH_AUTH_SOCK', 'GIT_CONFIG_GLOBAL', 'GIT_CONFIG_SYSTEM', 'NPM_CONFIG_USERCONFIG',
+]);
+const HIDDEN_EXECUTOR_ENV_KEYS = /(?:^|[_-])(API[_-]?KEY|KEY|TOKEN|SECRET|PASSWORD|PASSWD|AUTH|CREDENTIAL|COOKIE|PRIVATE)(?:$|[_-])/i;
+
+/** 给控制端子进程的最小环境:保留命令搜索与平台运行时,去掉凭证和真实用户目录。 */
+export function createExecutorEnv(input: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
+ const output: NodeJS.ProcessEnv = {};
+ for (const [key, value] of Object.entries(input)) {
+ if (value === undefined) continue;
+ const upper = key.toUpperCase();
+ if (HIDDEN_EXECUTOR_ENV_NAMES.has(upper) || HIDDEN_EXECUTOR_ENV_KEYS.test(upper)) continue;
+ output[key] = value;
+ }
+ return output;
+}
/** 一次性执行的输出上限(超出部分丢弃头部,保留最新输出)。 */
const RUN_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
const KILL_GRACE_MS = 2_000;
@@ -208,7 +228,7 @@ export function runOnce(script: string, opts: RunOptions): Promise<RunResult> {
try {
child = spawn(shell.file, shell.args, {
cwd: file.dir,
- env: opts.env ?? process.env,
+ env: opts.env ?? createExecutorEnv(),
stdio: ['ignore', 'pipe', 'pipe'],
detached: process.platform !== 'win32',
windowsHide: true,
@@ -294,6 +314,8 @@ export interface ShellSessionOptions {
isAllowedCwd: (cwd: string) => boolean;
/** 后台命令输出文件所在目录(本机)。 */
tempDir?: string;
+ /** 每次启动子进程时生成隔离环境,避免复用启动时已过期的路径别名。 */
+ env?: () => NodeJS.ProcessEnv;
}
/** Git Bash 的 pwd 使用 MSYS 挂载路径,权限与后续文件工具必须回到 Windows 本机路径。 */
@@ -339,7 +361,12 @@ export class ShellSession {
const started = Date.now();
let result: RunResult;
try {
- result = await runOnce(script, { cwd: startCwd, timeoutMs: timeout, signal });
+ result = await runOnce(script, {
+ cwd: startCwd,
+ timeoutMs: timeout,
+ signal,
+ env: this.opts.env?.() ?? createExecutorEnv(),
+ });
} catch (error) {
await fsp.rm(cwdFile, { force: true });
return { text: `Failed to run command: ${(error as Error).message}`, isError: true };
@@ -398,7 +425,7 @@ export class ShellSession {
try {
child = spawn(shell.file, shell.args, {
cwd: file.dir,
- env: process.env,
+ env: this.opts.env?.() ?? createExecutorEnv(),
stdio: ['ignore', out, out],
detached: process.platform !== 'win32',
windowsHide: true,
diff --git a/apps/desktop/src/main/remote-agent/executor/workspace.ts b/apps/desktop/src/main/remote-agent/executor/workspace.ts
index d63164c1a5..2e047ec2c4 100644
--- a/apps/desktop/src/main/remote-agent/executor/workspace.ts
+++ b/apps/desktop/src/main/remote-agent/executor/workspace.ts
@@ -6,6 +6,7 @@
* 让 Agent 照常加载项目说明与 Skill)在这里映射回本机真实目录,模型即使用了影子路径也落在
* 本机项目里。
*/
+import { randomUUID } from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -77,8 +78,9 @@ export function projectPathText(text: string, aliases: readonly ExecutorPathAlia
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');
+ // 左右都要求路径段边界,避免修改 longer/project2 或文本里的同前缀标识符。
+ // 这里的边界覆盖 shell 的 ;、反引号、?、& 等分隔符。
+ const pattern = new RegExp('(^|[^A-Za-z0-9_])(' + patterns.join('|') + ')(?=$|[^A-Za-z0-9_])([/\\\\][^\\s\\x60;:|&)<>}\\]]*|)', '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;
@@ -93,6 +95,8 @@ export class ExecutorWorkspace {
private extraDirs: string[];
private aliases: ExecutorPathAlias[];
private virtualRoot?: string;
+ private hostedEnvRoot?: string;
+ private hostedHomeDir?: string;
constructor(roots: ExecutorWorkspaceRoots) {
if (!path.isAbsolute(roots.workingDir)) throw new ExecutorPathError('working directory must be absolute');
@@ -106,7 +110,21 @@ export class ExecutorWorkspace {
/** Agent 启动后才知道它那边的影子目录,届时设置。 */
setAliases(aliases: readonly ExecutorPathAlias[]): void {
- this.aliases = aliases.filter((alias) => alias.from && path.isAbsolute(alias.to))
+ const expanded: ExecutorPathAlias[] = [];
+ for (const alias of aliases) {
+ if (!alias.from || !path.isAbsolute(alias.to)) continue;
+ expanded.push(alias);
+ const canonical = realPathOrAncestor(alias.to);
+ if (path.resolve(canonical) !== path.resolve(alias.to)) expanded.push({ from: alias.from, to: canonical });
+ }
+ const seen = new Set<string>();
+ this.aliases = expanded
+ .filter((alias) => {
+ const key = alias.from + '\\0' + path.resolve(alias.to);
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ })
.sort((a, b) => b.from.length - a.from.length);
}
@@ -161,7 +179,7 @@ export class ExecutorWorkspace {
return input;
}
- /** 工具的命令输出/诊断使用虚拟路径,文件内容与读写字节不经过文本替换。 */
+ /** 工具输出、诊断和可逆的 UTF-8 文本内容使用虚拟路径;二进制字节保持原样。 */
mapTextForAgent(text: string): string {
if (!this.virtualRoot) return text;
const aliases = this.aliases.flatMap((alias) => {
@@ -179,21 +197,157 @@ export class ExecutorWorkspace {
return projectPathText(text, aliases);
}
+ /** 把 Agent 虚拟路径还原成本机路径,用于文本文件写回。 */
+ mapTextFromAgent(text: string): string {
+ if (!this.virtualRoot) return text;
+ return projectPathText(text, this.aliases.map((alias) => ({
+ from: alias.from.replace(/\\/g, '/'),
+ to: alias.to,
+ })));
+ }
+
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;
+ if (data.includes(0) || !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 {
- // Windows 上的 Bash 使用正斜杠,避免未引用的反斜杠被 shell 当成转义。
- return projectPathText(command, this.aliases.map((alias) => ({
+ mapInputFromAgent(data: Buffer): Buffer {
+ const text = data.toString('utf8');
+ if (data.includes(0) || !Buffer.from(text, 'utf8').equals(data)) return data;
+ const projected = this.mapTextFromAgent(text);
+ return projected === text ? data : Buffer.from(projected, 'utf8');
+ }
+
+ /**
+ * 为控制端执行器创建隔离环境。只保留运行 shell 所需的通用系统变量;用户目录、临时目录
+ * 和凭证类变量都不从 Desktop 进程继承。目录仍在控制端落地,但会注册成虚拟别名,命令的
+ * env / printenv 输出再经过 mapOutputForAgent 时只会看到 Agent 侧路径。
+ */
+ hostedProcessEnv(tempDir: string): NodeJS.ProcessEnv {
+ const root = this.hostedEnvRoot ?? path.join(tempDir, 'env', randomUUID());
+ if (this.hostedEnvRoot !== root) {
+ this.hostedEnvRoot = root;
+ fs.mkdirSync(path.join(root, 'home'), { recursive: true });
+ fs.mkdirSync(path.join(root, 'tmp'), { recursive: true });
+ }
+ const fakeHome = path.join(root, 'home');
+ const fakeTemp = path.join(root, 'tmp');
+ this.hostedHomeDir = fakeHome;
+ this.virtualizeDirs([fakeHome, fakeTemp]);
+ const env: NodeJS.ProcessEnv = {};
+ const allowed = [
+ 'PATHEXT', 'SystemRoot', 'WINDIR', 'ComSpec', 'COMSPEC', 'SystemDrive', 'OS',
+ 'PROCESSOR_ARCHITECTURE', 'PROCESSOR_IDENTIFIER', 'PROCESSOR_LEVEL', 'PROCESSOR_REVISION',
+ 'NUMBER_OF_PROCESSORS', 'LANG', 'LC_ALL', 'LC_CTYPE', 'TERM', 'COLORTERM', 'CI',
+ 'NODE_ENV', 'FORCE_COLOR', 'NO_COLOR',
+ ];
+ for (const key of allowed) {
+ const value = process.env[key];
+ if (value !== undefined) env[key] = value;
+ }
+ const pathValue = process.env.PATH ?? process.env.Path ?? '';
+ // PATH 仍保留完整命令搜索能力;每个目录都登记成虚拟别名,printenv/env 的输出会投影回
+ // Agent 侧路径。这样用户级 Node/pnpm、Git Bash 等不会因为隔离而失效。
+ const pathEntries = pathValue.split(path.delimiter).filter(Boolean);
+ if (pathEntries.length) {
+ const pathRoot = path.join(root, 'path');
+ fs.mkdirSync(pathRoot, { recursive: true });
+ const hostedPathEntries: string[] = [];
+ for (const [index, target] of pathEntries.entries()) {
+ let stat: fs.Stats;
+ try {
+ stat = fs.statSync(target);
+ } catch {
+ continue;
+ }
+ if (!stat.isDirectory()) continue;
+ const link = path.join(pathRoot, `entry-${index}`);
+ try {
+ if (!fs.existsSync(link)) {
+ fs.symlinkSync(target, link, process.platform === 'win32' ? 'junction' : 'dir');
+ }
+ hostedPathEntries.push(link);
+ // Keep both sides addressable: child env uses the temporary link, while diagnostics such
+ // as process.execPath may still report the linked target directory.
+ this.virtualizeDirs([target, link]);
+ } catch {
+ // A PATH entry that cannot be linked is omitted rather than reintroducing a real path.
+ }
+ }
+ if (hostedPathEntries.length) env.PATH = hostedPathEntries.join(path.delimiter);
+ }
+ env.HOME = fakeHome;
+ env.USERPROFILE = fakeHome;
+ env.TMP = fakeTemp;
+ env.TEMP = fakeTemp;
+ env.TMPDIR = fakeTemp;
+ env.XDG_CONFIG_HOME = path.join(fakeHome, '.config');
+ env.XDG_CACHE_HOME = path.join(fakeHome, '.cache');
+ env.APPDATA = path.join(fakeHome, 'AppData', 'Roaming');
+ env.LOCALAPPDATA = path.join(fakeHome, 'AppData', 'Local');
+ env.USERNAME = 'agent';
+ env.USER = 'agent';
+ env.LOGNAME = 'agent';
+ if (process.platform !== 'win32') env.SHELL = '/bin/bash';
+ return env;
+ }
+
+ /** 任务结束后移除 fake HOME/TMP 与 PATH 链接,避免临时目录残留。 */
+ async cleanupHostedProcessEnv(): Promise<void> {
+ const root = this.hostedEnvRoot;
+ this.hostedEnvRoot = undefined;
+ this.hostedHomeDir = undefined;
+ if (!root) return;
+ await fs.promises.rm(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }).catch(() => undefined);
+ }
+
+ /** 命令文本里出现的影子目录前缀替换成本机目录(按 shell 语法安全引用)。 */
+ mapCommand(command: string, dialect: 'bash' | 'cmd' = 'bash'): string {
+ const aliases = this.aliases.map((alias) => ({
from: alias.from,
to: process.platform === 'win32' ? alias.to.replace(/\\/g, '/') : alias.to,
- })));
+ })).filter((alias) => alias.from.replace(/[\\/]+$/, '').length > 2)
+ .sort((a, b) => b.from.length - a.from.length);
+ if (!aliases.length) return command;
+ const patterns = aliases.map((alias) => alias.from.replace(/[\\/]+$/, '').split(/[\\/]/)
+ .map((part) => part.replace(/[.*+?^$()|[\\]{}]/g, '\\$&')).join('[/\\\\]'));
+ const pattern = new RegExp('(^|[^A-Za-z0-9_])(' + patterns.join('|') + ')(?=$|[^A-Za-z0-9_])([/\\\\][^\\s\\x60;:|&)<>}\\]]*|)', 'gi');
+ const quoteContext = (input: string, end: number): 'none' | 'single' | 'double' => {
+ let quote: 'none' | 'single' | 'double' = 'none';
+ let escaped = false;
+ for (let i = 0; i < end; i += 1) {
+ const char = input[i];
+ if (escaped) { escaped = false; continue; }
+ if (char === '\\' && quote !== 'single') { escaped = true; continue; }
+ if (quote === 'none' && char === "'") quote = 'single';
+ else if (quote === 'none' && char === '"') quote = 'double';
+ else if (quote === 'single' && char === "'") quote = 'none';
+ else if (quote === 'double' && char === '"') quote = 'none';
+ }
+ return quote;
+ };
+ const quote = (value: string, context: 'none' | 'single' | 'double'): string => {
+ if (dialect === 'cmd') {
+ const safe = value.replace(/%/g, '%%');
+ return context === 'double' ? safe : /[\s"&|<>^]/.test(safe) ? '"' + safe.replace(/"/g, '\\"') + '"' : safe;
+ }
+ if (/^[A-Za-z0-9_./:-]+$/.test(value)) return value;
+ if (context === 'single') return value.replace(/'/g, "'\\''");
+ if (context === 'double') return value.replace(/[\\$\x60"]/g, '\\$&');
+ return /[\s'"\x60$;&|<>()[\\]{}!*?]/.test(value)
+ ? "'" + value.replace(/'/g, "'\\''") + "'"
+ : value;
+ };
+ return command.replace(pattern, (match: string, left: string, prefix: string, suffix: string, offset: number, input: string) => {
+ const alias = aliases.find((entry) => stripAliasPrefix(prefix, entry.from) === '');
+ if (!alias) return match;
+ const separator = alias.to.includes('\\') ? '\\' : '/';
+ const target = alias.to.replace(/[\\/]+$/, '') + suffix.replace(/[\\/]/g, separator);
+ return left + quote(target, quoteContext(input, offset + left.length));
+ });
}
/** 把 Agent 给的路径解析成本机绝对路径(相对路径以 baseDir / 工作目录为基准)。 */
@@ -203,7 +357,7 @@ export class ExecutorWorkspace {
}
const trimmed = input.startsWith('@') ? input.slice(1) : input;
const expanded = trimmed === '~' || trimmed.startsWith('~/')
- ? path.join(process.env.HOME ?? '', trimmed.slice(1))
+ ? path.join(this.hostedHomeDir ?? process.env.HOME ?? '', trimmed.slice(1))
: trimmed;
return path.resolve(this.mapAlias(baseDir), this.mapAlias(expanded));
}
diff --git a/apps/desktop/src/main/remote-agent/host/runHost.ts b/apps/desktop/src/main/remote-agent/host/runHost.ts
index 5aae8147be..aa3ff66451 100644
--- a/apps/desktop/src/main/remote-agent/host/runHost.ts
+++ b/apps/desktop/src/main/remote-agent/host/runHost.ts
@@ -809,6 +809,7 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {
maxRuns: REMOTE_AGENT_MAX_RUNS_PER_CONTROLLER,
uploadChunkBytes: REMOTE_AGENT_UPLOAD_CHUNK_BYTES,
maxPayloadBytes: REMOTE_AGENT_MAX_PAYLOAD_BYTES,
+ virtualWorkspace: true,
};
return caps;
}
diff --git a/apps/desktop/src/main/remote-agent/wire.ts b/apps/desktop/src/main/remote-agent/wire.ts
index 90c23c5fb1..ed05a1dd79 100644
--- a/apps/desktop/src/main/remote-agent/wire.ts
+++ b/apps/desktop/src/main/remote-agent/wire.ts
@@ -139,7 +139,7 @@ export interface RemoteAgentWirePersonal {
export interface RemoteAgentOpenPayload {
/** 控制端任务 id。 */
sessionId: string;
- /** 可选增量能力:Agent 使用本机虚拟工作区,旧控制端不传时沿用原路径合同。 */
+ /** 能力增量:Agent 使用本机虚拟工作区;新控制端在 open 前必须确认对端 caps 支持。 */
virtualWorkspace?: boolean;
options: RemoteAgentWireStartOptions;
workspace: RemoteAgentWireWorkspace;
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 142ca4c1a9..298dc01daf 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -466,13 +466,14 @@ 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 虚拟化。
+- **本机虚拟工作区**:A 在 open 前先调用 caps,只有 B 回包声明
+ virtualWorkspace: true 才发送 open;旧 B 或未声明能力的 B 直接提示升级,不能静默降级到
+ 暴露 A 真实路径的合同。支持时,B 使用不含 A 真实目录名的固定短父级层级,继续承载最多 24
+ 级祖先说明文件,并回显 virtualWorkspace、extraDirs、writableDirs。Agent prompt、文件
+ 引用、工具路径诊断与命令输出使用 B 本机虚拟路径;包含本机路径的文本结果会做投影,写回时再
+ 还原到 A 的真实路径,二进制内容保持原样。A 的真实目录继续用于权限 gate、执行与变更抓取,
+ 路径别名不增加授权。执行平台与 shell 保留 A 的实际值,以免跨 macOS / Windows / Linux 选错
+ 命令。此增量不修改 channel、relay、协议版本或服务器,也不是 OS 虚拟化。
- **回退**:`REMOTE_AGENT_METHODS` 含 `previewRewindFiles` / `commitRewindFiles`,B 在 `describeHandle`
里声明支持后 A 才提供回退;文件按 A 本机的保存点链回退,对话由 B 截断。B 不支持时 A 关闭回退并提示
升级那台的 Cindy。
diff --git a/packages/device-link/src/remoteAgent.ts b/packages/device-link/src/remoteAgent.ts
index 9cade9a4c7..23bb847f2c 100644
--- a/packages/device-link/src/remoteAgent.ts
+++ b/packages/device-link/src/remoteAgent.ts
@@ -166,6 +166,8 @@ export interface RemoteAgentCaps {
maxRuns: number;
uploadChunkBytes: number;
maxPayloadBytes: number;
+ /** 是否支持 opaque 虚拟工作区;不支持时控制端必须拒绝启动以免泄露真实路径。 */
+ virtualWorkspace?: boolean;
}
export interface RemoteAgentReadResult {
@@ -364,6 +366,7 @@ export function parseRemoteAgentCaps(value: unknown): RemoteAgentCaps {
maxRuns: count(v.maxRuns, 1_000),
uploadChunkBytes: count(v.uploadChunkBytes, REMOTE_AGENT_UPLOAD_CHUNK_BYTES),
maxPayloadBytes: count(v.maxPayloadBytes, Number.MAX_SAFE_INTEGER),
+ ...(v.virtualWorkspace === true ? { virtualWorkspace: true } : {}),
};
if (caps.version < 1 || caps.maxRuns < 1 || caps.uploadChunkBytes < 1) invalid();
return caps;