Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 修复远程供应商工作目录、Skill 与文件打开路径 (#6037)

Lizie818d410a408
diff --git a/apps/desktop/src/main/remote-agent/__tests__/eventProjection.test.ts b/apps/desktop/src/main/remote-agent/__tests__/eventProjection.test.ts
new file mode 100644
index 0000000000..136d19123a
--- /dev/null
+++ b/apps/desktop/src/main/remote-agent/__tests__/eventProjection.test.ts
@@ -0,0 +1,409 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+import type { AgentEvent } from '@cindy/maker-core';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { collectGeneratedFiles } from '../../../renderer/lib/generatedFiles';
+import { resolveToolFilePath } from '../../../renderer/lib/localPathResolver';
+import { mapClaudeHostedEvent } from '../controller/eventMap';
+import { createRemoteAgentHandle } from '../controller/proxyHandle';
+import type { RemoteAgentRunClient } from '../controller/runClient';
+import { RemoteExecutor } from '../executor/executor';
+import { ExecutorGate } from '../executor/gate';
+import { ExecutorWorkspace } from '../executor/workspace';
+
+let root: string;
+beforeEach(() => { root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-event-projection-'))); });
+afterEach(() => { fs.rmSync(root, { recursive: true, force: true }); });
+
+function setup(virtual: string) {
+ const real = path.join(root, '真实 目录');
+ fs.mkdirSync(real);
+ const workspace = new ExecutorWorkspace({ workingDir: real, aliases: [{ from: virtual, to: real }] });
+ workspace.setVirtualRoot(virtual);
+ const controller = createRemoteAgentHandle({
+ client: {} as RemoteAgentRunClient,
+ started: { id: 'sdk-1', agentKind: 'claude-code', model: 'm', shadowDir: virtual, virtualWorkspace: true, methods: [], state: {} },
+ workspace, mapEvent: mapClaudeHostedEvent, recordApproval: () => {}, newId: () => 'request-id', dispose: async () => {},
+ });
+ return { real, workspace, controller };
+}
+
+async function eventsFrom(controller: ReturnType<typeof setup>['controller'], input: AgentEvent[]) {
+ const original = structuredClone(input);
+ for (const event of input) controller.onEvent(event);
+ controller.onClosed('closed');
+ const output: AgentEvent[] = [];
+ for await (const event of controller.handle.events()) output.push(event);
+ expect(input).toEqual(original);
+ return output;
+}
+
+function text(event: AgentEvent): string { return (event.data as { text: string }).text; }
+
+function remoteFileUrl(value: string): string {
+ return 'file://' + (/^[A-Za-z]:/.test(value) ? '/' : '') + value.replace(/\\/g, '/').split('/').map(encodeURIComponent).join('/').replace(/^([/]*[A-Za-z])%3A/, '$1:');
+}
+
+describe('remote file references on the task computer', () => {
+ it.each(['/Users/agent/workspace', '/home/agent/workspace', 'C:\\Agent\\workspace'])('opens a file generated at %s from its file card, tool result and reply link', async (virtual) => {
+ const { real, workspace, controller } = setup(virtual);
+ const native = virtual.startsWith('C:') ? path.win32 : path.posix;
+ const target = native.join(virtual, '报告 文件.txt');
+ const local = path.join(real, '报告 文件.txt');
+ const executor = new RemoteExecutor({ workspace, gate: new ExecutorGate(workspace, 'normal'), rgPath: 'unused' });
+ try {
+ await executor.callTool('Write', { file_path: target, content: 'remote-provider-result' });
+ const result = await executor.callTool('Read', { file_path: target });
+ expect(result.content).toEqual([{ type: 'text', text: '1\tremote-provider-result' }]);
+ const output = await eventsFrom(controller, [
+ { type: 'tool_use', source: 'claude-code', data: { toolUseId: 'write-id', toolName: 'mcp__cindy_exec__Write', input: { file_path: target, content: 'remote-provider-result' } } },
+ { type: 'tool_result_full', source: 'claude-code', data: { toolUseId: 'write-id', fullText: JSON.stringify({ path: target, url: remoteFileUrl(target) }), isError: false } },
+ { type: 'text', source: 'claude-code', data: { text: '[报告](<' + remoteFileUrl(target) + '>)', isFinal: true } },
+ ]);
+ const tool = output[0].data as { toolName: string; input: { file_path: string } };
+ const files = collectGeneratedFiles([{ role: 'tool_use', toolName: tool.toolName, toolInput: tool.input }], real);
+ expect(files.map((file) => file.path)).toEqual([local]);
+ expect(fs.readFileSync(resolveToolFilePath(files[0].path, real), 'utf8')).toBe('remote-provider-result');
+ expect(JSON.parse((output[1].data as { fullText: string }).fullText)).toEqual({ path: local, url: pathToFileURL(local).href });
+ const replyUrl = text(output[2]).slice('[报告](<'.length, -2);
+ expect(fs.readFileSync(fileURLToPath(replyUrl), 'utf8')).toBe('remote-provider-result');
+ } finally {
+ await executor.close();
+ }
+ });
+
+ it.each(['/Users/agent/Library/Application Support/workspace', 'C:\\Agent\\工作 目录'])('restores links and inline paths split across single-character deltas at %s', async (virtual) => {
+ const { real, controller } = setup(virtual);
+ const native = virtual.startsWith('C:') ? path.win32 : path.posix;
+ const target = native.join(virtual, '中文 空格', 'report.md');
+ const local = path.join(real, '中文 空格', 'report.md');
+ fs.mkdirSync(path.dirname(local), { recursive: true });
+ fs.writeFileSync(local, 'generated report');
+ const reply = '文件在 ' + '\x60' + target + '\x60' + ',打开[报告](<' + remoteFileUrl(target) + '#L2>)。';
+ const output = await eventsFrom(controller, [...reply].map((character) => ({
+ type: 'text', source: 'codex', data: { text: character, isFinal: false, agentMessageId: 'message-1' },
+ })));
+ expect(output.map(text).join('')).toBe('文件在 ' + '\x60' + local + '\x60' + ',打开[报告](<' + pathToFileURL(local).href + '#L2>)。');
+ expect(output.every((event) => (event.data as { isFinal: boolean }).isFinal === false)).toBe(true);
+ });
+
+ it.each(['/home/agent/workspace', 'C:\\Agent\\workspace'])('maps inline command paths without rewriting arguments at %s', async (virtual) => {
+ const { real, controller } = setup(virtual);
+ const native = virtual.startsWith('C:') ? path.win32 : path.posix;
+ const remote = native.join(virtual, 'run.sh');
+ const second = native.join(virtual, 'src', 'input.txt');
+ const output = await eventsFrom(controller, [' --url /api/v1', ' relative/input.txt', ' && cat ' + second].map((suffix) => ({
+ type: 'text', source: 'codex', data: { text: '\x60' + remote + suffix + '\x60', isFinal: true },
+ })));
+ expect(output.map(text)).toEqual([
+ '\x60' + path.join(real, 'run.sh') + ' --url /api/v1\x60',
+ '\x60' + path.join(real, 'run.sh') + ' relative/input.txt\x60',
+ '\x60' + path.join(real, 'run.sh') + ' && cat ' + path.join(real, 'src', 'input.txt') + '\x60',
+ ]);
+ });
+
+ it('keeps plain text live, flushes unfinished paths before tools and close, and separates message identities', async () => {
+ const virtual = '/Users/agent/workspace';
+ const { real, controller } = setup(virtual);
+ const output = await eventsFrom(controller, [
+ { type: 'text', source: 'codex', data: { text: '正在生成。', isFinal: false, agentMessageId: 'one' } },
+ { type: 'text', source: 'codex', data: { text: virtual + '/first.txt', isFinal: false, agentMessageId: 'one' } },
+ { type: 'tool_use', source: 'codex', data: { toolName: 'exec_command', input: { cmd: 'echo done' } } },
+ { type: 'text', source: 'codex', data: { text: virtual + '/second.txt', isFinal: false, agentMessageId: 'two' } },
+ { type: 'text', source: 'codex', data: { text: '下一条', isFinal: false, agentMessageId: 'three' } },
+ { type: 'text', source: 'codex', data: { text: virtual + '/last.txt', isFinal: false, agentMessageId: 'three' } },
+ ]);
+ expect(output.map((event) => event.type === 'text' ? text(event) : event.type)).toEqual([
+ '正在生成。', path.join(real, 'first.txt'), 'tool_use', path.join(real, 'second.txt'), '下一条', path.join(real, 'last.txt'),
+ ]);
+ expect((output[3].data as { agentMessageId: string }).agentMessageId).toBe('two');
+ });
+
+ it('keeps interleaved Claude child deltas in their own path buffers and metadata', async () => {
+ const virtual = '/Users/agent/workspace';
+ const { real, controller } = setup(virtual);
+ const delta = (parentUuid: string, value: string): AgentEvent => ({
+ type: 'text', source: 'claude-code', turnScope: 'turn', agentMeta: { parentUuid }, data: { text: value, isFinal: false },
+ });
+ const output = await eventsFrom(controller, [
+ delta('child-a', 'A: ' + virtual.slice(0, 12)),
+ delta('child-b', 'B: ' + virtual + '/second'),
+ delta('child-a', virtual.slice(12) + '/first.txt '),
+ delta('child-b', '.txt '),
+ ]);
+ expect(output.filter((event) => event.agentMeta?.parentUuid === 'child-a').map(text).join(''))
+ .toBe('A: ' + path.join(real, 'first.txt') + ' ');
+ expect(output.filter((event) => event.agentMeta?.parentUuid === 'child-b').map(text).join(''))
+ .toBe('B: ' + path.join(real, 'second.txt') + ' ');
+ expect(output.every((event) => (event.data as { isFinal: boolean }).isFinal === false)).toBe(true);
+ });
+
+ it('keeps sibling paths pending across another child final snapshot and tool boundary', async () => {
+ const virtual = '/Users/agent/workspace';
+ const { real, controller } = setup(virtual);
+ const child = (parentUuid: string, value: string, isFullText = false): AgentEvent => ({
+ type: 'text', source: 'claude-code', agentMeta: { parentUuid, ...(isFullText ? { sdkSessionId: 'vendor-session' } : {}) }, data: { text: value, isFinal: isFullText, isFullText },
+ });
+ const output = await eventsFrom(controller, [
+ child('child-a', virtual.slice(0, 12)),
+ child('child-b', virtual + '/second'),
+ child('child-b', virtual + '/second.txt', true),
+ { type: 'tool_use', source: 'claude-code', agentMeta: { parentUuid: 'child-b' }, data: { toolName: 'Read', input: {} } },
+ child('child-a', virtual.slice(12) + '/first.txt '),
+ ]);
+ expect(output.filter((event) => event.type === 'text' && event.agentMeta?.parentUuid === 'child-a').map(text).join(''))
+ .toBe(path.join(real, 'first.txt') + ' ');
+ expect(output.filter((event) => event.type === 'text' && event.agentMeta?.parentUuid === 'child-b').map(text))
+ .toEqual([path.join(real, 'second.txt')]);
+ });
+
+ it.each(['done', 'close'] as const)('flushes every unfinished child path at the %s boundary', async (boundary) => {
+ const virtual = '/Users/agent/workspace';
+ const { real, controller } = setup(virtual);
+ const input: AgentEvent[] = ['child-a', 'child-b'].map((parentUuid) => ({
+ type: 'text', source: 'claude-code', agentMeta: { parentUuid }, data: { text: virtual + '/' + parentUuid + '.txt', isFinal: false },
+ }));
+ if (boundary === 'done') input.push({ type: 'done', source: 'claude-code', data: {} });
+ const output = await eventsFrom(controller, input);
+ expect(output.filter((event) => event.type === 'text').map((event) => ({ parentUuid: event.agentMeta?.parentUuid, text: text(event) })))
+ .toEqual(['child-a', 'child-b'].map((parentUuid) => ({ parentUuid, text: path.join(real, parentUuid + '.txt') })));
+ if (boundary === 'done') expect(output.at(-1)?.type).toBe('done');
+ });
+
+ it('restores nested file changes and media file URLs while preserving external URLs, media identities and vendor metadata', async () => {
+ const virtual = '/Users/agent/workspace';
+ const { real, controller } = setup(virtual);
+ const remote = virtual + '/image space.png';
+ const xdt = 'xdt-file://local/?path=' + encodeURIComponent(remote);
+ const external = 'https://example.com' + virtual + '/file.txt';
+ const vendorMetadata = { uuid: virtual + '/vendor-id', parentUuid: 'parent' };
+ const input: AgentEvent[] = [
+ { type: 'tool_use', source: 'codex', agentMeta: vendorMetadata, data: {
+ toolUseId: virtual + '/tool-id', toolName: 'file_change',
+ input: { changes: [{ kind: 'add', path: virtual + '/report.txt' }, { kind: 'update', path: virtual + '/old.txt', movePath: virtual + '/new.txt' }] },
+ } },
+ { type: 'image', source: 'codex', data: { url: xdt, sourcePath: remote, mediaId: 'cindy-media://blobs/opaque.png', external } },
+ { type: 'text', source: 'pi', data: { text: '[图片](' + xdt + ') [网址](' + external + ')', isFinal: true, isFullText: true } },
+ ];
+ const output = await eventsFrom(controller, input);
+ expect(output[0].agentMeta).toBe(vendorMetadata);
+ expect(output[0].data).toMatchObject({ toolUseId: virtual + '/tool-id', input: { changes: [
+ { path: path.join(real, 'report.txt') }, { path: path.join(real, 'old.txt'), movePath: path.join(real, 'new.txt') },
+ ] } });
+ const image = output[1].data as { url: string; external: string; mediaId: string };
+ expect(new URL(image.url).searchParams.get('path')).toBe(path.join(real, 'image space.png'));
+ expect(image.external).toBe(external);
+ expect(image.mediaId).toBe('cindy-media://blobs/opaque.png');
+ expect(text(output[2])).toBe('[图片](' + image.url + ') [网址](' + external + ')');
+ });
+
+ it.each(['/home/agent/workspace', 'C:\\Agent\\workspace'])('restores JSON scalar paths and nested path arrays without normalizing quoted prose at %s', async (virtual) => {
+ const { real, controller } = setup(virtual);
+ const native = virtual.startsWith('C:') ? path.win32 : path.posix;
+ const target = native.join(virtual, '目录 空格', 'a.txt');
+ const local = path.join(real, '目录 空格', 'a.txt');
+ fs.mkdirSync(path.dirname(local));
+ fs.writeFileSync(local, 'existing file');
+ const prose = 'The docs say "' + native.join(virtual, 'README.md') + ' links to /api/v1"';
+ const original = { paths: [target, [target]], nested: { file_paths: [target] }, text: prose, links: [remoteFileUrl(target)] };
+ const output = await eventsFrom(controller, [target, [target], original].map((value) => ({
+ type: 'tool_result_full', source: 'claude-code', data: { toolUseId: 'result', fullText: JSON.stringify(value) },
+ })));
+ expect(output.map((event) => JSON.parse((event.data as { fullText: string }).fullText))).toEqual([local, [local], {
+ paths: [local, [local]], nested: { file_paths: [local] }, text: 'The docs say "' + path.join(real, 'README.md') + ' links to /api/v1"', links: [pathToFileURL(local).href],
+ }]);
+ });
+
+ it.each(['/home/agent/workspace', 'C:\\Agent\\workspace'])('preserves prose in JSON scalar and array tool results at %s', async (virtual) => {
+ const { real, controller } = setup(virtual);
+ const native = virtual.startsWith('C:') ? path.win32 : path.posix;
+ const prose = native.join(virtual, 'README.md') + ' links to /api/v1 and relative/input.txt';
+ const expected = path.join(real, 'README.md') + ' links to /api/v1 and relative/input.txt';
+ const output = await eventsFrom(controller, [prose, [prose, [prose]], JSON.stringify([prose])].map((value) => ({
+ type: 'tool_result_full', source: 'claude-code', data: { toolUseId: 'result', fullText: JSON.stringify(value) },
+ })));
+ expect(output.map((event) => JSON.parse((event.data as { fullText: string }).fullText)))
+ .toEqual([expected, [expected, [expected]], JSON.stringify([expected])]);
+ });
+
+ it('uses updated aliases and leaves permission requests and non-aliased paths unchanged', async () => {
+ const virtual = '/Users/agent/workspace';
+ const { real, workspace, controller } = setup(virtual);
+ const additional = '/Users/agent/additional';
+ workspace.setAliases([{ from: virtual, to: real }, { from: additional, to: path.join(root, 'extra') }]);
+ const permission = { toolName: 'Read', input: { file_path: virtual + '/report.txt' } };
+ const output = await eventsFrom(controller, [
+ { type: 'text', source: 'claude-code', data: { text: additional + '/new.txt', isFinal: true } },
+ { type: 'interaction_request', source: 'claude-code', data: permission },
+ { type: 'tool_use', source: 'claude-code', data: { toolName: 'Read', input: { file_path: '/unmapped/file.txt' } } },
+ ]);
+ expect(text(output[0])).toBe(path.join(root, 'extra', 'new.txt'));
+ expect(output[1].data).toEqual(permission);
+ expect(output[2].data).toMatchObject({ input: { file_path: '/unmapped/file.txt' } });
+ });
+
+ it('keeps an unfinished reply path across a standalone background notice', async () => {
+ const virtual = '/Users/agent/workspace';
+ const { real, controller } = setup(virtual);
+ const output = await eventsFrom(controller, [
+ { type: 'text', source: 'pi', data: { text: '[报告](<file:///Users/agent/work', isFinal: false } },
+ { type: 'text', source: 'pi', standaloneText: true, turnScope: 'background', backgroundTurnStartedAt: 1000,
+ data: { text: '后台文件:\x60' + virtual + '/background.txt\x60', isFinal: true } },
+ { type: 'tool_result', source: 'pi', turnScope: 'background', data: { summary: '后台读取完成' } },
+ { type: 'text', source: 'pi', data: { text: 'space/report.txt>)', isFinal: false } },
+ { type: 'done', source: 'pi', data: {} },
+ ]);
+ expect(output.filter((event) => event.type === 'text' && !event.standaloneText).map(text).join(''))
+ .toBe('[报告](<' + pathToFileURL(path.join(real, 'report.txt')).href + '>)');
+ expect(output.find((event) => event.standaloneText)).toMatchObject({
+ turnScope: 'background', backgroundTurnStartedAt: 1000,
+ data: { text: '后台文件:\x60' + path.join(real, 'background.txt') + '\x60', isFinal: true },
+ });
+ });
+
+ it.each(['tool_use', 'tool_result', 'done', 'error', 'compact_boundary', 'status'] as const)('flushes only the matching background stream before %s', async (boundary) => {
+ const virtual = '/Users/agent/workspace';
+ const { real, controller } = setup(virtual);
+ const foreground: AgentEvent = { type: 'text', source: 'pi', data: { text: virtual.slice(0, 12), isFinal: false } };
+ const background: AgentEvent = {
+ type: 'text', source: 'pi', turnScope: 'background', backgroundTurnStartedAt: 1000,
+ data: { text: virtual + '/background.txt', isFinal: false },
+ };
+ const output = await eventsFrom(controller, [
+ foreground, background,
+ { ...background, backgroundTurnStartedAt: 2000, data: { text: virtual.slice(0, 12), isFinal: false } },
+ { ...background, type: boundary, data: boundary === 'status' ? { isRunning: false } : {} },
+ { ...foreground, data: { text: virtual.slice(12) + '/foreground.txt ', isFinal: false } },
+ { ...background, backgroundTurnStartedAt: 2000, data: { text: virtual.slice(12) + '/other.txt ', isFinal: false } },
+ ]);
+ expect(output.map((event) => event.type === 'text' ? text(event) : event.type)).toEqual([
+ path.join(real, 'background.txt'), boundary,
+ path.join(real, 'foreground.txt') + ' ', path.join(real, 'other.txt') + ' ',
+ ]);
+ expect(output[0]).toMatchObject({ turnScope: 'background', backgroundTurnStartedAt: 1000 });
+ expect(output[3]).toMatchObject({ turnScope: 'background', backgroundTurnStartedAt: 2000 });
+ });
+
+ it.each([
+ { message: 'retrying', isTerminal: false },
+ { message: 'retrying', willRetry: true },
+ ])('keeps background paths pending across a recoverable foreground error (%j)', async (errorData) => {
+ const virtual = '/Users/agent/workspace';
+ const { real, controller } = setup(virtual);
+ const output = await eventsFrom(controller, [
+ { type: 'text', source: 'pi', turnScope: 'background', backgroundTurnStartedAt: 1000,
+ data: { text: virtual.slice(0, 12), isFinal: false } },
+ { type: 'error', source: 'pi', data: errorData },
+ { type: 'text', source: 'pi', turnScope: 'background', backgroundTurnStartedAt: 1000,
+ data: { text: virtual.slice(12) + '/background.txt ', isFinal: false } },
+ ]);
+ expect(output.map((event) => event.type === 'text' ? text(event) : event.type)).toEqual([
+ 'error', path.join(real, 'background.txt') + ' ',
+ ]);
+ });
+
+ it.each(['claude-code', 'codex', 'pi'] as const)('flushes all pending paths before foreground stopped status for %s without done or close', async (source) => {
+ const virtual = '/Users/agent/workspace';
+ const { real, controller } = setup(virtual);
+ const pending: AgentEvent[] = [
+ { type: 'text', source, data: { text: virtual + '/foreground.txt', isFinal: false } },
+ { type: 'text', source, agentMeta: { parentUuid: 'child' }, data: { text: virtual + '/child.txt', isFinal: false } },
+ { type: 'text', source, turnScope: 'background', backgroundTurnStartedAt: 1000, data: { text: virtual + '/background.txt', isFinal: false } },
+ ];
+ const stopped: AgentEvent = { type: 'status', source, data: { status: 'Done', isRunning: false, outputTokens: 7 } };
+ const input = [...pending, stopped];
+ const original = structuredClone(input);
+ try {
+ for (const event of input) controller.onEvent(event);
+ const output: AgentEvent[] = [];
+ for await (const event of controller.handle.events()) {
+ output.push(event);
+ if (event.type === 'status') break;
+ }
+ expect(output).toEqual([
+ ...pending.map((event) => ({ ...event, data: { ...event.data as object, text: path.join(real, path.posix.basename(text(event))) } })),
+ stopped,
+ ]);
+ expect(input).toEqual(original);
+ } finally {
+ controller.onClosed('closed');
+ }
+ });
+
+ it('flushes only the matching child path before stopped status', async () => {
+ const virtual = '/Users/agent/workspace';
+ const { real, controller } = setup(virtual);
+ const foreground: AgentEvent = { type: 'text', source: 'claude-code', data: { text: virtual.slice(0, 12), isFinal: false } };
+ const child = (parentUuid: string, value: string): AgentEvent => ({
+ ...foreground, agentMeta: { parentUuid }, data: { text: value, isFinal: false },
+ });
+ const stopped: AgentEvent = {
+ type: 'status', source: 'claude-code', agentMeta: { parentUuid: 'child-a' }, data: { status: 'Done', isRunning: false },
+ };
+ const output = await eventsFrom(controller, [
+ foreground, child('child-a', virtual + '/first.txt'), child('child-b', virtual.slice(0, 12)), stopped,
+ { ...foreground, data: { text: virtual.slice(12) + '/foreground.txt ', isFinal: false } },
+ child('child-b', virtual.slice(12) + '/second.txt '),
+ ]);
+ expect(output.map((event) => event.type === 'text' ? text(event) : event.type)).toEqual([
+ path.join(real, 'first.txt'), 'status', path.join(real, 'foreground.txt') + ' ', path.join(real, 'second.txt') + ' ',
+ ]);
+ expect(output[0].agentMeta).toEqual({ parentUuid: 'child-a' });
+ expect(output[1]).toEqual(stopped);
+ expect(output[3].agentMeta).toEqual({ parentUuid: 'child-b' });
+ });
+
+ it.each([true, undefined])('keeps an unfinished path pending across status with isRunning=%s', async (isRunning) => {
+ const virtual = '/Users/agent/workspace';
+ const { real, controller } = setup(virtual);
+ const status: AgentEvent = { type: 'status', source: 'codex', data: { status: 'Done', ...(isRunning === undefined ? {} : { isRunning }) } };
+ const output = await eventsFrom(controller, [
+ { type: 'text', source: 'codex', data: { text: virtual.slice(0, 12), isFinal: false } },
+ status,
+ { type: 'text', source: 'codex', data: { text: virtual.slice(12) + '/report.txt ', isFinal: false } },
+ ]);
+ expect(output.map((event) => event.type === 'text' ? text(event) : event.type)).toEqual(['status', path.join(real, 'report.txt') + ' ']);
+ expect(output[0]).toEqual(status);
+ });
+
+ it.each(['claude-code', 'codex', 'pi'] as const)('preserves the calibrated final reply and stream flags for %s', async (source) => {
+ const virtual = '/Users/agent/workspace';
+ const { real, controller } = setup(virtual);
+ const raw = '[报告](<' + remoteFileUrl(virtual + '/report.txt') + '>)';
+ const final = { text: raw, isFinal: true, ...(source === 'claude-code' ? {} : { isFullText: true }), agentMessageId: 'message' };
+ const output = await eventsFrom(controller, [
+ { type: 'text', source, data: { text: raw.slice(0, -2), isFinal: false, agentMessageId: 'message' } },
+ { type: 'text', source, data: { text: raw.slice(-2), isFinal: false, agentMessageId: 'message' } },
+ { type: 'text', source, data: final },
+ { type: 'done', source, data: {} },
+ ]);
+ const expected = '[报告](<' + pathToFileURL(path.join(real, 'report.txt')).href + '>)';
+ expect(output.filter((event) => event.type === 'text' && !(event.data as { isFinal?: boolean }).isFinal).map(text).join('')).toBe(expected);
+ expect(output.find((event) => event.type === 'text' && (event.data as { isFinal?: boolean }).isFinal)?.data).toEqual({ ...final, text: expected });
+ });
+
+ it.each(['claude-code', 'codex', 'pi'] as const)('finishes a link from the final snapshot when the last %s deltas are missing', async (source) => {
+ const virtual = '/Users/agent/workspace';
+ const { real, controller } = setup(virtual);
+ const remote = virtual + '/中文 空格/report.md';
+ const local = path.join(real, '中文 空格', 'report.md');
+ fs.mkdirSync(path.dirname(local), { recursive: true });
+ fs.writeFileSync(local, 'generated report');
+ const raw = '报告在 \x60' + remote + '\x60 [打开](<' + remoteFileUrl(remote) + '>)';
+ const output = await eventsFrom(controller, [
+ { type: 'text', source, data: { text: '报告在 \x60/Users/ag', isFinal: false, agentMessageId: 'message' } },
+ { type: 'text', source, data: { text: raw, isFinal: true, ...(source === 'claude-code' ? {} : { isFullText: true }), agentMessageId: 'message' } },
+ { type: 'done', source, data: {} },
+ ]);
+ const streamed = output.filter((event) => event.type === 'text' && !(event.data as { isFinal?: boolean }).isFinal).map(text).join('');
+ const final = output.find((event) => event.type === 'text' && (event.data as { isFinal?: boolean }).isFinal)!;
+ expect(text(final)).toBe('报告在 \x60' + local + '\x60 [打开](<' + pathToFileURL(local).href + '>)');
+ // Claude 的非 isFullText 终态仅在正文仍是其前缀时才会补齐持久消息。
+ expect(text(final).startsWith(streamed)).toBe(true);
+ expect(streamed).not.toContain('/Users/ag');
+ });
+});
diff --git a/apps/desktop/src/main/remote-agent/controller/eventProjection.ts b/apps/desktop/src/main/remote-agent/controller/eventProjection.ts
new file mode 100644
index 0000000000..a60ac64f79
--- /dev/null
+++ b/apps/desktop/src/main/remote-agent/controller/eventProjection.ts
@@ -0,0 +1,184 @@
+/** 远程事件落库和广播前还原文件引用;不改 Agent 的原生会话或执行权限。 */
+import fs from 'node:fs';
+import { pathToFileURL } from 'node:url';
+
+import { isTerminalAgentErrorEvent, type AgentEvent } from '@cindy/maker-core';
+
+import { mapJsonPathText, pathTextContext, type ExecutorWorkspace, type PathTextContext } from '../executor/workspace';
+
+const URL_TEXT = /[a-z][a-z0-9+.-]*:\/\/[^\s\x60"'<>()[\]{}]+/gi;
+const TEXT_BOUNDARIES = new Set(['tool_use', 'tool_result', 'tool_result_full', 'interaction_request', 'done', 'error', 'compact_boundary']);
+const IDENTITY_FIELDS = new Set(['id', 'toolUseId', 'toolUseIds', 'agentMessageId', 'taskId', 'parentToolUseId', 'turnId', 'requestId', 'blockId', 'sessionId', 'sdkSessionId', 'toolName', 'lastToolName', 'model', 'providerId']);
+
+function localFileUrl(value: string, workspace: ExecutorWorkspace): string {
+ try {
+ const url = new URL(value);
+ if (url.protocol === 'file:') {
+ // 不能用本机平台的 fileURLToPath 解析另一台电脑的 Windows/POSIX URL。
+ const remote = url.hostname
+ ? '//' + url.hostname + decodeURIComponent(url.pathname)
+ : decodeURIComponent(url.pathname).replace(/^\/(?=[A-Za-z]:[\\/])/, '');
+ const local = workspace.mapAlias(remote);
+ if (local === remote) return value;
+ const result = pathToFileURL(local);
+ result.search = url.search;
+ result.hash = url.hash;
+ return result.href;
+ }
+ if (url.protocol === 'xdt-file:' || url.protocol === 'xdt-audio:') {
+ const remote = url.searchParams.get('path');
+ if (!remote) return value;
+ const local = workspace.mapAlias(remote);
+ if (local === remote) return value;
+ url.searchParams.set('path', local);
+ return url.href;
+ }
+ } catch { /* 普通文本和无法解析的 URL 保持既有行为。 */ }
+ return value;
+}
+
+function localText(value: string, workspace: ExecutorWorkspace, context: PathTextContext = 'text'): string {
+ // 先处理 JSON 字符串,保留 Windows 转义、正文格式和非字符串字节。
+ if (/^\s*[{["]/.test(value)) {
+ try {
+ return mapJsonPathText(value, (decoded, context) => {
+ const local = workspace.mapAlias(decoded);
+ const complete = context === 'path' || ((context === 'untyped' || context === 'ambiguous-path')
+ && local !== decoded && fs.existsSync(local));
+ return localText(complete ? local : decoded, workspace, context);
+ });
+ } catch { /* 非 JSON 按文件引用投影。 */ }
+ }
+ // 尖括号链接是明确的完整路径。代码段也可能是命令,含空白时只有已存在的完整
+ // 文件/目录才按单一路径处理;其余回到下方逐 token 投影,保留参数和正文中的斜杠。
+ value = value.replace(/\x60([^\x60\r\n]+)\x60|<([^<>\r\n]+)>/g, (literal, code: string | undefined, angle: string | undefined) => {
+ const remote = code ?? angle!;
+ const local = workspace.mapAlias(remote);
+ if (code !== undefined && local !== remote && /\s/.test(remote) && !fs.existsSync(local)) return literal;
+ return local === remote ? literal : code !== undefined ? '\x60' + local + '\x60' : '<' + local + '>';
+ });
+ // URL 单独解析;HTTP 与媒体仓标识不得被普通路径替换改写。
+ const parts: string[] = [];
+ let end = 0;
+ for (const match of value.matchAll(URL_TEXT)) {
+ parts.push(workspace.mapTextFromAgent(value.slice(end, match.index), context), localFileUrl(match[0], workspace));
+ end = match.index! + match[0].length;
+ }
+ parts.push(workspace.mapTextFromAgent(value.slice(end), context));
+ return parts.join('');
+}
+
+function localValue(value: unknown, workspace: ExecutorWorkspace, key = ''): unknown {
+ if (typeof value === 'string') return localText(value, workspace, pathTextContext(key));
+ if (Array.isArray(value)) return value.map((item) => localValue(item, workspace, key));
+ if (!value || typeof value !== 'object') return value;
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, IDENTITY_FIELDS.has(key) ? item : localValue(item, workspace, key)]));
+}
+
+/** 只暂存末尾未闭合的路径,避免地址被多个 delta 切开后漏掉映射。 */
+function pendingPathIndex(text: string, workspace: ExecutorWorkspace): number {
+ let pending = text.length;
+ const prefixes = workspace.agentPathPrefixes().flatMap((prefix) => {
+ const forward = prefix.replace(/\\/g, '/');
+ const backward = forward.replace(/\//g, '\\');
+ return [forward, backward, backward.replace(/\\/g, '\\\\')];
+ });
+ if (!prefixes.length) return pending;
+ // 完整 URL 出现前保留 scheme,才能在后续 delta 中判断文件 URL 或外部 URL。
+ prefixes.push('file://', 'xdt-file://', 'xdt-audio://', 'http://', 'https://', 'cindy-media://');
+ for (const prefix of prefixes) {
+ const insensitive = /^[A-Za-z]:|^[a-z-]+:\/\//i.test(prefix);
+ const source = insensitive ? text.toLowerCase() : text;
+ const target = insensitive ? prefix.toLowerCase() : prefix;
+ let start = -1;
+ while ((start = source.indexOf(target[0], start + 1)) >= 0) {
+ if (start && /[A-Za-z0-9_]/.test(text[start - 1])) continue;
+ const tail = source.slice(start);
+ const quote = text[start - 1];
+ const closing = quote === '<' ? '>' : /["'\x60]/.test(quote ?? '') ? quote : undefined;
+ if (target.startsWith(tail)) {
+ pending = Math.min(pending, closing ? start - 1 : start);
+ continue;
+ }
+ if (!tail.startsWith(target)) continue;
+ if (!prefix.includes('://') && !/^[\\/]/.test(tail.slice(target.length))) continue;
+ const suffix = text.slice(start + target.length);
+ const ended = closing ? suffix.includes(closing) : prefix.includes('://')
+ ? /[\s\x60"'<>()[\]{}]/.test(suffix) : /[\s\x60"'<>()[\]{};|&]/.test(suffix);
+ if (!ended) {
+ pending = Math.min(pending, closing ? start - 1 : start);
+ }
+ }
+ }
+ // 引号可能独占一个 delta;保留开引号,下一段路径才能按完整引用(含空格)解析。
+ const trailing = text.at(-1);
+ if (pending === text.length && trailing && /["'\x60<]/.test(trailing)
+ && (trailing === '<' || text.split(trailing).length % 2 === 0)) pending = text.length - 1;
+ return pending;
+}
+
+/** 保留原事件身份和增量/全文语义;仅把数据中的已知虚拟文件引用还原。 */
+export class RemoteEventProjection {
+ private pending = new Map<string, AgentEvent>();
+
+ constructor(private readonly workspace: ExecutorWorkspace) {}
+
+ private streamKey(event: AgentEvent): string {
+ return JSON.stringify([event.source, event.turnScope, event.agentMeta?.parentUuid,
+ event.turnAttemptToken, event.sessionTurnGeneration, event.sessionInstanceId, event.backgroundTurnStartedAt]);
+ }
+
+ flush(stream?: string): AgentEvent[] {
+ const output: AgentEvent[] = [];
+ for (const key of stream === undefined ? this.pending.keys() : [stream]) {
+ const event = this.pending.get(key);
+ if (!event) continue;
+ this.pending.delete(key);
+ output.push({ ...event, data: localValue(event.data, this.workspace) });
+ }
+ return output;
+ }
+
+ project(event: AgentEvent): AgentEvent[] {
+ const data = event.data as { text?: unknown; isFinal?: boolean; isFullText?: boolean; isRunning?: boolean; agentMessageId?: string } | null;
+ const stream = this.streamKey(event);
+ let pending = this.pending.get(stream);
+ // 独立提示有自己的持久行,不能截断正在流式传输的正文路径。
+ if (event.type === 'text' && event.standaloneText) {
+ return [{ ...event, data: localValue(event.data, this.workspace) }];
+ }
+ if (event.type === 'text' && typeof data?.text === 'string' && !data.isFinal && !data.isFullText && !event.standaloneText) {
+ const output: AgentEvent[] = [];
+ if (pending) {
+ const previous = pending.data as typeof data;
+ if (previous?.agentMessageId !== data.agentMessageId) {
+ output.push(...this.flush(stream));
+ pending = undefined;
+ }
+ }
+ const raw = (pending?.data as typeof data)?.text;
+ const text = (typeof raw === 'string' ? raw : '') + data.text;
+ const boundary = pendingPathIndex(text, this.workspace);
+ if (boundary < text.length) this.pending.set(stream, { ...event, data: { ...data, text: text.slice(boundary) } });
+ else this.pending.delete(stream);
+ if (boundary) output.push({ ...event, data: { ...data, text: localText(text.slice(0, boundary), this.workspace) } });
+ return output;
+ }
+ // 全文终态覆盖同一消息的未闭合尾段;先输出半截虚拟前缀会让 Claude 的前缀校准失效。
+ if (event.type === 'text' && pending && typeof data?.text === 'string' && (data.isFinal || data.isFullText)) {
+ const previous = pending.data as typeof data;
+ if (previous?.agentMessageId === data.agentMessageId
+ && (data.isFullText || (typeof previous.text === 'string' && data.text.includes(previous.text)))) this.pending.delete(stream);
+ }
+ // Agent 可先发停止状态,且不一定随后有 done;正文必须在停止状态前送出。
+ const stopped = event.type === 'status' && data?.isRunning === false;
+ const terminal = !event.agentMeta?.parentUuid && event.turnScope !== 'background'
+ && (stopped || ['done', 'compact_boundary'].includes(event.type)
+ || (event.type === 'error' && isTerminalAgentErrorEvent(event)));
+ const output = event.type === 'text' || stopped || TEXT_BOUNDARIES.has(event.type)
+ ? this.flush(terminal ? undefined : stream) : [];
+ // agentMeta、session/tool id 和权限回执不经过递归文本改写。
+ output.push({ ...event, data: event.type === 'interaction_request' ? event.data : localValue(event.data, this.workspace) });
+ return output;
+ }
+}
diff --git a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts b/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts
index 5c4941e9de..c857dd19fa 100644
--- a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts
+++ b/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts
@@ -30,6 +30,7 @@ import type { ExecutorWorkspace } from '../executor/workspace';
import { isProviderShareCredentialSessionApproval } from '../../../shared/providerShareCredentialConsent';
import { encodeSendOptions, encodeUserMessage } from '../wire';
import { RemoteAgentRemoteError, type RemoteAgentRunClient } from './runClient';
+import { RemoteEventProjection } from './eventProjection';
const MAX_REMEMBERED_SEND_CALLBACKS = 64;
@@ -216,6 +217,7 @@ export interface RemoteAgentHandleController {
export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHandleController {
const { client, started } = deps;
const queue = new EventQueue();
+ const projection = new RemoteEventProjection(deps.workspace);
let state: Record<string, unknown> = { ...started.state };
let resolver: InteractionResolver | null = null;
let disposed = false;
@@ -229,6 +231,7 @@ export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHand
const dispose = async () => {
if (disposed) return;
disposed = true;
+ for (const projected of projection.flush()) queue.push(projected);
queue.end();
await deps.dispose().catch(() => undefined);
};
@@ -412,7 +415,7 @@ export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHand
onEvent(event) {
if (!event || typeof event !== 'object' || typeof (event as AgentEvent).type !== 'string') return;
const typed = event as AgentEvent;
- queue.push(deps.mapEvent ? deps.mapEvent(typed) : typed);
+ for (const projected of projection.project(deps.mapEvent ? deps.mapEvent(typed) : typed)) queue.push(projected);
},
onState(next) {
state = { ...state, ...next };
@@ -453,6 +456,7 @@ export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHand
return true;
},
onClosed(reason, message) {
+ for (const projected of projection.flush()) queue.push(projected);
// 'superseded':同一任务被重新打开、旧实例让位给新实例,不是错误,静默收起。
if (reason !== 'closed' && reason !== 'detached' && reason !== 'ended' && reason !== 'superseded') {
queue.push({
diff --git a/apps/desktop/src/main/remote-agent/controller/router.ts b/apps/desktop/src/main/remote-agent/controller/router.ts
index 1391b5fda9..1cc0bece6f 100644
--- a/apps/desktop/src/main/remote-agent/controller/router.ts
+++ b/apps/desktop/src/main/remote-agent/controller/router.ts
@@ -14,6 +14,7 @@ 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';
+import { pathTextContext } from '../executor/workspace';
/** 本任务可用的一个本机 MCP 服务:完整地址(已带本任务身份)与要附加的请求头。 */
export interface LocalMcpTarget {
@@ -31,6 +32,15 @@ export interface ReverseHttpRouterDeps {
const FORWARD_REQUEST_HEADERS = new Set(['content-type', 'accept', 'mcp-session-id', 'mcp-protocol-version', 'last-event-id']);
const FORWARD_RESPONSE_HEADERS = new Set(['content-type', 'mcp-session-id', 'mcp-protocol-version']);
+/** 本机工具已有的路径参数;兼容 MCP snake_case 与宿主 camelCase,正文和插件业务参数不做文本替换。 */
+const PATH_ARGUMENTS = new Set([
+ 'path', 'paths', 'filepath', 'filepaths', 'directory', 'directories', 'dir', 'dirs',
+ 'workingdir', 'workdir', 'cwd', 'root', 'libraryroot', 'sourcepath', 'destinationpath',
+ 'savedir', 'outpath', 'htmlpath', 'imagepath', 'iconsource', 'attachments', 'extradirs', 'writabledirs',
+ 'debugimageout',
+]);
+const WORKBENCH_PROJECT_TOOLS = new Set(['set_workbench_task', 'set_workbench_tasks']);
+
function json(status: number, value: unknown): Extract<RemoteAgentReply, { type: 'http' }> {
return {
type: 'http',
@@ -63,17 +73,30 @@ export function createReverseHttpRouter(deps: ReverseHttpRouterDeps) {
const doFetch = deps.fetch ?? fetch;
const workspace = deps.executor.workspace;
- const mapArguments = (value: unknown, key = ''): unknown => {
+ const mapArguments = (value: unknown, key = '', toolName = ''): unknown => {
if (typeof value === 'string') {
+ if (key === 'args') {
+ try {
+ const parsed = JSON.parse(value);
+ if (parsed && typeof parsed === 'object') return JSON.stringify(mapArguments(parsed, '', toolName));
+ } catch { /* 普通字符串参数保持原样。 */ }
+ }
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);
+ const fieldContext = pathTextContext(key);
+ if (fieldContext === 'ambiguous-path') return workspace.mapTextFromAgent(value, fieldContext);
+ if (fieldContext === 'path'
+ || PATH_ARGUMENTS.has(key.replace(/_/g, '').toLowerCase())
+ || (key === 'project' && WORKBENCH_PROJECT_TOOLS.has(toolName))) return workspace.mapAlias(value);
return value;
}
- if (Array.isArray(value)) return value.map((item) => mapArguments(item, key));
+ if (Array.isArray(value)) return value.map((item) => mapArguments(item, key, toolName));
if (!value || typeof value !== 'object') return value;
- return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, mapArguments(item, name)]));
+ const effectiveToolName = toolName === 'call_tool' && typeof (value as Record<string, unknown>).name === 'string'
+ ? (value as Record<string, unknown>).name as string
+ : toolName;
+ return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, mapArguments(item, name, effectiveToolName)]));
};
- const projectResult = (value: unknown): unknown => {
+ const projectResult = (value: unknown, key = ''): unknown => {
if (typeof value === 'string') {
if (value.startsWith('file://')) {
try {
@@ -86,11 +109,11 @@ export function createReverseHttpRouter(deps: ReverseHttpRouterDeps) {
}
} catch { /* 普通字符串或非本机 file URL,交给文本投影。 */ }
}
- return workspace.mapTextForAgent(value);
+ return workspace.mapTextForAgent(value, pathTextContext(key));
}
- if (Array.isArray(value)) return value.map(projectResult);
+ if (Array.isArray(value)) return value.map((item) => projectResult(item, key));
if (!value || typeof value !== 'object') return value;
- return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, projectResult(item)]));
+ return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, projectResult(item, name)]));
};
async function forwardMcp(
@@ -112,7 +135,9 @@ export function createReverseHttpRouter(deps: ReverseHttpRouterDeps) {
...(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);
+ if (message.method === 'tools/call' && message.params?.arguments) {
+ message.params.arguments = mapArguments(message.params.arguments, '', message.params.name ?? '');
+ }
return Buffer.from(JSON.stringify(message));
} catch { return body; }
})()) } : {}),
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 3ec63d4af9..b46e495185 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
@@ -2,11 +2,16 @@ 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 { createComputerMcpServer, registerGetCurrentSessionIdTool, XdtHelperToolRegistry } from '@cindy/mcps';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { z } from 'zod';
import { mapExecServerParams, mapExecServerResult, execServerActions } from '../../controller/execServerRelay';
import { RemoteExecutor } from '../executor';
import { ExecutorGate } from '../gate';
+import { resolveExecutorShell, runOnce } from '../shell';
import { ExecutorWorkspace, projectPathText } from '../workspace';
import { createReverseHttpRouter } from '../../controller/router';
@@ -25,6 +30,41 @@ function setup(virtual: string) {
}
describe('virtual workspace', () => {
+ it.each([
+ { real: 'C:\\Users\\local\\real project', virtual: '/home/agent/workspace', realPath: path.win32, agentPath: path.posix },
+ { real: '/Users/local/real project', virtual: 'C:\\Agent\\workspace', realPath: path.posix, agentPath: path.win32 },
+ ])('round-trips serialized JSON paths from $real to $virtual without changing its format', ({ real, virtual, realPath, agentPath }) => {
+ const document = (directory: string, native: typeof path.win32) => [
+ '{',
+ ' "working_dir": ' + JSON.stringify(directory) + ',',
+ ' "file": ' + JSON.stringify(native.join(directory, 'src', 'a.ts')) + ',',
+ ' "spaced_file": ' + JSON.stringify(native.join(directory, '目录 空格', 'skill', 'probe.cjs')) + ',',
+ ' "encoded": ' + JSON.stringify(JSON.stringify({ cwd: directory })) + ',',
+ ' "untouched": "\\u4e2d\\u6587",',
+ ' "number": 1.00e0',
+ '}',
+ '',
+ ].join('\n');
+ const original = document(real, realPath);
+ const projected = projectPathText(original, [{ from: real, to: virtual }]);
+ expect(projected).toBe(document(virtual, agentPath));
+ expect(JSON.parse(JSON.parse(projected).encoded).cwd).toBe(virtual);
+ expect(projectPathText(projected, [{ from: virtual, to: real }])).toBe(original);
+ const log = 'Starting script\r\n' + JSON.stringify({ cwd: real }) + '\r\n' + JSON.stringify({ cwd: real }) + '\r\n';
+ const projectedLog = 'Starting script\r\n' + JSON.stringify({ cwd: virtual }) + '\r\n' + JSON.stringify({ cwd: virtual }) + '\r\n';
+ expect(projectPathText(log, [{ from: real, to: virtual }])).toBe(projectedLog);
+ expect(projectPathText(projectedLog, [{ from: virtual, to: real }])).toBe(log);
+ const nativeScript = realPath.join(real, '目录 空格', 'skill', 'probe.cjs');
+ const virtualScript = agentPath.join(virtual, '目录 空格', 'skill', 'probe.cjs');
+ expect(projectPathText(nativeScript, [{ from: real, to: virtual }], 'path')).toBe(virtualScript);
+ expect(projectPathText(nativeScript + '\r\n', [{ from: real, to: virtual }], 'path')).toBe(virtualScript + '\r\n');
+ expect(projectPathText(JSON.stringify(nativeScript), [{ from: real, to: virtual }], 'path')).toBe(JSON.stringify(virtualScript));
+ expect(projectPathText(JSON.stringify([nativeScript]), [{ from: real, to: virtual }], 'path')).toBe(JSON.stringify([virtualScript]));
+ expect(projectPathText(real + realPath.sep, [{ from: real, to: virtual }])).toBe(virtual + agentPath.sep);
+ expect(projectPathText(JSON.stringify({ message: 'Cannot load', path: nativeScript }), [{ from: real, to: virtual }]))
+ .toBe(JSON.stringify({ message: 'Cannot load', path: virtualScript }));
+ });
+
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;
@@ -55,6 +95,8 @@ describe('virtual workspace', () => {
.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(projectPathText('cat "/real/project/src/a.ts" && echo "/other/file"', [{ from: '/real/project', to: 'C:\\Agent\\workspace' }]))
+ .toBe('cat "C:\\Agent\\workspace\\src\\a.ts" && echo "/other/file"');
expect(workspace.mapTextForAgent(project)).toBe('/Users/agent/workspace');
if (process.platform === 'win32') {
const bashPath = '/' + project[0].toLowerCase() + project.slice(2).replace(/\\/g, '/');
@@ -79,6 +121,212 @@ describe('virtual workspace', () => {
await executor.close();
});
+ it('maps the complete quoted Windows script path after a directory containing spaces', async () => {
+ const virtual = 'C:\\Agent\\workspace';
+ const { workspace, project, executor } = setup(virtual);
+ const script = path.win32.join(virtual, '目录 空格', 'skill', 'probe.cjs');
+ const mapped = project.replace(/\\/g, '/') + '/目录 空格/skill/probe.cjs';
+ expect(workspace.mapCommand('node "' + script + '" && echo "/other/file"'))
+ .toBe('node "' + mapped + '" && echo "/other/file"');
+ await executor.close();
+ });
+
+ it.each([
+ '$file', '$' + '{file}', '$(printf "%s" "$file")', String.fromCharCode(96) + 'printf "%s" "$file"' + String.fromCharCode(96), '\\$file', '\\"quoted\\"', '*.txt',
+ ])('preserves Bash syntax in a quoted POSIX path suffix: %s', (expression) => {
+ const { project, workspace } = setup('/Users/agent/workspace');
+ const real = project.replace(/\\/g, '/');
+ const suffix = '/目录 空格/' + expression;
+ expect(workspace.mapCommand('cat "/Users/agent/workspace' + suffix + '"'))
+ .toBe('cat "' + real + suffix + '"');
+ });
+
+ it('preserves unquoted Bash expansions and quoted cmd variables after the mapped prefix', () => {
+ const { project, workspace } = setup('/Users/agent/workspace');
+ const real = project.replace(/\\/g, '/');
+ expect(workspace.mapCommand('cat /Users/agent/workspace/$file/*.txt'))
+ .toBe("cat '" + real + "'/$file/*.txt");
+ expect(workspace.mapCommand('cat "/Users/agent/workspace/目录 空格/%file%"', 'cmd'))
+ .toBe('cat "' + real + '/目录 空格/%file%"');
+ });
+
+ it('maps the Windows literal path before a Bash expansion without rewriting substitution contents', () => {
+ const virtual = 'C:\\Agent\\workspace';
+ const { project, workspace } = setup(virtual);
+ const expression = '$(printf "\\\\n%s" "$file")';
+ const command = 'cat "' + path.win32.join(virtual, '目录 空格') + '/' + expression + '"';
+ expect(workspace.mapCommand(command))
+ .toBe('cat "' + project.replace(/\\/g, '/') + '/目录 空格/' + expression + '"');
+ });
+
+ it.each(['\\"; printf UNEXPECTED; #', '\\\\\\"; printf UNEXPECTED; #', '\\$file', '\\' + String.fromCharCode(96) + 'literal'])('preserves shell escapes after a spaced Windows path: %s', (suffix) => {
+ const virtual = 'C:\\Agent\\workspace';
+ const { project, workspace } = setup(virtual);
+ const command = 'printf \'%s\\n\' "' + virtual + '\\dir space\\safe' + suffix + '"';
+ expect(workspace.mapCommand(command))
+ .toBe('printf \'%s\\n\' "' + project.replace(/\\/g, '/') + '/dir space/safe' + suffix + '"');
+ });
+
+ it.skipIf(resolveExecutorShell().dialect !== 'bash')('keeps escaped command-looking text in one Bash argument after mapping', async () => {
+ const virtual = 'C:\\Agent\\workspace';
+ const { project, workspace } = setup(virtual);
+ const command = 'printf \'<%s>\\n\' "' + virtual + '\\dir space\\safe\\"; printf UNEXPECTED; #"';
+ const result = await runOnce(command + '\n' + workspace.mapCommand(command), { cwd: project });
+ expect(result.exitCode).toBe(0);
+ expect(result.output.toString('utf8'))
+ .toBe('<' + virtual + '\\dir space\\safe"; printf UNEXPECTED; #>\n'
+ + '<' + project.replace(/\\/g, '/') + '/dir space/safe"; printf UNEXPECTED; #>\n');
+ });
+
+ it.each([
+ { from: '/real/project', to: 'C:\\Agent\\workspace', source: path.posix, target: path.win32 },
+ { from: 'C:\\Agent\\workspace', to: '/real/project', source: path.win32, target: path.posix },
+ ])('maps each path token from $from without changing surrounding text', ({ from, to, source, target }) => {
+ const aliases = [{ from, to }];
+ const first = source.join(from, 'README.md');
+ const second = source.join(from, 'src', 'b.ts');
+ const mappedFirst = target.join(to, 'README.md');
+ const mappedSecond = target.join(to, 'src', 'b.ts');
+ expect(projectPathText(first + ' ' + second, aliases)).toBe(mappedFirst + ' ' + mappedSecond);
+ expect(projectPathText(first + ' links to /api/v1 and C:\\other\\file.txt', aliases))
+ .toBe(mappedFirst + ' links to /api/v1 and C:\\other\\file.txt');
+ const document = JSON.stringify({ text: first + ' links to /api/v1', path: source.join(from, '目录 空格', 'a.ts') });
+ expect(projectPathText(document, aliases)).toBe(JSON.stringify({ text: mappedFirst + ' links to /api/v1', path: target.join(to, '目录 空格', 'a.ts') }));
+ });
+
+ it.each(['/home/agent/workspace', 'C:\\Agent\\workspace'])('maps text file bytes token by token on input and output at %s', (virtual) => {
+ const { project, workspace } = setup(virtual);
+ const native = virtual.startsWith('C:') ? path.win32 : path.posix;
+ const input = Buffer.from(native.join(virtual, 'a.ts') + ' ' + native.join(virtual, 'src', 'b.ts') + ' links to /api/v1');
+ const real = Buffer.from(path.join(project, 'a.ts') + ' ' + path.join(project, 'src', 'b.ts') + ' links to /api/v1');
+ expect(workspace.mapInputFromAgent(input)).toEqual(real);
+ expect(workspace.mapOutputForAgent(real)).toEqual(input);
+ const quoted = 'The docs say "' + native.join(virtual, 'README.md') + ' links to /api/v1"';
+ expect(workspace.mapInputFromAgent(Buffer.from(quoted)))
+ .toEqual(Buffer.from('The docs say "' + path.join(project, 'README.md') + ' links to /api/v1"'));
+ });
+
+ it.each([
+ { from: '/home/agent/workspace', to: 'C:\\real\\project', source: path.posix, target: path.win32 },
+ { from: 'C:\\Agent\\workspace', to: '/real/project', source: path.win32, target: path.posix },
+ ])('keeps prose in JSON scalars and untyped arrays from $from', ({ from, to, source, target }) => {
+ const document = (directory: string, native: typeof path.win32) => {
+ const first = native.join(directory, 'README.md');
+ return [first + ' links to /api/v1', first + ' relative/input.txt', first + ' ' + native.join(directory, 'src', 'a.ts')];
+ };
+ const original = document(from, source);
+ const expected = document(to, target);
+ const aliases = [{ from, to }];
+ for (let index = 0; index < original.length; index += 1) {
+ expect(projectPathText(JSON.stringify(original[index]), aliases)).toBe(JSON.stringify(expected[index]));
+ }
+ expect(projectPathText(JSON.stringify([original, { text: original[0] }, JSON.stringify(original)]), aliases))
+ .toBe(JSON.stringify([expected, { text: expected[0] }, JSON.stringify(expected)]));
+ });
+
+ it.each(['/home/agent/workspace', 'C:\\Agent\\workspace'])('writes and reads JSON prose without changing non-path bytes at %s', async (virtual) => {
+ const { project, executor } = setup(virtual);
+ const native = virtual.startsWith('C:') ? path.win32 : path.posix;
+ const prose = native.join(virtual, 'README.md') + ' links to /api/v1 and relative/input.txt';
+ const localProse = path.join(project, 'README.md') + ' links to /api/v1 and relative/input.txt';
+ const documents = (value: string) => [
+ JSON.stringify(value),
+ '[\r\n ' + JSON.stringify(value) + ', [' + JSON.stringify(value) + '], 1.00e0, "\\u4e2d"\r\n]\r\n',
+ JSON.stringify(JSON.stringify([value])),
+ ];
+ const input = documents(prose);
+ const expected = documents(localProse);
+ try {
+ for (let index = 0; index < input.length; index += 1) {
+ const file = native.join(virtual, 'prose-' + index + '.json');
+ await executor.handle('fs.write', { path: file, data: Buffer.from(input[index]).toString('base64') });
+ expect(fs.readFileSync(path.join(project, 'prose-' + index + '.json'), 'utf8')).toBe(expected[index]);
+ const read = await executor.handle('fs.read', { path: file }) as { data: string };
+ expect(Buffer.from(read.data, 'base64').toString('utf8')).toBe(input[index]);
+ }
+ } finally {
+ await executor.close();
+ }
+ });
+
+ it('escapes regex metacharacters and backslash path separators without matching other prefixes', () => {
+ const from = 'C:\\Agent\\project[1].(data)$';
+ const text = path.win32.join(from, 'src', 'a.ts') + ' C:\\Agent\\project1xdata\\src\\b.ts';
+ expect(projectPathText(text, [{ from, to: '/real/project' }]))
+ .toBe('/real/project/src/a.ts C:\\Agent\\project1xdata\\src\\b.ts');
+ expect(projectPathText('"/REAL/project/a.ts"', [{ from: '/real/project', to: '/virtual/project' }], 'path'))
+ .toBe('"/REAL/project/a.ts"');
+ });
+
+ it.each([
+ { from: '/home/agent/workspace', to: 'C:\\real\\project', source: path.posix, target: path.win32 },
+ { from: 'C:\\Agent\\workspace', to: '/real/project', source: path.win32, target: path.posix },
+ ])('projects JSON scalar paths and inherited path arrays from $from', ({ from, to, source, target }) => {
+ const originalPath = source.join(from, '目录 空格', 'a.txt');
+ const mappedPath = target.join(to, '目录 空格', 'a.txt');
+ const aliases = [{ from, to }];
+ // 纯跨平台用例注入已确认的路径;下面的真实文件回归验证存在性判据。
+ const isCompletePath = (mapped: string) => mapped === mappedPath;
+ expect(projectPathText(JSON.stringify(originalPath), aliases, 'text', isCompletePath)).toBe(JSON.stringify(mappedPath));
+ expect(projectPathText(JSON.stringify([originalPath, [originalPath]]), aliases, 'text', isCompletePath)).toBe(JSON.stringify([mappedPath, [mappedPath]]));
+ const prose = source.join(from, 'README.md') + ' links to /api/v1';
+ const mappedProse = target.join(to, 'README.md') + ' links to /api/v1';
+ const original = { paths: [originalPath, [originalPath]], nested: { file_paths: [originalPath] }, text: prose, messages: [prose] };
+ const mapped = { paths: [mappedPath, [mappedPath]], nested: { file_paths: [mappedPath] }, text: mappedProse, messages: [mappedProse] };
+ expect(projectPathText(JSON.stringify(original), aliases)).toBe(JSON.stringify(mapped));
+ });
+
+ it.each(['/home/agent/workspace', 'C:\\Agent\\workspace'])('round-trips confirmed JSON paths and keeps future paths in explicit fields at %s', (virtual) => {
+ const { project, workspace } = setup(virtual);
+ const native = virtual.startsWith('C:') ? path.win32 : path.posix;
+ const local = path.join(project, '目录 空格', 'a.txt');
+ fs.mkdirSync(path.dirname(local));
+ fs.writeFileSync(local, 'existing file');
+ const remote = native.join(virtual, '目录 空格', 'a.txt');
+ const localFuture = path.join(project, '尚未 创建', 'future.txt');
+ const remoteFuture = native.join(virtual, '尚未 创建', 'future.txt');
+ const values = (file: string, directory: string, future: string) => [
+ file, [file, [directory]], { paths: [future, [future]], nested: { file_paths: [future] } },
+ ];
+ const input = values(remote, native.dirname(remote), remoteFuture);
+ const expected = values(local, path.dirname(local), localFuture);
+ expect(fs.existsSync(localFuture)).toBe(false);
+ for (let index = 0; index < input.length; index += 1) {
+ const remoteBytes = Buffer.from(JSON.stringify(input[index]));
+ const localBytes = Buffer.from(JSON.stringify(expected[index]));
+ expect(workspace.mapInputFromAgent(remoteBytes)).toEqual(localBytes);
+ expect(workspace.mapOutputForAgent(localBytes)).toEqual(remoteBytes);
+ }
+ });
+
+ it.each([
+ { from: '/home/agent/workspace', to: 'C:\\real\\project', source: path.posix, target: path.win32 },
+ { from: 'C:\\Agent\\workspace', to: '/real/project', source: path.win32, target: path.posix },
+ ])('preserves quoted prose and maps every embedded path token from $from', ({ from, to, source, target }) => {
+ const first = source.join(from, 'README.md');
+ const second = source.join(from, 'src', 'a.ts');
+ const original = 'The docs say "' + first + ' links to /api/v1 and ' + second + '"';
+ const mapped = 'The docs say "' + target.join(to, 'README.md') + ' links to /api/v1 and ' + target.join(to, 'src', 'a.ts') + '"';
+ expect(projectPathText(original, [{ from, to }])).toBe(mapped);
+ expect(projectPathText(JSON.stringify([original]), [{ from, to }])).toBe(JSON.stringify([mapped]));
+ });
+
+ it.each(['/home/agent/workspace', 'C:\\Agent\\workspace'])('treats script fields as source unless they are existing complete paths at %s', (virtual) => {
+ const { project, workspace } = setup(virtual);
+ const native = virtual.startsWith('C:') ? path.win32 : path.posix;
+ const existing = path.join(project, '目录 空格', 'run.js');
+ fs.mkdirSync(path.dirname(existing), { recursive: true });
+ fs.writeFileSync(existing, 'console.log(1);');
+ const existingVirtual = native.join(virtual, '目录 空格', 'run.js');
+ const source = JSON.stringify({ script: native.join(virtual, 'run.js') + ' --url /api/v1' });
+ const sourceExpected = JSON.stringify({ script: path.join(project, 'run.js') + ' --url /api/v1' });
+ expect(workspace.mapInputFromAgent(Buffer.from(source))).toEqual(Buffer.from(sourceExpected));
+ const pathValue = JSON.stringify({ script: existingVirtual });
+ const pathExpected = JSON.stringify({ script: existing });
+ expect(workspace.mapInputFromAgent(Buffer.from(pathValue))).toEqual(Buffer.from(pathExpected));
+ expect(workspace.mapOutputForAgent(Buffer.from(pathExpected))).toEqual(Buffer.from(pathValue));
+ });
+
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);
@@ -123,4 +371,282 @@ describe('virtual workspace', () => {
}
await executor.close();
});
+
+ it.each([
+ { virtual: '/home/agent/workspace', sse: false },
+ { virtual: '/home/agent/workspace', sse: true },
+ { virtual: 'C:\\Agent\\workspace', sse: false },
+ { virtual: 'C:\\Agent\\workspace', sse: true },
+ ])('preserves structured MCP path fields and nested arrays at $virtual (SSE=$sse)', async ({ virtual, sse }) => {
+ const { project, executor } = setup(virtual);
+ const agentPath = virtual.startsWith('C:') ? path.win32 : path.posix;
+ const realFile = path.join(project, '目录 空格', 'deep', 'report.txt');
+ const virtualFile = agentPath.join(virtual, '目录 空格', 'deep', 'report.txt');
+ const prose = path.join(project, 'README.md') + ' links to /api/v1 and relative/input.txt';
+ const virtualProse = agentPath.join(virtual, 'README.md') + ' links to /api/v1 and relative/input.txt';
+ const structuredContent = {
+ path: realFile,
+ paths: [realFile, [realFile], { path: realFile, text: prose }],
+ nested: { file_path: realFile, filePath: realFile, working_dir: path.dirname(realFile) },
+ text: prose,
+ enabled: true, count: 1, optional: null,
+ };
+ const response = { jsonrpc: '2.0', id: 1, result: {
+ structuredContent, content: [{ type: 'text', text: JSON.stringify({ path: realFile }) }, { type: 'text', text: prose }],
+ } };
+ const router = createReverseHttpRouter({
+ executor,
+ mcpTarget: () => ({ url: 'http://unused', headers: {} }),
+ fetch: async () => new Response(sse ? 'data: ' + JSON.stringify(response) + '\n\n' : JSON.stringify(response), {
+ headers: { 'content-type': sse ? 'text/event-stream' : 'application/json' },
+ }),
+ });
+ try {
+ const reply = await router({ method: 'POST', path: '/mcp/cindy_helper', headers: [], body: Buffer.from(JSON.stringify({
+ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'path_probe', arguments: {} },
+ })).toString('base64') });
+ if (reply.type !== 'http') throw new Error('expected MCP HTTP reply');
+ const body = Buffer.from(reply.body!, 'base64').toString();
+ expect(JSON.parse(sse ? body.split('\n')[0].slice(6) : body)).toEqual({
+ jsonrpc: '2.0', id: 1, result: {
+ structuredContent: {
+ ...structuredContent,
+ path: virtualFile,
+ paths: [virtualFile, [virtualFile], { path: virtualFile, text: virtualProse }],
+ nested: { file_path: virtualFile, filePath: virtualFile, working_dir: agentPath.dirname(virtualFile) },
+ text: virtualProse,
+ },
+ content: [{ type: 'text', text: JSON.stringify({ path: virtualFile }) }, { type: 'text', text: virtualProse }],
+ },
+ });
+ } finally {
+ await executor.close();
+ }
+ });
+
+ it.each([
+ { virtual: '/Users/agent/workspace', sse: false },
+ { virtual: '/Users/agent/workspace', sse: true },
+ { virtual: '/home/agent/workspace', sse: false },
+ { virtual: '/home/agent/workspace', sse: true },
+ { virtual: 'C:\\Agent\\workspace', sse: false },
+ { virtual: 'C:\\Agent\\workspace', sse: true },
+ ])('returns a usable current directory to the Agent at $virtual (SSE=$sse)', async ({ virtual, sse }) => {
+ const { workspace, project, executor, gate } = setup(virtual);
+ const context = { sessionId: 'local-task', agentKind: 'codex' as const, workingDir: project };
+ const registry = new XdtHelperToolRegistry();
+ registerGetCurrentSessionIdTool(registry, { getSessionContext: () => context });
+ let receivedDirectory: string | undefined;
+ registry.register({
+ name: 'workspace_probe', category: 'cindy', description: 'Read the current directory on the task computer.',
+ inputShape: { working_dir: z.string() },
+ handler: async ({ working_dir }) => {
+ receivedDirectory = working_dir;
+ expect(gate.authorize({ kind: 'read', path: working_dir }).ok).toBe(true);
+ return { content: [{ type: 'text', text: JSON.stringify({
+ ok: fs.statSync(working_dir).isDirectory(), working_dir,
+ }) }] };
+ },
+ });
+ const router = createReverseHttpRouter({
+ executor,
+ mcpTarget: () => ({ url: 'http://unused', headers: {} }),
+ fetch: async (_url, options) => {
+ const request = JSON.parse(Buffer.from(options!.body as Uint8Array).toString());
+ const rawArgs = request.params.arguments.args;
+ // The real MCP entry schema applies jsonObjectArg's stringified-JSON
+ // preprocessing before dispatching to the registry. Mirror that here
+ // so this router regression exercises the same downstream boundary.
+ const args = typeof rawArgs === 'string' ? JSON.parse(rawArgs) : rawArgs;
+ const result = await registry.call(request.params.arguments.name, args);
+ const message = JSON.stringify({ jsonrpc: '2.0', id: request.id, result });
+ return new Response(sse ? 'data: ' + message + '\n\n' : message, {
+ headers: { 'content-type': sse ? 'text/event-stream' : 'application/json' },
+ });
+ },
+ });
+ const call = async (name: string, args: Record<string, unknown> | string) => {
+ const reply = await router({ method: 'POST', path: '/mcp/cindy_helper', headers: [], body: Buffer.from(JSON.stringify({
+ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'call_tool', arguments: { name, args } },
+ })).toString('base64') });
+ if (reply.type !== 'http') throw new Error('expected MCP HTTP reply');
+ const body = Buffer.from(reply.body!, 'base64').toString();
+ const message = JSON.parse(sse ? body.split('\n')[0].slice(6) : body);
+ expect(message.result.isError).not.toBe(true);
+ return JSON.parse(message.result.content[0].text);
+ };
+ try {
+ const current = await call('get_current_session_id', {});
+ expect(current).toEqual({ ok: true, session_id: 'local-task', agent_kind: 'codex', working_dir: virtual });
+ expect(await call('workspace_probe', { working_dir: current.working_dir })).toEqual({ ok: true, working_dir: virtual });
+ expect(await call('workspace_probe', JSON.stringify({ working_dir: virtual }))).toEqual({ ok: true, working_dir: virtual });
+ expect(receivedDirectory).toBe(project);
+ expect(context.workingDir).toBe(project);
+ expect(workspace.workingDir).toBe(project);
+ } finally {
+ await executor.close();
+ }
+ });
+
+ it('restores helper, plugin and document path parameters while preserving their content and media identifiers', async () => {
+ const virtual = '/Users/agent/workspace';
+ const { project, executor } = setup(virtual);
+ let received: Record<string, unknown> | undefined;
+ const content = JSON.stringify({ path: virtual });
+ const router = createReverseHttpRouter({
+ executor,
+ mcpTarget: () => ({ url: 'http://unused', headers: {} }),
+ fetch: async (_url, options) => {
+ received = JSON.parse(Buffer.from(options!.body as Uint8Array).toString()).params.arguments;
+ return new Response('{}', { headers: { 'content-type': 'application/json' } });
+ },
+ });
+ try {
+ await router({ method: 'POST', path: '/mcp/cindy', headers: [], body: Buffer.from(JSON.stringify({
+ method: 'tools/call', params: { name: 'example', arguments: {
+ workdir: virtual, dir: virtual, save_dir: virtual,
+ extra_dirs: [virtual], writableDirs: [virtual],
+ attachments: [virtual + '/image.png', 'cindy-media://blobs/abc.png', 'xdt-image://task/image.png'],
+ args: { working_dir: virtual, file_path: virtual + '/file.txt', outPath: virtual + '/out.pdf', htmlPath: virtual + '/in.html', imagePath: virtual + '/image.png' },
+ workers: [{ working_dir: virtual }],
+ out_file: virtual + '/result.json', absPath: virtual + '/upload.txt',
+ workspace_root: virtual, anchorFile: virtual + '/index.ts', file_paths: [virtual + '/input.txt'],
+ content, text: virtual,
+ } },
+ })).toString('base64') });
+ expect(received).toEqual({
+ workdir: project, dir: project, save_dir: project,
+ extra_dirs: [project], writableDirs: [project],
+ attachments: [path.join(project, 'image.png'), 'cindy-media://blobs/abc.png', 'xdt-image://task/image.png'],
+ args: { working_dir: project, file_path: path.join(project, 'file.txt'), outPath: path.join(project, 'out.pdf'), htmlPath: path.join(project, 'in.html'), imagePath: path.join(project, 'image.png') },
+ workers: [{ working_dir: project }],
+ out_file: path.join(project, 'result.json'), absPath: path.join(project, 'upload.txt'),
+ workspace_root: project, anchorFile: path.join(project, 'index.ts'), file_paths: [path.join(project, 'input.txt')],
+ content, text: virtual,
+ });
+ } finally {
+ await executor.close();
+ }
+ });
+
+ it.each(['/Users/agent/workspace', 'C:\\Agent\\workspace'].flatMap((virtual) => [
+ { virtual, name: 'start_recording', key: 'output_dir', args: { record_video: true } },
+ { virtual, name: 'get_window_state', key: 'screenshot_out_file', args: { pid: 123, window_id: 7 } },
+ { virtual, name: 'click', key: 'debug_image_out', args: { pid: 123, window_id: 7, x: 10, y: 20 } },
+ ]))('restores $name ($key) at $virtual before the real Computer MCP path guard', async ({ virtual, name, key, args }) => {
+ const { project, executor } = setup(virtual);
+ const agentPath = virtual.startsWith('C:') ? path.win32 : path.posix;
+ const callTool = vi.fn(async () => ({ ok: true }));
+ const server = createComputerMcpServer({ getStatus: vi.fn(), callTool }, {
+ getSessionContext: () => ({ sessionId: 'local-task', agentKind: 'codex', workingDir: project }),
+ });
+ const client = new Client({ name: 'remote-path-test', version: '0.0.0' });
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ const router = createReverseHttpRouter({
+ executor,
+ mcpTarget: () => ({ url: 'http://unused', headers: {} }),
+ fetch: async (_url, options) => {
+ const request = JSON.parse(Buffer.from(options!.body as Uint8Array).toString());
+ const result = await client.callTool({ name: request.params.name, arguments: request.params.arguments });
+ return new Response(JSON.stringify({ jsonrpc: '2.0', id: request.id, result }), { headers: { 'content-type': 'application/json' } });
+ },
+ });
+ const invoke = async (output: string) => {
+ const reply = await router({ method: 'POST', path: '/mcp/cindy_computer', headers: [], body: Buffer.from(JSON.stringify({
+ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'call_tool', arguments: { name, args: { ...args, [key]: output } } },
+ })).toString('base64') });
+ if (reply.type !== 'http') throw new Error('expected MCP HTTP reply');
+ const result = JSON.parse(Buffer.from(reply.body!, 'base64').toString());
+ return JSON.parse(result.result.content[0].text);
+ };
+ try {
+ await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);
+ expect(await invoke(agentPath.join(virtual, '输出 目录', 'capture'))).toMatchObject({ ok: true });
+ expect(callTool).toHaveBeenCalledWith(name, expect.objectContaining({
+ ...args, [key]: path.join(project, '输出 目录', 'capture'), session: 'local-task',
+ }), expect.objectContaining({ sessionId: 'local-task' }));
+ callTool.mockClear();
+ // 保留别名前缀中的 ..,确认先还原再由本机工具的真实权限边界拒绝。
+ expect(await invoke(virtual + agentPath.sep + '..' + agentPath.sep + 'outside'))
+ .toMatchObject({ ok: false, errorCode: 'PATH_NOT_ALLOWED' });
+ expect(callTool).not.toHaveBeenCalled();
+ } finally {
+ await client.close();
+ await server.close();
+ await executor.close();
+ }
+ });
+
+ it('maps workbench project paths in direct and stringified generic-tool arguments', async () => {
+ const virtual = '/Users/agent/workspace';
+ const { project, executor } = setup(virtual);
+ const forwarded: Array<Record<string, unknown>> = [];
+ const router = createReverseHttpRouter({
+ executor,
+ mcpTarget: () => ({ url: 'http://unused', headers: {} }),
+ fetch: async (_url, options) => {
+ const request = JSON.parse(Buffer.from(options!.body as Uint8Array).toString()) as { params: { arguments: Record<string, unknown> } };
+ forwarded.push(request.params.arguments);
+ return new Response(JSON.stringify({ jsonrpc: '2.0', id: 1, result: { content: [{ type: 'text', text: '{}' }] } }), {
+ headers: { 'content-type': 'application/json' },
+ });
+ },
+ });
+ try {
+ for (const args of [
+ { project: virtual },
+ JSON.stringify({ project: virtual }),
+ { items: [{ project: virtual }] },
+ ]) {
+ await router({ method: 'POST', path: '/mcp/cindy_helper', headers: [], body: Buffer.from(JSON.stringify({
+ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'call_tool', arguments: {
+ name: args && typeof args === 'object' && !Array.isArray(args) && 'items' in args ? 'set_workbench_tasks' : 'set_workbench_task', args,
+ } },
+ })).toString('base64') });
+ }
+ expect(forwarded).toEqual([
+ { name: 'set_workbench_task', args: { project } },
+ { name: 'set_workbench_task', args: JSON.stringify({ project }) },
+ { name: 'set_workbench_tasks', args: { items: [{ project }] } },
+ ]);
+ } finally {
+ await executor.close();
+ }
+ });
+
+ it.each(['/Users/agent/workspace', 'C:\\Agent\\workspace'])('runs a Skill script in the real directory and returns JSON paths at %s', async (virtual) => {
+ const { project, executor } = setup(virtual);
+ const agentPath = virtual.startsWith('C:') ? path.win32 : path.posix;
+ const fixtureDir = path.join(project, '目录 空格');
+ const virtualDir = agentPath.join(virtual, '目录 空格');
+ const script = path.join(fixtureDir, 'skill', 'probe.cjs');
+ const virtualScript = agentPath.join(virtualDir, 'skill', 'probe.cjs');
+ fs.mkdirSync(path.dirname(script), { recursive: true });
+ fs.writeFileSync(script, [
+ 'const fs = require("node:fs");',
+ 'const path = require("node:path");',
+ 'const result = { cwd: process.cwd(), script: __filename, argument: path.resolve(process.argv[2]) };',
+ 'fs.writeFileSync("native-result.json", JSON.stringify(result));',
+ 'console.log("Running Skill script");',
+ 'console.log(JSON.stringify(result));',
+ ].join('\n'));
+ try {
+ const result = await executor.handle('exec.run', {
+ command: 'node "' + virtualScript + '" "' + virtual + '"', cwd: virtualDir,
+ }) as { output: string; exitCode: number };
+ expect(result.exitCode).toBe(0);
+ const output = Buffer.from(result.output, 'base64').toString();
+ const lines = output.trim().split(/\r?\n/);
+ expect(lines[0]).toBe('Running Skill script');
+ expect(JSON.parse(lines[1])).toEqual({ cwd: virtualDir, script: virtualScript, argument: virtual });
+ const nativeResult = { cwd: fixtureDir, script, argument: project };
+ const actualNative = JSON.parse(fs.readFileSync(path.join(fixtureDir, 'native-result.json'), 'utf8')) as typeof nativeResult;
+ expect(actualNative).toEqual({ cwd: expect.any(String), script, argument: project });
+ expect(fs.realpathSync.native(actualNative.cwd)).toBe(fs.realpathSync.native(fixtureDir));
+ await executor.handle('fs.write', { path: agentPath.join(virtualDir, 'returned.json'), data: Buffer.from(lines[1]).toString('base64') });
+ expect(JSON.parse(fs.readFileSync(path.join(fixtureDir, 'returned.json'), 'utf8'))).toEqual(nativeResult);
+ } finally {
+ await executor.close();
+ }
+ });
});
diff --git a/apps/desktop/src/main/remote-agent/executor/workspace.ts b/apps/desktop/src/main/remote-agent/executor/workspace.ts
index afab63e7f6..13005c56a3 100644
--- a/apps/desktop/src/main/remote-agent/executor/workspace.ts
+++ b/apps/desktop/src/main/remote-agent/executor/workspace.ts
@@ -70,22 +70,103 @@ function stripAliasPrefix(input: string, from: string): string | null {
return null;
}
+/** 普通文本逐 token 匹配;命令只匹配前缀,后缀按 shell 引号与转义规则扫描。 */
+function pathTextPattern(aliases: readonly ExecutorPathAlias[], prefixOnly = false): RegExp {
+ const patterns = aliases.map((alias) => alias.from.replace(/[\\/]+$/, '').split(/[\\/]/)
+ .map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('[/\\\\]'));
+ const prefix = '(' + patterns.join('|') + ')(?=$|[^A-Za-z0-9_])';
+ return new RegExp('(^|[^A-Za-z0-9_])' + prefix
+ + (prefixOnly ? '' : '([/\\\\][^\\s\\x60\\x27\\x22;:|&)<>}\\]]*|)'), 'gi');
+}
+
+export function isPathTextField(key: string): boolean {
+ return /^(?:cwd|workdir|working_?dir|script|files?|paths?|directories)$|(?:^|_)(?:paths?|files?|dirs?|directory|directories|root)$|(?:Paths?|Files?|Dirs?|Directory|Directories|Root)$/.test(key);
+}
+
+export type PathTextContext = 'text' | 'path' | 'ambiguous-path' | 'untyped';
+
+/** The existing script fields contain both executable paths and source text. */
+export function pathTextContext(key: string): PathTextContext {
+ if (key === 'script') return 'ambiguous-path';
+ return isPathTextField(key) ? 'path' : 'text';
+}
+
+export function mapJsonPathText(
+ text: string, project: (value: string, context: PathTextContext) => string, rootContext: PathTextContext = 'untyped',
+): string {
+ JSON.parse(text);
+ // 顶层字符串/数组也能承载正文,容器本身不提供完整路径的证据。
+ const frames: { type: 'object' | 'array'; context: PathTextContext; key?: string }[] = [];
+ const valueContext = (): PathTextContext => {
+ const frame = frames.at(-1);
+ return frame?.type === 'object' ? pathTextContext(frame.key ?? '') : frame?.context ?? rootContext;
+ };
+ return text.replace(/"(?:\\[\s\S]|[^"\\])*"|[{}[\],:]/g, (token, offset: number) => {
+ if (token === '{' || token === '[') {
+ frames.push({ type: token === '{' ? 'object' : 'array', context: valueContext() });
+ return token;
+ }
+ if (token === '}' || token === ']') {
+ frames.pop();
+ return token;
+ }
+ if (token === ',') {
+ const frame = frames.at(-1);
+ if (frame?.type === 'object') frame.key = undefined;
+ return token;
+ }
+ if (token === ':') return token;
+ const decoded = JSON.parse(token) as string;
+ if (/^\s*:/.test(text.slice(offset + token.length))) {
+ const frame = frames.at(-1);
+ if (frame?.type === 'object') frame.key = decoded;
+ return token;
+ }
+ const projected = project(decoded, valueContext());
+ return projected === decoded ? token : JSON.stringify(projected);
+ });
+}
+
/** 对已知目录做单次双向投影,最长前缀先匹配,防止替换结果再次被短祖先别名改写。 */
-export function projectPathText(text: string, aliases: readonly ExecutorPathAlias[]): string {
+export function projectPathText(
+ text: string, aliases: readonly ExecutorPathAlias[], context: PathTextContext = 'text',
+ isCompletePath?: (mapped: string) => boolean,
+): 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 或文本里的同前缀标识符。
- // 这里的边界覆盖 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;
- const separator = alias.to.includes('\\') ? '\\' : '/';
- return left + alias.to.replace(/[\\/]+$/, '') + suffix.replace(/[\\/]/g, separator);
- });
+ const textPattern = pathTextPattern(entries, false);
+ const project = (value: string, valueContext: PathTextContext = 'text'): string => {
+ // MCP 的 text 常嵌一层 JSON;Skill/命令输出和文本文件也可能是 JSON。
+ // 先解码字符串再投影,才能识别 Windows 转义路径;只改变化的字符串 token,保留格式与其它字节。
+ if (/^\s*[{["]/.test(value)) {
+ try { return mapJsonPathText(value, project, valueContext === 'text' ? 'untyped' : valueContext); } catch { /* 普通文本继续按路径边界投影。 */ }
+ }
+ // 脚本可能先打印日志再逐行输出 JSON;保留换行格式,逐行应用同一套转义处理。
+ if (value.includes('\n')) return value.split('\n').map((line) => project(line, valueContext)).join('\n');
+ // 整个字符串就是路径时(含已解码的 JSON 字符串),空格也属于路径,不能截断后续分隔符。
+ const lineEnd = value.endsWith('\r') ? '\r' : '';
+ const pathValue = lineEnd ? value.slice(0, -1) : value;
+ if (valueContext !== 'text') {
+ for (const alias of entries) {
+ if (stripAliasPrefix(pathValue, alias.from) === null) continue;
+ const separator = alias.to.includes('\\') ? '\\' : '/';
+ const suffix = pathValue.slice(alias.from.replace(/[\\/]+$/, '').length);
+ const mapped = alias.to.replace(/[\\/]+$/, '') + suffix.replace(/[\\/]/g, separator);
+ // 明确的路径字段可整体映射;歧义字段(如 script)只有现存完整路径才整体映射,
+ // 否则按正文逐 token 投影,避免把脚本源码里的 /api/v1 等内容当成路径。
+ if (valueContext === 'path' || isCompletePath?.(mapped)) return mapped + lineEnd;
+ break;
+ }
+ }
+ return value.replace(textPattern, (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);
+ });
+ };
+ return project(text, context);
}
export class ExecutorWorkspace {
@@ -195,7 +276,7 @@ export class ExecutorWorkspace {
}
/** 工具输出、诊断和可逆的 UTF-8 文本内容使用虚拟路径;二进制字节保持原样。 */
- mapTextForAgent(text: string): string {
+ mapTextForAgent(text: string, context: PathTextContext = 'text'): string {
if (!this.virtualRoot) return text;
const aliases = this.aliases.flatMap((alias) => {
const real = alias.to.replace(/\\/g, '/');
@@ -209,16 +290,21 @@ export class ExecutorWorkspace {
}
return entries;
});
- return projectPathText(text, aliases);
+ return projectPathText(text, aliases, context, (mapped) => fs.existsSync(this.mapAlias(mapped)));
}
/** 把 Agent 虚拟路径还原成本机路径,用于文本文件写回。 */
- mapTextFromAgent(text: string): string {
+ mapTextFromAgent(text: string, context: PathTextContext = 'text'): string {
if (!this.virtualRoot) return text;
return projectPathText(text, this.aliases.map((alias) => ({
from: alias.from.replace(/\\/g, '/'),
to: alias.to,
- })));
+ })), context, (mapped) => fs.existsSync(mapped));
+ }
+
+ /** 展示层延迟尚未传完整的虚拟路径;别名仍由当前执行器维护。 */
+ agentPathPrefixes(): readonly string[] {
+ return this.virtualRoot ? this.aliases.map((alias) => alias.from) : [];
}
mapOutputForAgent(data: Buffer): Buffer {
@@ -244,19 +330,19 @@ export class ExecutorWorkspace {
})).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('[/\\\\]'));
// 路径尾部遇到引号即止:闭合引号属于外层 shell 语法,吞进路径会被按引号上下文转义
// ('…mjs' → '…mjs'\''),留下未闭合的引号。
- const pattern = new RegExp('(^|[^A-Za-z0-9_])(' + patterns.join('|') + ')(?=$|[^A-Za-z0-9_])([/\\\\][^\\s\\x60\\x27\\x22;:|&)<>}\\]]*|)', 'gi');
+ const pattern = pathTextPattern(aliases, true);
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';
+ if (dialect === 'bash' && char === '\\' && (quote === 'none'
+ || (quote === 'double' && /[$\x60"\\\n]/.test(input[i + 1] ?? '')))) { escaped = true; continue; }
+ if (dialect === 'cmd' && char === '^' && quote === 'none') { escaped = true; continue; }
+ if (dialect === 'bash' && 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';
@@ -271,17 +357,43 @@ export class ExecutorWorkspace {
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)
+ 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) => {
+ let result = '';
+ let end = 0;
+ for (const match of command.matchAll(pattern)) {
+ const [, left, prefix] = match;
+ const start = match.index! + left.length;
+ if (start < end) continue;
const alias = aliases.find((entry) => stripAliasPrefix(prefix, entry.from) === '');
- if (!alias) return match;
+ if (!alias) continue;
const separator = alias.to.includes('\\') ? '\\' : '/';
- const target = alias.to.replace(/[\\/]+$/, '') + suffix.replace(/[\\/]/g, separator);
- return left + quote(target, quoteContext(input, offset + left.length));
- });
+ const context = quoteContext(command, start);
+ const windowsPath = /^[A-Za-z]:|^[/\\]{2}/.test(prefix);
+ let suffixEnd = start + prefix.length;
+ const suffixStart = suffixEnd;
+ if ((windowsPath || dialect === 'cmd') && /[/\\]/.test(command[suffixEnd] ?? '')) {
+ // 只转换静态路径段。转义、变量与命令替换从原文原样保留,尤其不能把转义
+ // 引号前的反斜杠当成路径分隔符,否则参数中的数据会变成新的 shell 命令。
+ for (; suffixEnd < command.length; suffixEnd += 1) {
+ const char = command[suffixEnd];
+ if (char === '\r' || char === '\n') break;
+ if (context === 'single' && char === "'") break;
+ if (context === 'double' && char === '"') break;
+ if (context === 'none' && /[\s'"\x60;:|&()<>}\]]/.test(char)) break;
+ if (dialect === 'bash' && context !== 'single'
+ && (/[$\x60]/.test(char) || (char === '\\'
+ && (context === 'double' ? /[$\x60"\\\n]/ : /[\s'"$\x60\\;|&()<>]/).test(command[suffixEnd + 1] ?? '')))) break;
+ if (dialect === 'cmd' && /[%^!]/.test(char)) break;
+ }
+ }
+ result += command.slice(end, start) + quote(alias.to.replace(/[\\/]+$/, ''), context)
+ + command.slice(suffixStart, suffixEnd).replace(/[\\/]/g, separator);
+ end = suffixEnd;
+ }
+ return result + command.slice(end);
}
/** 把 Agent 给的路径解析成本机绝对路径(相对路径以 baseDir / 工作目录为基准)。 */
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index b907340176..8379f8b4de 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -812,6 +812,23 @@ handler 无 sender 依赖;不加入共享任务访客白名单,不进入自
还原到 A 的真实路径,二进制内容保持原样。A 的真实目录继续用于权限 gate、执行与变更抓取,
路径别名不增加授权。执行平台与 shell 保留 A 的实际值,以免跨 macOS / Windows / Linux 选错
命令。此增量不修改 channel、relay、协议版本或服务器,也不是 OS 虚拟化。
+ 本机 MCP 的 snake_case / camelCase 路径参数(含工作目录、插件目录交接、文档输入输出)在 A 执行前还原;
+ 参数复用结果侧的路径字段判据,覆盖 `output_dir`、`screenshot_out_file`、`out_file`、`absPath` 等已有字段,并兼容 `debug_image_out`;还原后的路径仍由各本机工具执行原有的目录范围与权限检查。
+ `get_current_session_id` 等工具的 JSON 文本及 Skill/命令的 JSON 输出先解码字符串再投影,保持合法转义与原有格式。
+ MCP 的 JSON/SSE 结构化结果保留路径字段语义,并传给路径字段内嵌的数组;普通正文仍逐路径 token 投影,避免空格后的分隔符漏转或正文被当成完整路径。
+ 已明确为路径的参数、路径字段内嵌的数组与命令内的完整路径保留中文和空格,空格之后的子路径也必须转换成目标电脑的分隔符。
+ "script" 字段同时承载脚本源码和可执行文件路径;只有完整值对应 A 上已存在的文件或目录时才整体转换,否则按正文逐路径 token 投影,避免改写脚本里的参数与 URL。
+ JSON 标量/独立数组不自动提供路径语义;无字段名的字符串只有在完整值对应 A 上已存在的文件或目录时才整体转换,否则逐路径 token 投影,避免改写正文中的 `/api/v1` 或相对参数。明确的路径字段不依赖文件存在性,仍支持尚未创建的目标。
+ 普通输出和文件正文无论引号内外都逐个路径 token 投影,不把以路径开头的整段当成单一路径;命令只安全引用替换的目录前缀,保留后缀的变量和命令替换语义。
+ 命令后缀按执行端 shell 的引号与转义边界扫描;转义引号前的反斜杠不得变成路径分隔符。权限检查继续使用映射后实际执行的命令。
+ Agent 取到的当前目录可直接用于后续工具,A 的任务语境、执行 cwd 与权限检查始终使用真实目录。
+ B 回传的工具文件路径、文本文件链接与图片源路径在 A 的事件落库和广播前还原,文件卡及预览读取 A 的真实文件。
+ 行内代码含空白时,只有完整引用对应 A 上已存在的文件或目录才整体还原;否则逐路径 token 投影,保留命令参数。明确的链接目标与结构化路径不依赖文件存在性。
+ 流式正文按来源、轮次和子代理 parentUuid 分别暂存未传完整的文件引用,同一流的工具和终态边界补齐尾段;全局终态与关闭清空所有流,独立后台提示不打断正文路径。
+ `status { isRunning: false }` 也在转发前补齐尾段,不依赖后续 `done` 或关闭;仅前台顶层停止状态清空所有流,后台或子代理停止只补齐自身流,运行中或未声明停止的状态不打断正文路径。
+ `file://` 与 `xdt-file://` / `xdt-audio://` 的文件路径按 URL 语法转换,HTTP 和 `cindy-media://` 地址保持原样。
+ 事件身份、Agent 元信息与权限回执不改写,原生 Agent 会话继续使用 B 的虚拟路径;旧消息不回填。
+ 回归见 `remote-agent/executor/__tests__/virtualWorkspace.test.ts` 与 `remote-agent/__tests__/eventProjection.test.ts`。
- **执行环境**(2026-10-07 裁决):A 上的命令(Claude 的 Bash、Pi 的 `exec.run`、Codex exec-server、
搜索)沿用 A 的 Desktop 完整环境,与本机 Agent 一致:真实用户目录、临时目录、`SSH_AUTH_SOCK`、
git / gh / npm 配置与用户自己的环境变量照常可用,不另造假 HOME,也不剥离凭证类变量。任务由 A 的