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): 保留文件路径写法并修复远程文件链接 (#6180)

Lizi8dc47a6c778e
diff --git a/apps/desktop/src/main/remote-agent/__tests__/eventProjection.test.ts b/apps/desktop/src/main/remote-agent/__tests__/eventProjection.test.ts
index 136d19123a..e6c09e5a70 100644
--- a/apps/desktop/src/main/remote-agent/__tests__/eventProjection.test.ts
+++ b/apps/desktop/src/main/remote-agent/__tests__/eventProjection.test.ts
@@ -44,6 +44,9 @@ async function eventsFrom(controller: ReturnType<typeof setup>['controller'], in
function text(event: AgentEvent): string { return (event.data as { text: string }).text; }
+/** 正文里还原的路径沿用 Agent 写的分隔符(Markdown 会把 `\.git` 这类反斜杠当转义);结构化路径字段仍用本机写法。 */
+function written(local: string, virtual = '/'): string { return virtual.startsWith('C:') ? local : local.replace(/\\/g, '/'); }
+
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:');
}
@@ -87,7 +90,7 @@ describe('remote file references on the task computer', () => {
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.map(text).join('')).toBe('文件在 ' + '\x60' + written(local, virtual) + '\x60' + ',打开[报告](<' + pathToFileURL(local).href + '#L2>)。');
expect(output.every((event) => (event.data as { isFinal: boolean }).isFinal === false)).toBe(true);
});
@@ -100,9 +103,9 @@ describe('remote file references on the task computer', () => {
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',
+ '\x60' + written(path.join(real, 'run.sh'), virtual) + ' --url /api/v1\x60',
+ '\x60' + written(path.join(real, 'run.sh'), virtual) + ' relative/input.txt\x60',
+ '\x60' + written(path.join(real, 'run.sh'), virtual) + ' && cat ' + written(path.join(real, 'src', 'input.txt'), virtual) + '\x60',
]);
});
@@ -118,7 +121,7 @@ describe('remote file references on the task computer', () => {
{ 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'),
+ '正在生成。', written(path.join(real, 'first.txt')), 'tool_use', written(path.join(real, 'second.txt')), '下一条', written(path.join(real, 'last.txt')),
]);
expect((output[3].data as { agentMessageId: string }).agentMessageId).toBe('two');
});
@@ -136,9 +139,9 @@ describe('remote file references on the task computer', () => {
delta('child-b', '.txt '),
]);
expect(output.filter((event) => event.agentMeta?.parentUuid === 'child-a').map(text).join(''))
- .toBe('A: ' + path.join(real, 'first.txt') + ' ');
+ .toBe('A: ' + written(path.join(real, 'first.txt')) + ' ');
expect(output.filter((event) => event.agentMeta?.parentUuid === 'child-b').map(text).join(''))
- .toBe('B: ' + path.join(real, 'second.txt') + ' ');
+ .toBe('B: ' + written(path.join(real, 'second.txt')) + ' ');
expect(output.every((event) => (event.data as { isFinal: boolean }).isFinal === false)).toBe(true);
});
@@ -156,9 +159,9 @@ describe('remote file references on the task computer', () => {
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') + ' ');
+ .toBe(written(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')]);
+ .toEqual([written(path.join(real, 'second.txt'))]);
});
it.each(['done', 'close'] as const)('flushes every unfinished child path at the %s boundary', async (boundary) => {
@@ -170,7 +173,7 @@ describe('remote file references on the task computer', () => {
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') })));
+ .toEqual(['child-a', 'child-b'].map((parentUuid) => ({ parentUuid, text: written(path.join(real, parentUuid + '.txt')) })));
if (boundary === 'done') expect(output.at(-1)?.type).toBe('done');
});
@@ -214,7 +217,7 @@ describe('remote file references on the task computer', () => {
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],
+ paths: [local, [local]], nested: { file_paths: [local] }, text: 'The docs say "' + written(path.join(real, 'README.md'), virtual) + ' links to /api/v1"', links: [pathToFileURL(local).href],
}]);
});
@@ -222,7 +225,7 @@ describe('remote file references on the task computer', () => {
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 expected = written(path.join(real, 'README.md'), virtual) + ' 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) },
})));
@@ -241,7 +244,7 @@ describe('remote file references on the task computer', () => {
{ 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(text(output[0])).toBe(written(path.join(root, 'extra', 'new.txt')));
expect(output[1].data).toEqual(permission);
expect(output[2].data).toMatchObject({ input: { file_path: '/unmapped/file.txt' } });
});
@@ -261,7 +264,7 @@ describe('remote file references on the task computer', () => {
.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 },
+ data: { text: '后台文件:\x60' + written(path.join(real, 'background.txt')) + '\x60', isFinal: true },
});
});
@@ -281,8 +284,8 @@ describe('remote file references on the task computer', () => {
{ ...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') + ' ',
+ written(path.join(real, 'background.txt')), boundary,
+ written(path.join(real, 'foreground.txt')) + ' ', written(path.join(real, 'other.txt')) + ' ',
]);
expect(output[0]).toMatchObject({ turnScope: 'background', backgroundTurnStartedAt: 1000 });
expect(output[3]).toMatchObject({ turnScope: 'background', backgroundTurnStartedAt: 2000 });
@@ -302,7 +305,7 @@ describe('remote file references on the task computer', () => {
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') + ' ',
+ 'error', written(path.join(real, 'background.txt')) + ' ',
]);
});
@@ -325,7 +328,7 @@ describe('remote file references on the task computer', () => {
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))) } })),
+ ...pending.map((event) => ({ ...event, data: { ...event.data as object, text: written(path.join(real, path.posix.basename(text(event)))) } })),
stopped,
]);
expect(input).toEqual(original);
@@ -350,7 +353,7 @@ describe('remote file references on the task computer', () => {
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') + ' ',
+ written(path.join(real, 'first.txt')), 'status', written(path.join(real, 'foreground.txt')) + ' ', written(path.join(real, 'second.txt')) + ' ',
]);
expect(output[0].agentMeta).toEqual({ parentUuid: 'child-a' });
expect(output[1]).toEqual(stopped);
@@ -366,7 +369,7 @@ describe('remote file references on the task computer', () => {
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.map((event) => event.type === 'text' ? text(event) : event.type)).toEqual(['status', written(path.join(real, 'report.txt')) + ' ']);
expect(output[0]).toEqual(status);
});
@@ -401,7 +404,7 @@ describe('remote file references on the task computer', () => {
]);
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 + '>)');
+ expect(text(final)).toBe('报告在 \x60' + written(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/__tests__/execServerProjection.e2e.test.ts b/apps/desktop/src/main/remote-agent/__tests__/execServerProjection.e2e.test.ts
index c358e09f34..799f38e6a0 100644
--- a/apps/desktop/src/main/remote-agent/__tests__/execServerProjection.e2e.test.ts
+++ b/apps/desktop/src/main/remote-agent/__tests__/execServerProjection.e2e.test.ts
@@ -60,6 +60,20 @@ describe.skipIf(!fs.existsSync(CODEX))('native exec-server workspace projection'
expect(output.trim()).toBe(virtual);
expect(actions).toEqual([expect.objectContaining({ kind: 'exec', cwd: project })]);
expect(JSON.stringify(messages)).not.toContain(project.replace(/\\/g, '\\\\'));
+
+ // Pinned Codex 0.159.2 writes through fs/writeFile (dataBase64), not fs/writeBlock.
+ // Exercise its real wire contract and verify an edit keeps the file's original path spelling.
+ const target = path.join(project, 'paths.json');
+ const original = { out: path.join(project, 'build', 'out.txt'), label: 'before' };
+ fs.writeFileSync(target, JSON.stringify(original));
+ send({ id: 3, method: 'fs/writeFile', params: {
+ path: 'file://' + virtual + '/paths.json',
+ dataBase64: Buffer.from(JSON.stringify({ out: virtual + '/build/out.txt', label: 'after' })).toString('base64'),
+ } });
+ await expect.poll(() => messages.find((item) => item.id === 3), { timeout: 5000 }).toBeDefined();
+ expect(messages.find((item) => item.id === 3)?.error).toBeUndefined();
+ expect(fs.readFileSync(target, 'utf8')).toBe(JSON.stringify({ ...original, label: 'after' }));
+ expect(actions.at(-1)).toEqual({ kind: 'write', path: target });
} finally {
relay.close();
await fsp.rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
diff --git a/apps/desktop/src/main/remote-agent/__tests__/execServerRelayConsent.test.ts b/apps/desktop/src/main/remote-agent/__tests__/execServerRelayConsent.test.ts
index 22fa9791fb..d4fd71ffb3 100644
--- a/apps/desktop/src/main/remote-agent/__tests__/execServerRelayConsent.test.ts
+++ b/apps/desktop/src/main/remote-agent/__tests__/execServerRelayConsent.test.ts
@@ -48,7 +48,7 @@ afterEach(() => {
fs.rmSync(root, { recursive: true, force: true });
});
-function setup() {
+function setup(authorize?: (action: ExecutorAction) => ExecutorGateDecision) {
const workspace = new ExecutorWorkspace({ workingDir: root });
const approved = new Set<string>();
const pending: Array<{ action: ExecutorAction; answer(allowed: boolean): void }> = [];
@@ -58,11 +58,11 @@ function setup() {
codexPath: 'codex',
cwd: root,
workspace,
- authorize: (action): ExecutorGateDecision => {
+ authorize: authorize ?? ((action): ExecutorGateDecision => {
if (!isSecret(action)) return { ok: true };
const key = action.kind === 'exec' || action.kind === 'fetch' ? '' : action.path;
return approved.delete(key) ? { ok: true, elevated: true } : { ok: false, reason: 'needs confirmation' };
- },
+ }),
confirm: (action) => new Promise<boolean>((resolve) => {
pending.push({
action,
@@ -118,6 +118,44 @@ describe('exec-server relay with confirmation on this computer', () => {
expect(pending).toEqual([]);
});
+ it('does not read old file content while a write is awaiting consent or after it is denied', async () => {
+ const target = path.join(root, 'denied.txt');
+ fs.writeFileSync(target, 'old content');
+ const { relay, send, pending, replies, sentIds } = setup(() => ({ ok: false, reason: 'write denied' }));
+ const read = vi.spyOn(fs, 'readFileSync');
+ try {
+ send({ id: 1, method: 'fs/writeFile', params: { path: target, dataBase64: Buffer.from('new content').toString('base64') } });
+ await vi.waitFor(() => expect(pending).toHaveLength(1));
+ expect(read).not.toHaveBeenCalledWith(target);
+ pending[0].answer(false);
+ await vi.waitFor(() => expect(replies).toEqual([{ id: 1, error: { code: -32001, message: 'write denied' } }]));
+ expect(read).not.toHaveBeenCalledWith(target);
+ expect(sentIds()).toEqual([]);
+ } finally {
+ read.mockRestore();
+ relay.close();
+ }
+ });
+
+ it('reads old content only after the earlier confirmation has released the queued write', async () => {
+ const target = path.join(root, 'queued.txt');
+ fs.writeFileSync(target, 'old content');
+ const { relay, send, pending, sentIds } = setup();
+ const read = vi.spyOn(fs, 'readFileSync');
+ try {
+ send({ id: 1, method: 'fs/readFile', params: { path: path.join(root, '.env') } });
+ send({ id: 2, method: 'fs/writeFile', params: { path: target, dataBase64: Buffer.from('new content').toString('base64') } });
+ await vi.waitFor(() => expect(pending).toHaveLength(1));
+ expect(read).not.toHaveBeenCalledWith(target);
+ pending[0].answer(true);
+ await vi.waitFor(() => expect(sentIds()).toEqual([1, 2]));
+ expect(read).toHaveBeenCalledWith(target);
+ } finally {
+ read.mockRestore();
+ relay.close();
+ }
+ });
+
it('checks fs/open replace as a write before allowing the handle stream', async () => {
const { send, pending, replies } = setup();
send({ id: 1, method: 'fs/open', params: { handleId: 'h1', mode: 'replace', path: path.join(root, '.env') } });
diff --git a/apps/desktop/src/main/remote-agent/controller/eventProjection.ts b/apps/desktop/src/main/remote-agent/controller/eventProjection.ts
index a60ac64f79..29adf23413 100644
--- a/apps/desktop/src/main/remote-agent/controller/eventProjection.ts
+++ b/apps/desktop/src/main/remote-agent/controller/eventProjection.ts
@@ -51,9 +51,10 @@ function localText(value: string, workspace: ExecutorWorkspace, context: PathTex
}
// 尖括号链接是明确的完整路径。代码段也可能是命令,含空白时只有已存在的完整
// 文件/目录才按单一路径处理;其余回到下方逐 token 投影,保留参数和正文中的斜杠。
+ // 分隔符沿用 Agent 的写法:Markdown 会把链接里的 `\.git`、`\_x` 当成转义吃掉。
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);
+ const local = workspace.mapAliasInText(remote);
if (code !== undefined && local !== remote && /\s/.test(remote) && !fs.existsSync(local)) return literal;
return local === remote ? literal : code !== undefined ? '\x60' + local + '\x60' : '<' + local + '>';
});
@@ -75,6 +76,20 @@ function localValue(value: unknown, workspace: ExecutorWorkspace, key = ''): unk
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, IDENTITY_FIELDS.has(key) ? item : localValue(item, workspace, key)]));
}
+/**
+ * 计划审阅:计划正文与计划文件按本机路径展示和保存,计划里的文件才能点开。权限与提问的回执要与
+ * 原请求逐字对应,保持原样。
+ */
+export function localPlanReview<T extends { kind: string }>(request: T, workspace: ExecutorWorkspace): T {
+ if (request.kind !== 'plan_review') return request;
+ const { plan, planFilePath } = request as { plan?: unknown; planFilePath?: unknown };
+ return {
+ ...request,
+ ...(typeof plan === 'string' ? { plan: localText(plan, workspace) } : {}),
+ ...(typeof planFilePath === 'string' ? { planFilePath: workspace.mapAlias(planFilePath) } : {}),
+ };
+}
+
/** 只暂存末尾未闭合的路径,避免地址被多个 delta 切开后漏掉映射。 */
function pendingPathIndex(text: string, workspace: ExecutorWorkspace): number {
let pending = text.length;
diff --git a/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts b/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts
index ab092f1d57..071beb5acc 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 {
type RemoteAgentStreamItem,
} from '@cindy/device-link';
+import { readExistingTextSync } from '../executor/files';
import type { ExecutorAction, ExecutorGateDecision } from '../executor/gate';
import { resolveExecutorShell } from '../executor/shell';
import type { ExecutorWorkspace } from '../executor/workspace';
@@ -114,16 +115,16 @@ export function execServerActions(method: string, params: unknown, cwd: string):
.map((key) => fromFileUrl(record[key], cwd))
.filter((value): value is string => !!value);
if (TREE_READ_METHODS.has(method)) return paths.map((target) => ({ kind: 'read', path: target, scope: 'tree' }));
- // fs/open also handles writes: Codex replace/write mode creates or truncates a file, while
- // the later fs/writeBlock request carries only a handle and no path. Check the write at open.
- // An omitted mode is the legacy read-only shape; every explicit unknown mode is fail-closed.
+ // Pinned Codex 0.159.2 uses a read-only fs/open and writes through fs/writeFile.
+ // Keep explicit non-read modes fail-closed for newer protocols; they are not evidence that
+ // their later handle-based write methods are supported by this relay.
const readOnlyOpen = method !== 'fs/open' || record.mode === undefined || record.mode === 'read';
const kind = READ_METHODS.has(method) && readOnlyOpen ? 'read' : 'write';
return paths.map((target) => ({ kind, path: target }) as ExecutorAction);
}
/** 映射协议路径、命令和可逆的 UTF-8 文件数据;二进制内容保持原样。 */
-export function mapExecServerParams(value: unknown, workspace: ExecutorWorkspace, method?: string): unknown {
+export function mapExecServerParams(value: unknown, workspace: ExecutorWorkspace, method?: string, mapFileData = true): 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']) {
@@ -137,10 +138,31 @@ export function mapExecServerParams(value: unknown, workspace: ExecutorWorkspace
}
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 mapFileData ? mapExecServerFileData(result, workspace, method) : result;
+}
+
+/**
+ * 授权通过后、实际转发前才读写入目标的原内容,排队中的请求也在出队后读取最新内容。
+ * 路径与命令的映射仍在权限检查前完成,确保 gate 检查的是实际执行的操作。
+ */
+function mapExecServerFileData(value: unknown, workspace: ExecutorWorkspace, method?: string): unknown {
+ if (!method?.startsWith('fs/write') || !value || typeof value !== 'object' || Array.isArray(value)) return value;
+ const result = value as Record<string, unknown>;
+ if (typeof result.dataBase64 !== 'string') return value;
+ return { ...result, dataBase64: workspace.mapInputFromAgent(Buffer.from(result.dataBase64, 'base64'),
+ existingTextFor(result.path, workspace)).toString('base64') };
+}
+
+/** 旧内容仅用于还原写入路径的原写法,不回给 Agent;凭证类文件不预读。 */
+function existingTextFor(target: unknown, workspace: ExecutorWorkspace): string | null {
+ if (typeof target !== 'string') return null;
+ let local: string;
+ try {
+ local = target.startsWith('file://') ? fileURLToPath(target) : target;
+ } catch {
+ return null;
}
- return result;
+ return workspace.isSensitive(local) ? null : readExistingTextSync(local);
}
/** JSON 层逐字符串投影;文件 base64 数据保持原始字节,进程输出单独解码。 */
@@ -271,12 +293,18 @@ export class ExecServerRelay {
let actions: ExecutorAction[] = [];
if (message && typeof message.method === 'string' && message.id !== undefined) {
this.counts.requests += 1;
- message.params = mapExecServerParams(message.params, this.deps.workspace, message.method);
+ message.params = mapExecServerParams(message.params, this.deps.workspace, message.method, false);
data = JSON.stringify(message);
actions = execServerActions(message.method, message.params, this.deps.cwd);
}
const id = message?.id;
- const line = `${data}\n`;
+ // 延迟到所有 action 获准之后,不能为了内容保真提前读取被拒绝的目标。
+ const line = () => {
+ if (message && typeof message.method === 'string' && message.id !== undefined) {
+ return JSON.stringify({ ...message, params: mapExecServerFileData(message.params, this.deps.workspace, message.method) }) + '\n';
+ }
+ return data + '\n';
+ };
if (connection.queue) {
this.enqueue(connection, () => this.deliver(connId, connection, id, line, actions));
return;
@@ -293,7 +321,7 @@ export class ExecServerRelay {
this.enqueue(connection, () => this.deliver(connId, connection, id, line, rest));
return;
}
- connection.child.stdin.write(line);
+ connection.child.stdin.write(line());
}
private enqueue(connection: Connection, task: () => Promise<void>): void {
@@ -306,7 +334,7 @@ export class ExecServerRelay {
});
}
- private async deliver(connId: string, connection: Connection, id: unknown, line: string, actions: ExecutorAction[]): Promise<void> {
+ private async deliver(connId: string, connection: Connection, id: unknown, line: () => string, actions: ExecutorAction[]): Promise<void> {
for (const action of actions) {
let decision = this.deps.authorize(action);
if (!decision.ok && this.deps.confirm && await this.deps.confirm(action)) decision = this.deps.authorize(action);
@@ -316,7 +344,7 @@ export class ExecServerRelay {
return;
}
}
- if (!connection.closed) connection.child.stdin.write(line);
+ if (!connection.closed) connection.child.stdin.write(line());
}
private reject(connId: string, id: unknown, decision: ExecutorGateDecision): void {
diff --git a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts b/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts
index c857dd19fa..4d424ef9f9 100644
--- a/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts
+++ b/apps/desktop/src/main/remote-agent/controller/proxyHandle.ts
@@ -30,7 +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';
+import { localPlanReview, RemoteEventProjection } from './eventProjection';
const MAX_REMEMBERED_SEND_CALLBACKS = 64;
@@ -402,11 +402,18 @@ export function createRemoteAgentHandle(deps: RemoteHandleDeps): RemoteAgentHand
: { kind: 'permission', behavior: 'deny', reason: 'interaction_unavailable' };
return { type: 'interaction', result: decision };
}
- const decision = await resolver(request);
+ let decision = await resolver(localPlanReview(request, deps.workspace));
if (decision.kind === 'permission' && decision.behavior === 'allow') {
const effective = decision.updatedInput ? { ...request, input: decision.updatedInput } : request;
for (const action of approvalActionsFor(effective, deps.workspace)) deps.recordApproval(action);
}
+ // 用户改过的计划按本机路径展示,交回 Agent 前换回它那边的写法。
+ if (decision.kind === 'plan_review') {
+ decision = { ...decision,
+ ...(typeof decision.editedPlan === 'string' ? { editedPlan: deps.workspace.mapTextForAgent(decision.editedPlan) } : {}),
+ ...(!decision.dismissed && typeof decision.reason === 'string' ? { reason: deps.workspace.mapTextForAgent(decision.reason) } : {}),
+ };
+ }
return { type: 'interaction', result: JSON.parse(JSON.stringify(decision)) };
}
diff --git a/apps/desktop/src/main/remote-agent/executor/__tests__/pathFidelity.test.ts b/apps/desktop/src/main/remote-agent/executor/__tests__/pathFidelity.test.ts
new file mode 100644
index 0000000000..5714ffb1a7
--- /dev/null
+++ b/apps/desktop/src/main/remote-agent/executor/__tests__/pathFidelity.test.ts
@@ -0,0 +1,529 @@
+/**
+ * 远程供应商的文件读写与引用:Agent 看到的虚拟路径、它写进文件和回复里的路径、命令与文件操作实际
+ * 落盘的位置必须是同一个地方;没改动的文件内容写回后逐字节不变。
+ */
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import type { AgentEvent, InteractionDecision, InteractionRequest } from '@cindy/maker-core';
+import type { Link, Root } from 'mdast';
+import remarkParse from 'remark-parse';
+import { unified } from 'unified';
+import { visit } from 'unist-util-visit';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { mapClaudeHostedEvent } from '../../controller/eventMap';
+import { RemoteEventProjection } from '../../controller/eventProjection';
+import { mapExecServerParams } from '../../controller/execServerRelay';
+import { createRemoteAgentHandle } from '../../controller/proxyHandle';
+import type { RemoteAgentRunClient } from '../../controller/runClient';
+import { RemoteExecutor } from '../executor';
+import { ExecutorGate } from '../gate';
+import { ExecutorWorkspace } from '../workspace';
+
+let root: string;
+beforeEach(() => { root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-path-fidelity-'))); });
+afterEach(() => { fs.rmSync(root, { recursive: true, force: true }); });
+
+const VIRTUAL_ROOT = '/Users/agent/Library/Application Support/Cindy/remote-agent/workspaces/0123456789abcdef/run/fs';
+const SHADOW = VIRTUAL_ROOT + '/workspace/p/p';
+const PARENT = VIRTUAL_ROOT + '/workspace/p';
+
+/** 与控制端 shadowAliases 一致:工作目录和它的上级目录各对应一个虚拟目录。 */
+function setup(workingDir = path.join(root, 'fp2', 'flash-party-retro')) {
+ fs.mkdirSync(workingDir, { recursive: true });
+ const parent = path.dirname(workingDir);
+ const workspace = new ExecutorWorkspace({ workingDir, aliases: [{ from: SHADOW, to: workingDir }, { from: PARENT, to: parent }] });
+ workspace.setVirtualRoot(VIRTUAL_ROOT);
+ const executor = new RemoteExecutor({ workspace, gate: new ExecutorGate(workspace, 'full'), rgPath: 'unused' });
+ return { parent, workingDir, workspace, executor };
+}
+
+/** Agent 写的 `/` 路径还原到本机时的写法(Windows 上沿用 `/`)。 */
+const agentStyle = (local: string) => local.replace(/\\/g, '/');
+
+function markdownLinks(markdown: string): string[] {
+ const urls: string[] = [];
+ visit(unified().use(remarkParse).parse(markdown) as Root, 'link', (node: Link) => { urls.push(node.url); });
+ return urls;
+}
+
+function readBack(result: { content: Array<{ type: string; text?: string }> }): string {
+ return result.content.map((item) => item.text ?? '').join('').split('\n').map((line) => line.replace(/^\s*\d+\t/, '')).join('\n');
+}
+
+describe('remote provider file paths', () => {
+ it.each(['flash-party-retro.git', 'flash-party-retro-v1'])('keeps the sibling folder %s apart from the workspace everywhere', async (sibling) => {
+ const { parent, workspace, executor } = setup();
+ const real = path.join(parent, sibling, 'fp-devlog', 'v20', '验收报告.html');
+ fs.mkdirSync(path.dirname(real), { recursive: true });
+ try {
+ // Agent 看到的是按完整目录段换算的路径,不会把 `flash-party-retro` 当成 `.git` 目录的前缀。
+ const seen = workspace.mapTextForAgent('report: ' + real).slice('report: '.length);
+ expect(seen).toBe(PARENT + '/' + sibling + '/fp-devlog/v20/验收报告.html');
+ expect(workspace.resolve(seen)).toBe(real);
+ await executor.callTool('Write', { file_path: seen, content: 'v20' });
+ expect(fs.readFileSync(real, 'utf8')).toBe('v20');
+ expect(fs.readdirSync(parent).sort()).toEqual(['flash-party-retro', sibling].sort());
+ // 回复里的链接和命令里的路径指向写文件的同一处。
+ const [link] = markdownLinks(workspace.mapTextFromAgent('请你验收:[报告](<' + seen + '>)'));
+ expect(fs.readFileSync(link, 'utf8')).toBe('v20');
+ expect(workspace.mapCommand('cat "' + seen + '"')).toBe('cat "' + agentStyle(real) + '"');
+ // 以前把它投影成 `…/p.git` 的旧会话里,同一个写法在文字、命令和文件操作中也落在同一处。
+ const legacy = SHADOW + sibling.slice('flash-party-retro'.length) + '/a.txt';
+ const literal = path.join(parent, 'p' + sibling.slice('flash-party-retro'.length), 'a.txt');
+ expect(workspace.resolve(legacy)).toBe(literal);
+ expect(workspace.mapTextFromAgent(legacy)).toBe(agentStyle(literal));
+ } finally {
+ await executor.close();
+ }
+ });
+
+ it('checks the disk before treating a space or bracket after the workspace as the end of the path', async () => {
+ const { parent, workingDir, workspace, executor } = setup();
+ try {
+ for (const name of ['flash-party-retro copy', 'flash-party-retro (1)']) {
+ const real = path.join(parent, name, 'a.txt');
+ fs.mkdirSync(path.dirname(real), { recursive: true });
+ fs.writeFileSync(real, name);
+ const seen = workspace.mapTextForAgent(real);
+ expect(seen.startsWith(PARENT + '/flash-party-retro')).toBe(true);
+ expect(workspace.resolve(seen)).toBe(real);
+ }
+ // 没有这样的同级目录时,空格、标点后面就是正文。
+ expect(workspace.mapTextForAgent(workingDir + ' is ready, ' + workingDir + '. Done')).toBe(SHADOW + ' is ready, ' + SHADOW + '. Done');
+ const local = agentStyle(workingDir);
+ expect(workspace.mapTextFromAgent('在 ' + SHADOW + '。见 `' + SHADOW + '/src/a.ts:12`, ' + SHADOW + '.'))
+ .toBe('在 ' + local + '。见 `' + local + '/src/a.ts:12`, ' + local + '.');
+ } finally {
+ await executor.close();
+ }
+ });
+
+ it('keeps shell expansions immediately after a mapped directory prefix', async () => {
+ const { workingDir, workspace, executor } = setup();
+ try {
+ const local = agentStyle(workingDir);
+ for (const suffix of ['*', '?', '[ab]', '{a,b}', '$suffix', '${suffix}', '$' + '(printf x)', String.fromCharCode(96) + 'printf x' + String.fromCharCode(96)]) {
+ expect(workspace.mapCommand('ls ' + SHADOW + suffix)).toBe('ls ' + local + suffix);
+ }
+ for (const suffix of ['$suffix', '${suffix}']) {
+ expect(workspace.mapCommand('ls "' + SHADOW + suffix + '"')).toBe('ls "' + local + suffix + '"');
+ }
+ for (const suffix of ['%SUFFIX%', '!SUFFIX!']) {
+ expect(workspace.mapCommand('dir "' + SHADOW + suffix + '"', 'cmd')).toBe('dir "' + local + suffix + '"');
+ }
+ for (const quote of ['', '"']) {
+ for (const variable of ['PATH', 'Path', 'CLASSPATH', 'INCLUDE', 'LIB']) {
+ expect(workspace.mapCommand('set ' + quote + variable + '=' + SHADOW + ';%PATH%' + quote, 'cmd'))
+ .toBe('set ' + quote + variable + '=' + local + ';%PATH%' + quote);
+ }
+ }
+ expect(workspace.mapCommand('type "' + SHADOW + ';literal"', 'cmd'))
+ .toBe('type "' + agentStyle(workspace.resolve(SHADOW + ';literal')) + '"');
+ expect(workspace.mapCommand('PATH=' + SHADOW + ':$PATH command')).toBe('PATH=' + local + ':$PATH command');
+ for (const variable of ['NODE_PATH', 'PYTHONPATH', 'LD_LIBRARY_PATH', 'XDG_DATA_DIRS', 'PERL5LIB']) {
+ for (const quote of ['', '"', "'"]) {
+ expect(workspace.mapCommand(variable + '=' + quote + SHADOW + ':$' + variable + quote + ' command'))
+ .toBe(variable + '=' + quote + local + ':$' + variable + quote + ' command');
+ }
+ }
+ for (const variable of ['PATH', 'NODE_PATH']) {
+ for (const quote of ['', '"', "'"]) {
+ expect(workspace.mapCommand(variable + '+=' + quote + ':' + SHADOW + ':$' + variable + quote + ' command'))
+ .toBe(variable + '+=' + quote + ':' + local + ':$' + variable + quote + ' command');
+ }
+ }
+ expect(workspace.mapCommand('FILE+="' + SHADOW + ':literal" command'))
+ .toBe('FILE+="' + agentStyle(workspace.resolve(SHADOW + ':literal')) + '" command');
+ expect(workspace.mapCommand('FILE="' + SHADOW + ':literal" command'))
+ .toBe('FILE="' + agentStyle(workspace.resolve(SHADOW + ':literal')) + '" command');
+ expect(workspace.mapCommand('set "FILE=' + SHADOW + ';literal"', 'cmd'))
+ .toBe('set "FILE=' + agentStyle(workspace.resolve(SHADOW + ';literal')) + '"');
+ const windowsWorkspace = new ExecutorWorkspace({ workingDir, aliases: [{ from: 'C:/agent/workspace', to: workingDir }] });
+ for (const virtual of ['C:/agent/workspace', 'C:\\agent\\workspace']) {
+ expect(windowsWorkspace.mapCommand('set "CLASSPATH=' + virtual + ';%CLASSPATH%"', 'cmd'))
+ .toBe('set "CLASSPATH=' + local + ';%CLASSPATH%"');
+ }
+ expect(workspace.mapCommand('cat ' + SHADOW + ':literal'))
+ .toBe('cat ' + agentStyle(workspace.resolve(SHADOW + ':literal')));
+ for (const quote of ['"', "'"]) {
+ expect(workspace.mapCommand('PATH=' + quote + SHADOW + ':$PATH' + quote + ' command'))
+ .toBe('PATH=' + quote + local + ':$PATH' + quote + ' command');
+ expect(workspace.mapCommand('cat ' + quote + SHADOW + ':literal' + quote))
+ .toBe('cat ' + quote + agentStyle(workspace.resolve(SHADOW + ':literal')) + quote);
+ expect(workspace.mapCommand('echo ' + quote + 'PATH=' + SHADOW + ':literal' + quote))
+ .toBe('echo ' + quote + 'PATH=' + agentStyle(workspace.resolve(SHADOW + ':literal')) + quote);
+ }
+ // 单引号里的变量和 glob、双引号里的 glob 是目录名的字面部分,必须按父目录别名解析。
+ for (const suffix of ['$suffix', '*', '?', '[ab]']) {
+ const virtual = SHADOW + suffix;
+ expect(workspace.mapCommand("ls '" + virtual + "'")).toBe("ls '" + agentStyle(workspace.resolve(virtual)) + "'");
+ }
+ for (const suffix of ['*', '?', '[ab]']) {
+ const virtual = SHADOW + suffix;
+ expect(workspace.mapCommand('ls "' + virtual + '"')).toBe('ls "' + agentStyle(workspace.resolve(virtual)) + '"');
+ }
+ } finally {
+ await executor.close();
+ }
+ });
+
+ it('keeps dynamic suffixes in file contents and recognizes existing literal sibling names', async () => {
+ const { parent, workingDir, workspace, executor } = setup();
+ try {
+ const script = ['*', '?', '$suffix', '${suffix}', '%SUFFIX%'].map((suffix) => 'echo ' + SHADOW + suffix).join('\n');
+ const expected = ['*', '?', '$suffix', '${suffix}', '%SUFFIX%'].map((suffix) => 'echo ' + agentStyle(workingDir) + suffix).join('\n');
+ await executor.callTool('Write', { file_path: SHADOW + '/script.sh', content: script });
+ expect(fs.readFileSync(path.join(workingDir, 'script.sh'), 'utf8')).toBe(expected);
+ expect(workspace.mapTextForAgent(expected)).toBe(script);
+ expect(workspace.mapContentFromAgent(script, expected)).toBe(expected);
+ for (const suffix of ['$suffix', '%SUFFIX%']) {
+ const literal = path.join(parent, 'p' + suffix);
+ fs.mkdirSync(literal);
+ expect(workspace.mapContentFromAgent('literal: ' + SHADOW + suffix))
+ .toBe('literal: ' + agentStyle(literal));
+ const realSibling = workingDir + suffix;
+ fs.mkdirSync(realSibling);
+ expect(workspace.mapTextForAgent('literal: ' + realSibling))
+ .toBe('literal: ' + PARENT + '/flash-party-retro' + suffix);
+ }
+ } finally {
+ await executor.close();
+ }
+ });
+
+ it.each(['$suffix', '%SUFFIX%'])('preserves an unchanged dynamic path ending in %s when another line is edited', async (suffix) => {
+ const { parent, workingDir, workspace, executor } = setup();
+ fs.mkdirSync(path.join(parent, 'p' + suffix));
+ try {
+ const file = path.join(workingDir, 'dynamic.txt');
+ for (const tail of ['', '/child/file.txt', '\\child\\file.txt']) {
+ const original = 'first=' + workingDir + suffix + tail + '\nunchanged=1';
+ fs.writeFileSync(file, original);
+ const seen = readBack(await executor.callTool('Read', { file_path: SHADOW + '/dynamic.txt' }));
+ expect(seen).toBe('first=' + SHADOW + suffix + tail + '\nunchanged=1');
+ const edited = seen.replace('unchanged=1', 'unchanged=2');
+ expect(workspace.mapContentFromAgent(edited, original)).toBe(original.replace('unchanged=1', 'unchanged=2'));
+ await executor.callTool('Write', { file_path: SHADOW + '/dynamic.txt', content: edited });
+ expect(fs.readFileSync(file, 'utf8')).toBe(original.replace('unchanged=1', 'unchanged=2'));
+ }
+ } finally {
+ await executor.close();
+ }
+ });
+
+ it.each([' copy', ' (1)', '.git', '-v1'])('maps quoted sibling suffix %s to the same location as file tools', async (suffix) => {
+ const { parent, workspace, executor } = setup();
+ try {
+ const virtual = SHADOW + suffix;
+ const expected = path.join(parent, 'p' + suffix);
+ expect(workspace.resolve(virtual)).toBe(expected);
+ for (const quote of ['"', "'"]) {
+ expect(workspace.mapCommand('mkdir -p ' + quote + virtual + quote))
+ .toBe('mkdir -p ' + quote + agentStyle(expected) + quote);
+ }
+ await executor.callTool('Write', { file_path: virtual + '/a.txt', content: 'same folder' });
+ expect(fs.readFileSync(path.join(expected, 'a.txt'), 'utf8')).toBe('same folder');
+ const seen = virtual + '/a.txt';
+ const local = agentStyle(path.join(expected, 'a.txt'));
+ expect(workspace.mapTextFromAgent('report: ' + seen)).toBe('report: ' + local);
+ expect(workspace.mapContentFromAgent('report: ' + seen)).toBe('report: ' + local);
+ } finally {
+ await executor.close();
+ }
+ });
+
+ // symlink-platform-skip: Windows filesystems are case-insensitive, so they cannot represent this POSIX alias distinction.
+ it.skipIf(process.platform === 'win32')('keeps case-distinct canonical aliases on case-sensitive hosts', ({ skip }) => {
+ const actual = path.join(root, 'actual', 'project');
+ const link = path.join(root, 'actual', 'PROJECT');
+ fs.mkdirSync(actual, { recursive: true });
+ // macOS 等主机也可能使用大小写不敏感的卷,按当前临时目录的实际能力判断。
+ if (fs.existsSync(link)) return skip();
+ fs.symlinkSync(actual, link, 'dir');
+ const workspace = new ExecutorWorkspace({ workingDir: link, aliases: [{ from: SHADOW, to: link }] });
+ workspace.setVirtualRoot(VIRTUAL_ROOT);
+ expect(workspace.mapTextForAgent(path.join(actual, 'src', 'main.ts')))
+ .toBe(SHADOW + '/src/main.ts');
+ });
+
+ it('writes an unchanged file back byte for byte through every write path', async () => {
+ const { workingDir, workspace, executor } = setup();
+ const forward = workingDir.replace(/\\/g, '/');
+ const spellings = [
+ workingDir + path.sep + 'src' + path.sep + 'a.ts',
+ ...(process.platform === 'win32' ? [
+ forward + '/build/out.js',
+ '/' + forward[0].toLowerCase() + forward.slice(2) + '/scripts/run.sh',
+ workingDir.toUpperCase() + '\\LOUD.TXT',
+ '/tmp/' + path.relative(os.tmpdir(), workingDir).replace(/\\/g, '/') + '/cache',
+ ] : []),
+ ];
+ const lines = [
+ '# paths',
+ ...spellings.map((item, index) => 'const p' + index + ' = ' + JSON.stringify(item) + ';'),
+ 'raw: ' + spellings.join(' '),
+ ];
+ // Read 工具按行给出内容(不带行尾),换行风格由 Write 决定,与路径无关;Pi 与 Codex 整文件读写保留 CRLF。
+ const original = lines.join('\n');
+ const crlf = lines.join('\r\n');
+ const json = JSON.stringify({ root: workingDir, nested: { file: spellings.at(-1) } }, null, 2);
+ const target = path.join(workingDir, 'paths.ts');
+ const config = path.join(workingDir, 'config.json');
+ fs.writeFileSync(target, original);
+ try {
+ // Claude:Read 后原样 Write 回去。
+ const seen = readBack(await executor.callTool('Read', { file_path: SHADOW + '/paths.ts' }));
+ expect(seen).not.toContain(path.join('fp2', 'flash-party-retro'));
+ expect(seen).toContain(SHADOW + '/src/a.ts');
+ await executor.callTool('Write', { file_path: SHADOW + '/paths.ts', content: seen });
+ expect(fs.readFileSync(target, 'utf8')).toBe(original);
+ // Pi:fs.read 后原样 fs.write。
+ fs.writeFileSync(target, crlf);
+ fs.writeFileSync(config, json);
+ for (const file of ['paths.ts', 'config.json']) {
+ const read = await executor.handle('fs.read', { path: SHADOW + '/' + file }) as { data: string };
+ expect(Buffer.from(read.data, 'base64').toString('utf8')).not.toContain(path.join('fp2', 'flash-party-retro'));
+ await executor.handle('fs.write', { path: SHADOW + '/' + file, data: read.data });
+ }
+ expect(fs.readFileSync(target, 'utf8')).toBe(crlf);
+ expect(fs.readFileSync(config, 'utf8')).toBe(json);
+ // Codex:整文件写入同一份虚拟内容。
+ const virtual = workspace.mapTextForAgent(crlf);
+ const params = mapExecServerParams({ path: SHADOW + '/paths.ts', dataBase64: Buffer.from(virtual).toString('base64') }, workspace, 'fs/writeFile') as { dataBase64: string };
+ expect(Buffer.from(params.dataBase64, 'base64').toString('utf8')).toBe(crlf);
+ } finally {
+ await executor.close();
+ }
+ });
+
+ it('writes new paths with the separators the Agent used so source strings keep their meaning', async () => {
+ const { workingDir, executor } = setup();
+ try {
+ await executor.callTool('Write', { file_path: SHADOW + '/build.js', content: 'const out = "' + SHADOW + '/build/out.js";\n' });
+ expect(fs.readFileSync(path.join(workingDir, 'build.js'), 'utf8')).toBe('const out = "' + agentStyle(workingDir) + '/build/out.js";\n');
+ await executor.handle('fs.write', { path: SHADOW + '/new.json', data: Buffer.from(JSON.stringify({ out: SHADOW + '/dist' })).toString('base64') });
+ expect(JSON.parse(fs.readFileSync(path.join(workingDir, 'new.json'), 'utf8'))).toEqual({ out: agentStyle(workingDir) + '/dist' });
+ } finally {
+ await executor.close();
+ }
+ });
+
+ it('edits text around a path that the file spells differently from the Agent', async () => {
+ const actual = path.join(root, 'actual', 'flash-party-retro');
+ fs.mkdirSync(actual, { recursive: true });
+ const link = path.join(root, 'link');
+ fs.symlinkSync(actual, link, process.platform === 'win32' ? 'junction' : 'dir');
+ // 任务工作目录是链接,文件里记的是真实目录;两者对 Agent 都是同一个虚拟目录。
+ const { workspace, executor } = setup(link);
+ const file = path.join(actual, 'notes.md');
+ const content = [
+ 'output: ' + path.join(actual, 'out', 'a.txt'),
+ 'again: ' + path.join(actual, 'out', 'a.txt'),
+ ...(process.platform === 'win32' ? ['slash: ' + actual.replace(/\\/g, '/') + '/out/b.txt'] : []),
+ '',
+ ].join('\n');
+ fs.writeFileSync(file, content);
+ try {
+ const seen = readBack(await executor.callTool('Read', { file_path: SHADOW + '/notes.md' }));
+ expect(seen).toContain('output: ' + SHADOW + '/out/a.txt');
+ const result = await executor.callTool('Edit', {
+ file_path: SHADOW + '/notes.md',
+ old_string: 'again: ' + SHADOW + '/out/a.txt',
+ new_string: 'again: ' + SHADOW + '/out/a.txt (checked)',
+ });
+ expect(result.isError).toBeFalsy();
+ expect(fs.readFileSync(file, 'utf8')).toBe(content.replace(
+ 'again: ' + path.join(actual, 'out', 'a.txt'),
+ 'again: ' + path.join(actual, 'out', 'a.txt') + ' (checked)',
+ ));
+ if (process.platform === 'win32') {
+ // 文件里用 `/` 写的路径同样找得到;新写的路径用任务工作目录的写法和 Agent 的分隔符。
+ const slash = await executor.callTool('Edit', { file_path: SHADOW + '/notes.md', old_string: SHADOW + '/out/b.txt', new_string: SHADOW + '/out/c.txt' });
+ expect(slash.isError).toBeFalsy();
+ expect(fs.readFileSync(file, 'utf8')).toContain('slash: ' + agentStyle(link) + '/out/c.txt');
+ }
+ } finally {
+ await executor.close();
+ }
+ });
+
+ it('keeps the matching spelling when the same path is written two ways in one file', async () => {
+ const actual = path.join(root, 'actual', 'flash-party-retro');
+ fs.mkdirSync(actual, { recursive: true });
+ const link = path.join(root, 'link');
+ fs.symlinkSync(actual, link, process.platform === 'win32' ? 'junction' : 'dir');
+ const { executor } = setup(link);
+ const file = path.join(actual, 'twice.md');
+ const content = 'a: ' + path.join(link, 'x.txt') + '\nb: ' + path.join(actual, 'x.txt') + '\n';
+ fs.writeFileSync(file, content);
+ try {
+ await executor.callTool('Read', { file_path: SHADOW + '/twice.md' });
+ const result = await executor.callTool('Edit', {
+ file_path: SHADOW + '/twice.md', old_string: 'b: ' + SHADOW + '/x.txt', new_string: 'b: ' + SHADOW + '/x.txt (ok)',
+ });
+ expect(result.isError).toBeFalsy();
+ expect(fs.readFileSync(file, 'utf8')).toBe('a: ' + path.join(link, 'x.txt') + '\nb: ' + path.join(actual, 'x.txt') + ' (ok)\n');
+ } finally {
+ await executor.close();
+ }
+ });
+
+ it.each(['text', 'json'])('counts and replaces every virtual match with different original spellings in %s', async (format) => {
+ const actual = path.join(root, 'actual', 'project');
+ const link = path.join(root, 'linked-project');
+ fs.mkdirSync(actual, { recursive: true });
+ fs.symlinkSync(actual, link, process.platform === 'win32' ? 'junction' : 'dir');
+ const { executor } = setup(link);
+ const native = path.join(link, 'x.txt');
+ const forward = agentStyle(path.join(actual, 'x.txt'));
+ const untouched = 'c: ' + path.join(actual, 'keep.txt') + '\r\n';
+ const original = format === 'json' ? JSON.stringify({ a: native, b: forward, keep: path.join(actual, 'keep.txt') })
+ : 'a: ' + native + '\r\nb: ' + forward + '\r\n' + untouched;
+ const file = path.join(actual, 'all.md');
+ fs.writeFileSync(file, original);
+ try {
+ await executor.callTool('Read', { file_path: SHADOW + '/all.md' });
+ const edit = { file_path: SHADOW + '/all.md', old_string: SHADOW + '/x.txt', new_string: SHADOW + '/y.txt' };
+ const ambiguous = await executor.callTool('Edit', edit);
+ expect(ambiguous.isError).toBe(true);
+ expect(ambiguous.content).toEqual(expect.arrayContaining([expect.objectContaining({ text: expect.stringContaining('Found 2 matches') })]));
+ expect(fs.readFileSync(file, 'utf8')).toBe(original);
+ const all = await executor.callTool('Edit', { ...edit, replace_all: true });
+ expect(all.isError).toBeFalsy();
+ const expected = format === 'json' ? JSON.stringify({ a: agentStyle(link) + '/y.txt', b: agentStyle(link) + '/y.txt', keep: path.join(actual, 'keep.txt') })
+ : 'a: ' + agentStyle(link) + '/y.txt\r\nb: ' + agentStyle(link) + '/y.txt\r\n' + untouched;
+ expect(fs.readFileSync(file, 'utf8')).toBe(expected);
+ } finally {
+ await executor.close();
+ }
+ });
+
+ it('keeps each unchanged spelling when earlier occurrences are deleted, inserted or moved', async () => {
+ const actual = path.join(root, 'actual', 'project');
+ const link = path.join(root, 'linked-project');
+ fs.mkdirSync(actual, { recursive: true });
+ fs.symlinkSync(actual, link, process.platform === 'win32' ? 'junction' : 'dir');
+ const { workspace, executor } = setup(link);
+ const native = path.join(link, 'build', 'out.js');
+ const forward = agentStyle(path.join(actual, 'build', 'out.js'));
+ const virtual = SHADOW + '/build/out.js';
+ try {
+ const original = '// a: ' + native + '\nconst out = "' + forward + '";\n';
+ expect(workspace.mapContentFromAgent('const out = "' + virtual + '";\n', original))
+ .toBe('const out = "' + forward + '";\n');
+ expect(workspace.mapContentFromAgent('new: ' + virtual + '\n' + workspace.mapTextForAgent(original), original))
+ .toBe('new: ' + agentStyle(link) + '/build/out.js\n' + original);
+ const prose = 'a: ' + native + '; b: ' + forward + '\n';
+ expect(workspace.mapContentFromAgent('b: ' + virtual + '\n', prose)).toBe('b: ' + forward + '\n');
+ const json = JSON.stringify({ a: native, b: forward });
+ expect(workspace.mapContentFromAgent(JSON.stringify({ b: virtual }), json)).toBe(JSON.stringify({ b: forward }));
+ const jsonProse = JSON.stringify({ text: 'before ' + native + ' tail' });
+ expect(workspace.mapContentFromAgent(workspace.mapTextForAgent(jsonProse).replace('before', 'after'), jsonProse))
+ .toBe(JSON.stringify({ text: 'after ' + native + ' tail' }));
+ const moved = 'const out = "' + virtual + '";\n// a: ' + virtual + '\n';
+ expect(workspace.mapContentFromAgent(moved, original)).toBe('const out = "' + forward + '";\n// a: ' + native + '\n');
+ } finally {
+ await executor.close();
+ }
+ });
+
+ it('edits a multiline fragment with repeated virtual paths using that fragment’s original spellings', async () => {
+ const actual = path.join(root, 'actual', 'project');
+ const link = path.join(root, 'linked-project');
+ fs.mkdirSync(actual, { recursive: true });
+ fs.symlinkSync(actual, link, process.platform === 'win32' ? 'junction' : 'dir');
+ const { executor } = setup(link);
+ const native = path.join(link, 'build', 'out.js');
+ const forward = agentStyle(path.join(actual, 'build', 'out.js'));
+ const virtual = SHADOW + '/build/out.js';
+ const file = path.join(actual, 'repeated.md');
+ fs.writeFileSync(file, 'a: ' + native + '\nb: ' + forward + '\nc: ' + native + '\n');
+ try {
+ await executor.callTool('Read', { file_path: SHADOW + '/repeated.md' });
+ const result = await executor.callTool('Edit', {
+ file_path: SHADOW + '/repeated.md', old_string: 'b: ' + virtual + '\nc: ' + virtual,
+ new_string: 'b: ' + virtual + '\nc: ' + virtual + ' (ok)',
+ });
+ expect(result.isError).toBeFalsy();
+ expect(fs.readFileSync(file, 'utf8')).toBe('a: ' + native + '\nb: ' + forward + '\nc: ' + native + ' (ok)\n');
+ } finally {
+ await executor.close();
+ }
+ });
+
+ it('restores notebook paths from the edited cell rather than an earlier cell', async () => {
+ const actual = path.join(root, 'actual', 'project');
+ const link = path.join(root, 'linked-project');
+ fs.mkdirSync(actual, { recursive: true });
+ fs.symlinkSync(actual, link, process.platform === 'win32' ? 'junction' : 'dir');
+ const { executor } = setup(link);
+ const native = path.join(link, 'build', 'out.js');
+ const forward = agentStyle(path.join(actual, 'build', 'out.js'));
+ const file = path.join(actual, 'paths.ipynb');
+ const a = 'a = "' + native + '"';
+ const b = 'b = "' + forward + '"';
+ fs.writeFileSync(file, JSON.stringify({ nbformat: 4, nbformat_minor: 5, cells: [
+ { id: 'a', cell_type: 'code', source: [a], metadata: {}, outputs: [] },
+ { id: 'b', cell_type: 'code', source: [b], metadata: {}, outputs: [] },
+ ] }));
+ try {
+ await executor.callTool('Read', { file_path: SHADOW + '/paths.ipynb' });
+ const result = await executor.callTool('NotebookEdit', {
+ notebook_path: SHADOW + '/paths.ipynb', cell_id: 'b', new_source: 'b = "' + SHADOW + '/build/out.js" # checked',
+ });
+ expect(result.isError).toBeFalsy();
+ expect(JSON.parse(fs.readFileSync(file, 'utf8')).cells.map((cell: { source: unknown }) => cell.source))
+ .toEqual([[a], b + ' # checked']);
+ } finally {
+ await executor.close();
+ }
+ });
+
+ it('keeps Markdown links in replies intact for folders that start with punctuation', () => {
+ const { workingDir, workspace } = setup();
+ const target = path.join(workingDir, '.github', 'workflows', 'ci.yml');
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, 'ci');
+ const projection = new RemoteEventProjection(workspace);
+ const reply = '改好了:[ci](' + SHADOW + '/.github/workflows/ci.yml),也可以看 [同一个](<' + SHADOW + '/.github/workflows/ci.yml>)';
+ const [event] = projection.project({ type: 'text', source: 'claude-code', data: { text: reply, isFinal: true } } as AgentEvent);
+ const links = markdownLinks((event.data as { text: string }).text);
+ expect(links).toHaveLength(2);
+ for (const url of links) expect(fs.readFileSync(url, 'utf8')).toBe('ci');
+ });
+
+ it.each(['allow', 'deny'] as const)('shows plan file links locally and returns %s feedback in Agent paths', async (behavior) => {
+ const { workingDir, workspace, executor } = setup();
+ const controller = createRemoteAgentHandle({
+ client: {} as RemoteAgentRunClient,
+ started: { id: 'sdk-1', agentKind: 'claude-code', model: 'm', shadowDir: SHADOW, virtualWorkspace: true, methods: [], state: {} },
+ workspace, mapEvent: mapClaudeHostedEvent, recordApproval: () => {}, newId: () => 'request-id', dispose: async () => {},
+ });
+ let shown: InteractionRequest | undefined;
+ const local = agentStyle(workingDir);
+ controller.handle.setInteractionResolver(async (request) => {
+ shown = request;
+ return { kind: 'plan_review', behavior,
+ ...(behavior === 'allow' ? { editedPlan: (request as { plan: string }).plan + '\n2. 再看 ' + local + '/docs/b.md' } : {}),
+ reason: '重新看 ' + local + '/docs/b.md',
+ };
+ });
+ try {
+ const reply = await controller.onRequest({ type: 'interaction', request: {
+ kind: 'plan_review', requestId: 'plan', plan: '1. 修改 [ci](' + SHADOW + '/.github/ci.yml)', planFilePath: SHADOW + '/plan.md',
+ } });
+ expect(shown).toMatchObject({ plan: '1. 修改 [ci](' + local + '/.github/ci.yml)', planFilePath: path.join(workingDir, 'plan.md') });
+ expect(markdownLinks((shown as { plan: string }).plan)).toEqual([local + '/.github/ci.yml']);
+ expect((reply as { result: InteractionDecision }).result).toMatchObject({
+ kind: 'plan_review', behavior, reason: '重新看 ' + SHADOW + '/docs/b.md',
+ ...(behavior === 'allow' ? { editedPlan: '1. 修改 [ci](' + SHADOW + '/.github/ci.yml)\n2. 再看 ' + SHADOW + '/docs/b.md' } : {}),
+ });
+ } finally {
+ controller.onClosed('closed');
+ await executor.close();
+ }
+ });
+});
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 b46e495185..ba8659757a 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
@@ -19,6 +19,9 @@ let root: string;
beforeEach(() => { root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-virtual-workspace-'))); });
afterEach(() => { fs.rmSync(root, { recursive: true, force: true }); });
+/** Agent 写进文件的路径还原到本机时沿用它的分隔符,源码字符串里不会冒出 `\f`、`\b` 这类转义。 */
+function written(local: string, virtual: string): string { return virtual.startsWith('C:') ? local : local.replace(/\\/g, '/'); }
+
function setup(virtual: string) {
const project = path.join(root, 'real project');
fs.mkdirSync(project);
@@ -198,12 +201,12 @@ describe('virtual workspace', () => {
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');
+ const real = Buffer.from(written(path.join(project, 'a.ts'), virtual) + ' ' + written(path.join(project, 'src', 'b.ts'), virtual) + ' 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"'));
+ .toEqual(Buffer.from('The docs say "' + written(path.join(project, 'README.md'), virtual) + ' links to /api/v1"'));
});
it.each([
@@ -228,7 +231,7 @@ describe('virtual workspace', () => {
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 localProse = written(path.join(project, 'README.md'), virtual) + ' 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',
@@ -289,7 +292,7 @@ describe('virtual workspace', () => {
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);
+ const expected = values(written(local, virtual), written(path.dirname(local), virtual), written(localFuture, virtual));
expect(fs.existsSync(localFuture)).toBe(false);
for (let index = 0; index < input.length; index += 1) {
const remoteBytes = Buffer.from(JSON.stringify(input[index]));
@@ -319,10 +322,10 @@ describe('virtual workspace', () => {
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' });
+ const sourceExpected = JSON.stringify({ script: written(path.join(project, 'run.js'), virtual) + ' --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 });
+ const pathExpected = JSON.stringify({ script: written(existing, virtual) });
expect(workspace.mapInputFromAgent(Buffer.from(pathValue))).toEqual(Buffer.from(pathExpected));
expect(workspace.mapOutputForAgent(Buffer.from(pathExpected))).toEqual(Buffer.from(pathValue));
});
@@ -644,7 +647,9 @@ describe('virtual workspace', () => {
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);
+ expect(JSON.parse(fs.readFileSync(path.join(fixtureDir, 'returned.json'), 'utf8'))).toEqual({
+ cwd: written(fixtureDir, virtual), script: written(script, virtual), argument: written(project, virtual),
+ });
} finally {
await executor.close();
}
diff --git a/apps/desktop/src/main/remote-agent/executor/executor.ts b/apps/desktop/src/main/remote-agent/executor/executor.ts
index 251c45aed5..6df014a3f7 100644
--- a/apps/desktop/src/main/remote-agent/executor/executor.ts
+++ b/apps/desktop/src/main/remote-agent/executor/executor.ts
@@ -25,6 +25,7 @@ import {
rawReaddir,
rawStat,
rawWriteFile,
+ readExistingText,
ReadStateTracker,
textResult,
type FileWriteHooks,
@@ -312,7 +313,7 @@ export class RemoteExecutor {
const target = this.resolvePath(str(body, 'path'));
await this.authorize({ kind: 'write', path: target }, signal);
if (typeof body.data !== 'string') throw new ExecutorRequestError('INVALID', 'data must be a base64 string');
- const data = this.workspace.mapInputFromAgent(Buffer.from(body.data, 'base64'));
+ const data = this.workspace.mapInputFromAgent(Buffer.from(body.data, 'base64'), await readExistingText(target));
await this.writeHooks.beforeWrite(target);
await rawWriteFile(target, data);
return {};
@@ -429,7 +430,8 @@ export class RemoteExecutor {
const content = args.content;
if (typeof content !== 'string') return textResult('content must be a string.', true);
await this.authorizeTool({ kind: 'write', path: target }, signal);
- return this.mapToolResult(await ccWrite(target, this.workspace.mapTextFromAgent(content), this.readState, this.writeHooks, this.workspace.toAgentPath(target)));
+ const local = this.workspace.mapContentFromAgent(content, await readExistingText(target));
+ return this.mapToolResult(await ccWrite(target, local, this.readState, this.writeHooks, this.workspace.toAgentPath(target)));
}
case 'Edit': {
const target = this.resolvePath(str(args, 'file_path'), this.shell.getCwd());
@@ -438,10 +440,11 @@ export class RemoteExecutor {
}
await this.authorizeTool({ kind: 'write', path: target }, signal);
return this.mapToolResult(await ccEdit(target, {
- old_string: this.workspace.mapTextFromAgent(args.old_string),
- new_string: this.workspace.mapTextFromAgent(args.new_string),
+ old_string: args.old_string,
+ new_string: 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),
+ (oldString, newString, original) => this.workspace.mapEditFromAgent(oldString, newString, original)));
}
case 'NotebookEdit': {
const target = this.resolvePath(str(args, 'notebook_path'), this.shell.getCwd());
@@ -452,10 +455,10 @@ export class RemoteExecutor {
await this.authorizeTool({ kind: 'write', path: target }, signal);
return this.mapToolResult(await ccNotebookEdit(target, {
cell_id: optionalString(args, 'cell_id'),
- new_source: this.workspace.mapTextFromAgent(args.new_source),
+ new_source: args.new_source,
cell_type: cellType,
edit_mode: editMode,
- }, this.readState, this.writeHooks));
+ }, this.readState, this.writeHooks, (source, original) => this.workspace.mapContentFromAgent(source, original)));
}
case 'WebFetch':
if (!this.opts.webFetch) return textResult(`Unknown tool: ${name}`, true);
diff --git a/apps/desktop/src/main/remote-agent/executor/files.ts b/apps/desktop/src/main/remote-agent/executor/files.ts
index 56fbeb87e1..98cc8e1e62 100644
--- a/apps/desktop/src/main/remote-agent/executor/files.ts
+++ b/apps/desktop/src/main/remote-agent/executor/files.ts
@@ -73,6 +73,36 @@ export async function rawReadFile(absPath: string): Promise<Buffer> {
return fsp.readFile(absPath);
}
+function textOrNull(data: Buffer): string | null {
+ const text = data.toString('utf8');
+ return data.includes(0) || !Buffer.from(text, 'utf8').equals(data) ? null : text;
+}
+
+/**
+ * 写入前的文件文本,用来沿用文件里路径的原写法(见 ExecutorWorkspace.mapContentFromAgent)。
+ * 不存在、不是普通文件、二进制或超过原始读取上限时为 null,写入照常进行。
+ */
+export async function readExistingText(absPath: string): Promise<string | null> {
+ try {
+ const stat = await fsp.stat(absPath);
+ if (!stat.isFile() || stat.size > EXECUTOR_RAW_READ_MAX_BYTES) return null;
+ return textOrNull(await fsp.readFile(absPath));
+ } catch {
+ return null;
+ }
+}
+
+/** readExistingText 的同步版本(exec-server 消息按序同步改写)。 */
+export function readExistingTextSync(absPath: string): string | null {
+ try {
+ const stat = fs.statSync(absPath);
+ if (!stat.isFile() || stat.size > EXECUTOR_RAW_READ_MAX_BYTES) return null;
+ return textOrNull(fs.readFileSync(absPath));
+ } catch {
+ return null;
+ }
+}
+
export async function rawAccess(absPath: string, mode: 'read' | 'write'): Promise<void> {
await fsp.access(absPath, mode === 'write' ? fs.constants.R_OK | fs.constants.W_OK : fs.constants.R_OK);
}
@@ -470,6 +500,14 @@ export interface CcEditInput {
replace_all?: boolean;
}
+/** 匹配 Agent 实际读到的文本;写入时再恢复本机文件的路径写法。 */
+export interface CcEditView {
+ oldString: string;
+ newString: string;
+ text?: string;
+ restore?: (updated: string) => string;
+}
+
function countOccurrences(haystack: string, needle: string): number {
let count = 0;
let index = haystack.indexOf(needle);
@@ -486,6 +524,7 @@ export async function ccEdit(
readState: ReadStateTracker,
hooks: FileWriteHooks,
displayPath = absPath,
+ mapEdit?: (oldString: string, newString: string, original: string | null) => CcEditView,
): Promise<ToolResult> {
const { old_string: oldString, new_string: newString } = input;
if (oldString === newString) {
@@ -497,25 +536,28 @@ export async function ccEdit(
if (oldString !== '') return textResult(`File does not exist: ${displayPath}`, true);
await hooks.beforeWrite(absPath);
await fsp.mkdir(path.dirname(absPath), { recursive: true });
- await fsp.writeFile(absPath, newString, 'utf8');
+ await fsp.writeFile(absPath, mapEdit?.(oldString, newString, null).newString ?? newString, 'utf8');
readState.record(absPath, (await fsp.stat(absPath)).mtimeMs);
return textResult(`File created successfully at: ${displayPath}`);
}
const problem = await readState.check(absPath);
if (problem) return textResult(problem, true);
const original = await fsp.readFile(absPath, 'utf8');
+ // 映射也只在先读后改检查通过后执行。匹配数以 Agent 的读视图为准,避免同一虚拟路径的多种原写法漏改。
+ const crlf = original.includes('\r\n');
+ const originalText = crlf ? original.replace(/\r\n/g, '\n') : original;
+ const edit = mapEdit?.(oldString, newString, originalText) ?? { oldString, newString };
if (oldString === '') {
if (original.trim() !== '') return textResult('Cannot create new file - file already exists.', true);
await hooks.beforeWrite(absPath);
- await fsp.writeFile(absPath, newString, 'utf8');
+ await fsp.writeFile(absPath, edit.restore?.(edit.newString) ?? edit.newString, 'utf8');
readState.record(absPath, (await fsp.stat(absPath)).mtimeMs);
return textResult(`The file ${displayPath} has been updated successfully.`);
}
// 文件用 CRLF 时按 LF 匹配,写回时恢复原换行风格。
- const crlf = original.includes('\r\n');
- const text = crlf ? original.replace(/\r\n/g, '\n') : original;
- const needle = crlf ? oldString.replace(/\r\n/g, '\n') : oldString;
- const replacement = crlf ? newString.replace(/\r\n/g, '\n') : newString;
+ const text = edit.text ?? originalText;
+ const needle = crlf ? edit.oldString.replace(/\r\n/g, '\n') : edit.oldString;
+ const replacement = crlf ? edit.newString.replace(/\r\n/g, '\n') : edit.newString;
const matches = countOccurrences(text, needle);
if (matches === 0) {
return textResult(`String to replace not found in file.\nString: ${oldString}`, true);
@@ -527,8 +569,9 @@ export async function ccEdit(
);
}
const updated = input.replace_all ? text.split(needle).join(replacement) : text.replace(needle, () => replacement);
+ const restored = edit.restore?.(updated) ?? updated;
await hooks.beforeWrite(absPath);
- await fsp.writeFile(absPath, crlf ? updated.replace(/\n/g, '\r\n') : updated, 'utf8');
+ await fsp.writeFile(absPath, crlf ? restored.replace(/\n/g, '\r\n') : restored, 'utf8');
readState.record(absPath, (await fsp.stat(absPath)).mtimeMs);
return textResult(`The file ${displayPath} has been updated successfully.`);
}
@@ -565,6 +608,7 @@ export async function ccNotebookEdit(
input: CcNotebookEditInput,
readState: ReadStateTracker,
hooks: FileWriteHooks,
+ mapSource: (source: string, original?: string) => string = (source) => source,
): Promise<ToolResult> {
if (path.extname(absPath).toLowerCase() !== '.ipynb') {
return textResult('File must be a Jupyter notebook (.ipynb file). For editing other file types, use the Edit tool.', true);
@@ -599,9 +643,10 @@ export async function ccNotebookEdit(
cells.splice(index, 1);
} else if (mode === 'insert') {
const cellType = input.cell_type ?? 'code';
+ const source = mapSource(input.new_source);
const cell: NotebookCell = cellType === 'markdown'
- ? { cell_type: 'markdown', metadata: {}, source: input.new_source }
- : { cell_type: 'code', metadata: {}, source: input.new_source, outputs: [], execution_count: null };
+ ? { cell_type: 'markdown', metadata: {}, source }
+ : { cell_type: 'code', metadata: {}, source, outputs: [], execution_count: null };
if (supportsIds) {
cell.id = newCellId();
resultId = cell.id;
@@ -609,7 +654,8 @@ export async function ccNotebookEdit(
cells.splice(index + 1, 0, cell);
} else {
const cell = cells[index];
- cell.source = input.new_source;
+ const original = Array.isArray(cell.source) ? cell.source.join('') : cell.source;
+ cell.source = mapSource(input.new_source, original);
if (input.cell_type && input.cell_type !== cell.cell_type) {
cell.cell_type = input.cell_type;
if (input.cell_type === 'markdown') {
diff --git a/apps/desktop/src/main/remote-agent/executor/workspace.ts b/apps/desktop/src/main/remote-agent/executor/workspace.ts
index 13005c56a3..592ea2ab79 100644
--- a/apps/desktop/src/main/remote-agent/executor/workspace.ts
+++ b/apps/desktop/src/main/remote-agent/executor/workspace.ts
@@ -11,6 +11,7 @@ import os from 'node:os';
import path from 'node:path';
import { isSensitiveCredentialPath } from '@cindy/maker-core';
+import { diffLines, diffWordsWithSpace } from 'diff';
export interface ExecutorPathAlias {
/** Agent 所在电脑上的影子目录(绝对路径,按该电脑的路径写法)。 */
@@ -35,13 +36,13 @@ export class ExecutorPathError extends Error {
}
}
-/** 取一个路径的真实路径;不存在时按最近的已存在祖先解析,再拼回剩余部分。 */
-export function realPathOrAncestor(target: string): string {
+/** 按指定 realpath 实现取真实路径;不存在时按最近的已存在祖先解析,再拼回剩余部分。 */
+function realPathOrAncestorWith(target: string, resolveRealpath: (path: string) => string): string {
let current = path.resolve(target);
const rest: string[] = [];
for (;;) {
try {
- const real = fs.realpathSync.native(current);
+ const real = resolveRealpath(current);
return rest.length ? path.join(real, ...rest.reverse()) : real;
} catch {
const parent = path.dirname(current);
@@ -52,6 +53,16 @@ export function realPathOrAncestor(target: string): string {
}
}
+/** 取一个路径的真实路径;不存在时按最近的已存在祖先解析,再拼回剩余部分。 */
+export function realPathOrAncestor(target: string): string {
+ return realPathOrAncestorWith(target, fs.realpathSync.native);
+}
+
+/** Windows 的 native realpath 可能返回长路径,而 Node 的普通实现保留短路径写法;两者都要覆盖。 */
+function realPathOrAncestorPortable(target: string): string {
+ return realPathOrAncestorWith(target, fs.realpathSync);
+}
+
function isInside(child: string, parent: string): boolean {
const relative = path.relative(parent, child);
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
@@ -70,13 +81,110 @@ 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');
+const WINDOWS_PATH = /^[A-Za-z]:|^[\\/]{2}/;
+
+/** 正文与脚本里的路径边界(含通配符/变量后缀);若磁盘上存在同名延续,仍由 continuesName 保留字面目录名。 */
+const NAME_END = /[\s"'\x60<>()[\]{}|&;:,*?$%,。、;:!?()【】《》「」『』“”‘’]/;
+
+/**
+ * 目录前缀后面那个字符是否让这一段结束。串尾和分隔符一定结束;空白、引号、括号和句末标点
+ * (`路径。`、`path.`)只在正文里算结束,仍可能是同级目录名的一部分(`xxx copy`),由调用方按
+ * 磁盘核对。其余字符(`xxx.git`、`xxx-v1`)接着的是另一个名字:只按完整目录段匹配,与
+ * mapAlias 的判断一致,否则文本和文件操作会把同一个路径换到两个地方。
+ */
+function segmentEnd(text: string, index: number): 'separator' | 'punctuation' | null {
+ const char = text[index];
+ if (char === undefined || char === '/' || char === '\\') return 'separator';
+ if (NAME_END.test(char)) return 'punctuation';
+ if (!/[.!?]/.test(char)) return null;
+ let next = index;
+ while (/[.!?]/.test(text[next] ?? '')) next += 1;
+ return next >= text.length || NAME_END.test(text[next]) ? 'punctuation' : null;
+}
+
+interface AliasPrefixes<T extends ExecutorPathAlias> {
+ finder: RegExp;
+ prefixes: Array<{ alias: T; pattern: RegExp }>;
+}
+
+/** 别名需已按 from 由长到短排好;Windows 路径不区分大小写,其余按原样比较。 */
+function aliasPrefixes<T extends ExecutorPathAlias>(aliases: readonly T[]): AliasPrefixes<T> {
+ const prefixes = aliases.map((alias) => ({
+ alias,
+ pattern: new RegExp(alias.from.replace(/[\\/]+$/, '').split(/[\\/]/)
+ .map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('[/\\\\]'), WINDOWS_PATH.test(alias.from) ? 'iy' : 'y'),
+ }));
+ return { finder: new RegExp(prefixes.map((item) => item.pattern.source).join('|'), 'gi'), prefixes };
+}
+
+/** 从 start 起找下一个完整的目录前缀;同一位置先试最长的别名,不成立再试它的上级。 */
+function nextAliasPrefix<T extends ExecutorPathAlias>(
+ text: string, start: number, { finder, prefixes }: AliasPrefixes<T>,
+ continuesName?: (alias: T, rest: string) => boolean,
+ boundary: (text: string, index: number, start: number) => 'separator' | 'punctuation' | null = segmentEnd,
+): { index: number; end: number; alias: T } | null {
+ for (let from = start; from < text.length;) {
+ finder.lastIndex = from;
+ const found = finder.exec(text);
+ if (!found) return null;
+ const index = found.index;
+ if (index === 0 || !/[A-Za-z0-9_]/.test(text[index - 1])) {
+ for (const { alias, pattern } of prefixes) {
+ pattern.lastIndex = index;
+ const hit = pattern.exec(text);
+ if (!hit) continue;
+ const end = index + hit[0].length;
+ const kind = boundary(text, end, index);
+ if (!kind || (kind === 'punctuation' && continuesName?.(alias, text.slice(end, end + 1024)))) continue;
+ return { index, end, alias };
+ }
+ }
+ from = index + 1;
+ }
+ return null;
+}
+
+/** 正文里的路径后缀;在变量和通配符前停下,父目录别名回退也能还原未改路径的原拼写。 */
+const PATH_SUFFIX = /[/\\][^\s\x60'";:|&)<>}\]*?$%]*/y;
+
+/**
+ * target:分隔符按目标端统一(Agent 看到的路径、结构化路径字段)。
+ * source:本机 Windows 路径沿用 Agent 原文的分隔符。写回文件和正文时用它:Agent 写的
+ * `/` 换成 `\` 会让源码字符串里的 `\f`、`\b` 变成转义字符,Markdown 里的 `\.git` 也会被吃掉。
+ */
+export type SeparatorStyle = 'target' | 'source';
+
+function joinMapped(to: string, matched: string, suffix: string, style: SeparatorStyle): string {
+ const base = to.replace(/[\\/]+$/, '');
+ if (style === 'source' && WINDOWS_PATH.test(base)) {
+ const separator = /[\\/]/.exec(matched)?.[0] ?? '\\';
+ return base.replace(/[\\/]/g, separator) + suffix.replace(/[\\/]/g, separator);
+ }
+ const separator = to.includes('\\') ? '\\' : '/';
+ return base + suffix.replace(/[\\/]/g, separator);
+}
+
+/** 记录 / 还原路径的原写法:text 为正文 token,decoded 为 JSON 字符串里的值,json 为 JSON 字符串字面量。 */
+export type SpellingLevel = 'text' | 'decoded' | 'json';
+
+export interface PathSpellingHooks {
+ record?(level: SpellingLevel, output: string, input: string): void;
+ restore?(level: SpellingLevel, input: string): string | undefined;
+}
+
+export interface ProjectPathTextOptions {
+ /** 正文 token 的分隔符写法,默认 target。 */
+ separators?: SeparatorStyle;
+ /** 整值路径(路径字段、已存在的完整路径)的分隔符写法,默认 target。 */
+ wholeSeparators?: SeparatorStyle;
+ /** false 时不按 JSON 解析,只逐行逐 token 投影(与 Read 工具带行号的输出一致)。 */
+ json?: boolean;
+ /** 目录名后接空白或标点时,核对它是否其实是同级目录名的一部分。 */
+ continuesName?: (alias: ExecutorPathAlias, rest: string) => boolean;
+ spellings?: PathSpellingHooks;
+ /** 原始正文中的位置,不包含 JSON 解码后的临时字符串。 */
+ restoreOriginal?(offset: number, input: string): string | undefined;
+ recordReplacement?(offset: number, input: string, output: string): void;
}
export function isPathTextField(key: string): boolean {
@@ -93,6 +201,7 @@ export function pathTextContext(key: string): PathTextContext {
export function mapJsonPathText(
text: string, project: (value: string, context: PathTextContext) => string, rootContext: PathTextContext = 'untyped',
+ literals?: { record?(output: string, input: string): void; restore?(input: string, offset: number): string | undefined; replaced?(offset: number, input: string, output: string): void },
): string {
JSON.parse(text);
// 顶层字符串/数组也能承载正文,容器本身不提供完整路径的证据。
@@ -122,53 +231,252 @@ export function mapJsonPathText(
if (frame?.type === 'object') frame.key = decoded;
return token;
}
+ const restored = literals?.restore?.(token, offset);
+ if (restored !== undefined) {
+ if (restored !== token) literals?.replaced?.(offset, token, restored);
+ return restored;
+ }
const projected = project(decoded, valueContext());
- return projected === decoded ? token : JSON.stringify(projected);
+ const output = projected === decoded ? token : JSON.stringify(projected);
+ if (output !== token) literals?.record?.(output, token);
+ if (output !== token) literals?.replaced?.(offset, token, output);
+ return output;
});
}
/** 对已知目录做单次双向投影,最长前缀先匹配,防止替换结果再次被短祖先别名改写。 */
export function projectPathText(
text: string, aliases: readonly ExecutorPathAlias[], context: PathTextContext = 'text',
- isCompletePath?: (mapped: string) => boolean,
+ isCompletePath?: (mapped: string) => boolean, options: ProjectPathTextOptions = {},
): 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 textPattern = pathTextPattern(entries, false);
- const project = (value: string, valueContext: PathTextContext = 'text'): string => {
+ const prefixes = aliasPrefixes(entries);
+ const { spellings } = options;
+ // 同一个路径在 JSON 字符串里和正文里的转义不同,原写法按所处层级分别记录与还原。
+ let depth = 0;
+ const replace = (input: string, mapped: () => string, offset: number | null): string => {
+ const level: SpellingLevel = depth ? 'decoded' : 'text';
+ const restored = (offset === null ? undefined : options.restoreOriginal?.(offset, input)) ?? spellings?.restore?.(level, input);
+ const output = restored ?? mapped();
+ if (output !== input) {
+ if (restored === undefined) spellings?.record?.(level, output, input);
+ if (offset !== null) options.recordReplacement?.(offset, input, output);
+ }
+ return output;
+ };
+ const project = (value: string, valueContext: PathTextContext = 'text', offset: number | null = 0): string => {
// MCP 的 text 常嵌一层 JSON;Skill/命令输出和文本文件也可能是 JSON。
// 先解码字符串再投影,才能识别 Windows 转义路径;只改变化的字符串 token,保留格式与其它字节。
- if (/^\s*[{["]/.test(value)) {
- try { return mapJsonPathText(value, project, valueContext === 'text' ? 'untyped' : valueContext); } catch { /* 普通文本继续按路径边界投影。 */ }
+ if (options.json !== false && /^\s*[{["]/.test(value)) {
+ depth += 1;
+ try {
+ return mapJsonPathText(value, (decoded, context) => project(decoded, context, null), valueContext === 'text' ? 'untyped' : valueContext, {
+ record: (output, input) => spellings?.record?.('json', output, input),
+ restore: (input, index) => (offset === null ? undefined : options.restoreOriginal?.(offset + index, input)) ?? spellings?.restore?.('json', input),
+ replaced: (index, input, output) => { if (offset !== null) options.recordReplacement?.(offset + index, input, output); },
+ });
+ } catch { /* 普通文本继续按路径边界投影。 */ } finally {
+ depth -= 1;
+ }
}
// 脚本可能先打印日志再逐行输出 JSON;保留换行格式,逐行应用同一套转义处理。
- if (value.includes('\n')) return value.split('\n').map((line) => project(line, valueContext)).join('\n');
+ if (value.includes('\n')) {
+ let lineStart = 0;
+ return value.split('\n').map((line) => {
+ const output = project(line, valueContext, offset === null ? null : offset + lineStart);
+ lineStart += line.length + 1;
+ return output;
+ }).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);
+ const mapped = joinMapped(alias.to, pathValue, suffix, options.wholeSeparators ?? 'target');
// 明确的路径字段可整体映射;歧义字段(如 script)只有现存完整路径才整体映射,
// 否则按正文逐 token 投影,避免把脚本源码里的 /api/v1 等内容当成路径。
- if (valueContext === 'path' || isCompletePath?.(mapped)) return mapped + lineEnd;
+ if (valueContext === 'path' || isCompletePath?.(mapped)) return replace(pathValue, () => mapped, offset) + 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);
- });
+ let result = '';
+ let position = 0;
+ for (let hit = nextAliasPrefix(value, 0, prefixes, options.continuesName); hit;
+ hit = nextAliasPrefix(value, position, prefixes, options.continuesName)) {
+ PATH_SUFFIX.lastIndex = hit.end;
+ const suffix = PATH_SUFFIX.exec(value)?.[0] ?? '';
+ const input = value.slice(hit.index, hit.end + suffix.length);
+ const { to } = hit.alias;
+ result += value.slice(position, hit.index) + replace(input, () => joinMapped(to, input, suffix, options.separators ?? 'target'), offset === null ? null : offset + hit.index);
+ position = hit.end + suffix.length;
+ }
+ return result + value.slice(position);
};
return project(text, context);
}
+const escapeJson = (value: string): string => JSON.stringify(value).slice(1, -1);
+
+interface UnchangedRange { before: number; after: number; length: number }
+interface OriginalSpelling { input: string; output: string }
+interface OriginalProjection { text: string; spellings: Map<number, OriginalSpelling> }
+
+/** 按上下文对齐未改内容,不能按同一个虚拟路径在新文件里的出现序号认领原写法。 */
+function unchangedRanges(before: string, after: string): UnchangedRange[] {
+ const ranges: UnchangedRange[] = [];
+ const deadline = Date.now() + 75;
+ const changes = diffLines(before, after, { timeout: 50, maxEditLength: 4096 });
+ let oldOffset = 0;
+ let newOffset = 0;
+ let removed = '';
+ let added = '';
+ const refine = () => {
+ // 行内小修改也保留未改的完整路径;限制同步 diff 的工作量,整文件重写不占满 main。
+ const remaining = deadline - Date.now();
+ const parts = remaining > 0 && removed.length + added.length <= 64 * 1024
+ ? diffWordsWithSpace(removed, added, { timeout: Math.min(25, remaining), maxEditLength: 4096 }) : undefined;
+ let oldPart = oldOffset - removed.length;
+ let newPart = newOffset - added.length;
+ for (const part of parts ?? []) {
+ if (!part.added && !part.removed) ranges.push({ before: oldPart, after: newPart, length: part.value.length });
+ if (!part.added) oldPart += part.value.length;
+ if (!part.removed) newPart += part.value.length;
+ }
+ removed = '';
+ added = '';
+ };
+ for (const change of changes ?? []) {
+ if (change.removed) { removed += change.value; oldOffset += change.value.length; }
+ else if (change.added) { added += change.value; newOffset += change.value.length; }
+ else {
+ refine();
+ ranges.push({ before: oldOffset, after: newOffset, length: change.value.length });
+ oldOffset += change.value.length;
+ newOffset += change.value.length;
+ }
+ }
+ refine();
+ // 完整且唯一的一行即便被移动,也仍能确定它对应哪段原文;同时作为 diff 超时的低成本回退。
+ const uniqueLines = new Map<string, number | null>();
+ let offset = 0;
+ for (const line of before.split('\n')) {
+ uniqueLines.set(line, uniqueLines.has(line) ? null : offset);
+ offset += line.length + 1;
+ }
+ offset = 0;
+ for (const line of after.split('\n')) {
+ const old = uniqueLines.get(line);
+ if (old !== undefined && old !== null && line) ranges.push({ before: old, after: offset, length: line.length });
+ offset += line.length + 1;
+ }
+ return ranges;
+}
+
+function alignedSpellings(projection: OriginalProjection, ranges: readonly UnchangedRange[]): Map<number, OriginalSpelling> {
+ const result = new Map<number, OriginalSpelling>();
+ const entries = [...projection.spellings].sort((a, b) => a[0] - b[0]);
+ for (const range of ranges) {
+ let low = 0;
+ let high = entries.length;
+ while (low < high) {
+ const middle = (low + high) >>> 1;
+ if (entries[middle][0] < range.before) low = middle + 1;
+ else high = middle;
+ }
+ for (let index = low; index < entries.length && entries[index][0] < range.before + range.length; index += 1) {
+ const [offset, spelling] = entries[index];
+ if (offset + spelling.input.length <= range.before + range.length) {
+ result.set(range.after + offset - range.before, spelling);
+ }
+ }
+ }
+ return result;
+}
+
+/**
+ * 写回文件时沿用原文件里路径的写法。Agent 读到的是投影后的虚拟路径,而原文件里同一个目录
+ * 可能写成 `E:/x`、`E:\x`、`/e/x`、`/tmp` 或不同大小写;按 Agent 看到的写法查回原写法,
+ * 没改动的部分写回后逐字节不变。同一个虚拟写法对应多种原写法时按出现顺序对应。
+ */
+export class PathSpellings {
+ readonly projectedTexts: string[] = [];
+ private readonly spellings = new Map<string, string[]>();
+ private readonly used = new Map<string, number>();
+ private readonly ambiguous = new Map<string, string[]>();
+ private forced = new Map<string, string>();
+
+ /** raw:Agent 写的是文件原文(Write / Edit);decoded:写的是 JSON 里解码后的内容(Notebook 单元格)。 */
+ constructor(private readonly view: 'raw' | 'decoded' = 'raw') {}
+
+ /** 正向投影原文件时记录。A 为不解析 JSON 的逐行投影(Read 工具所见),B 为默认投影(fs.read 所见)。 */
+ recorder(pass: 'A' | 'B'): PathSpellingHooks {
+ return {
+ record: (level, output, input) => {
+ this.add(pass + ':' + level, output, input);
+ // JSON 字符串里的值出现在 JSON 源码片段(如 Edit 的 old_string)里时带着转义。
+ if (pass === 'B' && level === 'decoded') this.add('B:escaped', escapeJson(output), escapeJson(input));
+ },
+ };
+ }
+
+ restorer(pass?: 'A' | 'B' | 'unique'): PathSpellingHooks {
+ return { restore: (level, input) => this.restore(level, input, pass) };
+ }
+
+ /** 查过的、原文件里有多种原写法的虚拟写法。 */
+ alternatives(): Array<[string, string[]]> {
+ return [...this.ambiguous];
+ }
+
+ /** 指定某些虚拟写法用哪种原写法(Edit 在原文件里定位 old_string 时用),并从头计数。 */
+ force(choices: ReadonlyMap<string, string>): void {
+ this.forced = new Map(choices);
+ this.used.clear();
+ }
+
+ private add(namespace: string, output: string, input: string): void {
+ const key = namespace + '\0' + output;
+ const list = this.spellings.get(key);
+ if (list) list.push(input);
+ else this.spellings.set(key, [input]);
+ }
+
+ private order(level: SpellingLevel, pass?: 'A' | 'B' | 'unique'): string[] {
+ // 还原 Read 的逐行视图时,不能借用整体 JSON 视图的队列:其中有些转义路径在 Read 里没有投影。
+ if (pass === 'A') return level === 'json' ? [] : ['A:text'];
+ if (level === 'json') return ['B:json'];
+ if (level === 'decoded' || this.view === 'decoded') return ['B:decoded', 'A:text', 'B:text'];
+ return ['A:text', 'B:text', 'B:escaped', 'B:decoded'];
+ }
+
+ private restore(level: SpellingLevel, input: string, pass?: 'A' | 'B' | 'unique'): string | undefined {
+ const key = level + '\0' + input;
+ const forced = this.forced.get(key);
+ if (forced !== undefined) return forced;
+ let picked: string | undefined;
+ const choices: string[] = [];
+ for (const namespace of this.order(level, pass)) {
+ const counter = namespace + '\0' + input;
+ const list = this.spellings.get(counter);
+ if (!list) continue;
+ if (picked === undefined) {
+ const count = this.used.get(counter) ?? 0;
+ this.used.set(counter, count + 1);
+ picked = list[Math.min(count, list.length - 1)];
+ }
+ for (const item of list) if (!choices.includes(item)) choices.push(item);
+ }
+ if (choices.length > 1) this.ambiguous.set(key, choices);
+ if (pass === 'unique' && choices.length !== 1) return undefined;
+ return picked;
+ }
+}
+
export class ExecutorWorkspace {
readonly workingDir: string;
private roots: string[];
@@ -192,8 +500,10 @@ export class ExecutorWorkspace {
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 canonicalPaths = [realPathOrAncestor(alias.to), realPathOrAncestorPortable(alias.to)];
+ for (const canonical of canonicalPaths) {
+ if (path.resolve(canonical) !== path.resolve(alias.to)) expanded.push({ from: alias.from, to: canonical });
+ }
}
const seen = new Set<string>();
this.aliases = expanded
@@ -277,29 +587,193 @@ export class ExecutorWorkspace {
/** 工具输出、诊断和可逆的 UTF-8 文本内容使用虚拟路径;二进制字节保持原样。 */
mapTextForAgent(text: string, context: PathTextContext = 'text'): string {
+ return this.projectForAgent(text, context);
+ }
+
+ private projectForAgent(text: string, context: PathTextContext, options: ProjectPathTextOptions = {}): string {
if (!this.virtualRoot) return text;
- const aliases = this.aliases.flatMap((alias) => {
- const real = alias.to.replace(/\\/g, '/');
- const entries = [{ from: real, to: alias.from }];
- // Git Bash / MSYS 的 pwd 和诊断使用 /c/...,而 Node 返回 C:\...。
- if (/^[A-Za-z]:\//.test(real)) entries.push({ from: '/' + real[0].toLowerCase() + real.slice(2), to: alias.from });
- if (process.platform === 'win32') {
- const temporary = os.tmpdir().replace(/\\/g, '/').replace(/\/+$/, '');
- const relative = stripAliasPrefix(real, temporary);
- if (relative !== null) entries.push({ from: '/tmp' + (relative ? '/' + relative : ''), to: alias.from });
- }
- return entries;
+ return projectPathText(text, this.agentAliases(), context, (mapped) => fs.existsSync(this.mapAlias(mapped)),
+ { ...options, continuesName: this.continuesName });
+ }
+
+ /** 本机真实路径(含 Git Bash 写法)→ Agent 看到的虚拟路径。 */
+ private agentAliases(): ExecutorPathAlias[] {
+ const seen = new Set<string>();
+ return this.aliases.flatMap((alias) => {
+ // A junction/symlink can be resolved differently by the Windows runner and by
+ // the process that created the alias. Include the current canonical target at
+ // projection time so both spellings still map to the same virtual directory.
+ const targets = [alias.to, realPathOrAncestor(alias.to)];
+ return targets.flatMap((target) => {
+ const real = target.replace(/\\/g, '/');
+ const entries: ExecutorPathAlias[] = [{ from: real, to: alias.from }];
+ // Git Bash / MSYS 的 pwd 和诊断使用 /c/...,而 Node 返回 C:\...。
+ if (/^[A-Za-z]:\//.test(real)) entries.push({ from: '/' + real[0].toLowerCase() + real.slice(2), to: alias.from });
+ if (process.platform === 'win32') {
+ const temporary = os.tmpdir().replace(/\\/g, '/').replace(/\/+$/, '');
+ const relative = stripAliasPrefix(real, temporary);
+ if (relative !== null) entries.push({ from: '/tmp' + (relative ? '/' + relative : ''), to: alias.from });
+ }
+ return entries.filter((entry) => {
+ const normalizedFrom = entry.from.replace(/\\/g, '/');
+ const keyFrom = process.platform === 'win32' ? normalizedFrom.toLowerCase() : normalizedFrom;
+ const key = keyFrom + '\\0' + entry.to;
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ });
+ });
});
- return projectPathText(text, aliases, context, (mapped) => fs.existsSync(this.mapAlias(mapped)));
}
- /** 把 Agent 虚拟路径还原成本机路径,用于文本文件写回。 */
+ /**
+ * 正文里目录名后接空白或标点时,按磁盘核对后面是否其实是同级目录名(`xxx copy`、`xxx (1)`):
+ * 是就交给上级目录别名按完整目录段投影,Agent 用这个路径读写时才会落回同一个目录。
+ */
+ private readonly continuesName = (alias: ExecutorPathAlias, rest: string): boolean => {
+ const real = alias.from.replace(/\\/g, '/').replace(/\/+$/, '');
+ const cut = real.lastIndexOf('/');
+ if (cut <= 0) return false;
+ const name = real.slice(cut + 1);
+ let parent = real.slice(0, cut);
+ if (/^[A-Za-z]:$/.test(parent)) parent += '/';
+ // Git Bash 写法 /c/x 对应 C:/x。
+ else if (process.platform === 'win32' && /^\/[A-Za-z](?:\/|$)/.test(parent)) parent = parent[1] + ':/' + parent.slice(3);
+ // 命令刚建的目录也要认得,不缓存目录列表;只核对到下一个分隔符为止的几处可能的名字结尾。
+ let checked = 0;
+ for (let length = 1; length <= Math.min(rest.length, 255) && checked < 8; length += 1) {
+ if (/[\\/\r\n]/.test(rest[length - 1])) break;
+ if (!segmentEnd(rest, length)) continue;
+ checked += 1;
+ if (fs.existsSync(parent.replace(/\/+$/, '') + '/' + name + rest.slice(0, length))) return true;
+ }
+ return false;
+ };
+
+ private agentPathsToLocal(): ExecutorPathAlias[] {
+ return this.aliases.map((alias) => ({ from: alias.from.replace(/\\/g, '/'), to: alias.to }));
+ }
+
+ /**
+ * 把 Agent 虚拟路径还原成本机路径,用于展示的正文、工具参数等。正文 token 沿用 Agent 的分隔符,
+ * 结构化路径字段与已存在的完整路径用本机写法。
+ */
+ private readonly localContinuesName = (alias: ExecutorPathAlias, rest: string): boolean => {
+ const virtual = alias.from.replace(/[\\/]+$/, '').replace(/\\/g, '/');
+ const cut = virtual.lastIndexOf('/');
+ if (cut <= 0) return false;
+ // basename 属于虚拟目录名,父目录则在本机侧检查,确保与 mapAlias 落在同一处。
+ return this.continuesName({ ...alias, from: path.join(this.mapAlias(virtual.slice(0, cut)), virtual.slice(cut + 1)) }, rest);
+ };
+
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));
+ return projectPathText(text, this.agentPathsToLocal(), context, (mapped) => fs.existsSync(mapped), { separators: 'source', continuesName: this.localContinuesName });
+ }
+
+ /** 正文里的单个完整路径(代码段、尖括号链接):还原成本机路径,分隔符沿用 Agent 的写法。 */
+ mapAliasInText(input: string): string {
+ const local = this.mapAlias(input);
+ if (local === input || !WINDOWS_PATH.test(local)) return local;
+ const separator = /[\\/]/.exec(input)?.[0] ?? '\\';
+ return local.replace(/[\\/]/g, separator);
+ }
+
+ /**
+ * Agent 写回的文件内容。original 为写入前的文件内容:Agent 读到的是投影后的路径,按它还原原文件里
+ * 的写法,没改动的部分逐字节不变;新出现的路径沿用 Agent 的分隔符。
+ */
+ mapContentFromAgent(text: string, original?: string | null, view: 'raw' | 'decoded' = 'raw'): string {
+ if (!this.virtualRoot) return text;
+ if (!original || view === 'decoded') return this.contentFromAgent(text, original ? this.contentSpellings(original, view) : undefined);
+ const projections = this.originalProjections(original);
+ if (projections.some((projection) => projection.text === text)) return original;
+ if (projections.every((projection) => projection.text === original)) return this.contentFromAgent(text);
+ let matched = new Map<number, OriginalSpelling>();
+ let bestLength = -1;
+ for (const projection of projections) {
+ const candidate = alignedSpellings(projection, unchangedRanges(projection.text, text));
+ const length = [...candidate.values()].reduce((sum, item) => sum + item.input.length, 0);
+ if (length > bestLength) { matched = candidate; bestLength = length; }
+ }
+ // 字符串内的正文改变而路径不变时,只有一种原写法的路径仍可直接还原;有歧义的只按上下文恢复。
+ return this.contentFromAgent(text, this.contentSpellings(original, view), { restoreOriginal: (offset, input) => {
+ const spelling = matched.get(offset);
+ return spelling?.input === input ? spelling.output : undefined;
+ } }, 'unique');
+ }
+
+ /**
+ * Edit 在 Agent 读到的投影视图里匹配,保证同一虚拟路径的多种原写法都参与唯一性和批量替换检查。
+ * 写回时恢复未改内容;没有投影视图能匹配的旧请求继续按本机原文匹配。
+ */
+ mapEditFromAgent(oldString: string, newString: string, original: string | null): {
+ oldString: string; newString: string; text?: string; restore?: (updated: string) => string;
+ } {
+ if (!this.virtualRoot) return { oldString, newString };
+ if (!original) return { oldString: this.contentFromAgent(oldString), newString: this.contentFromAgent(newString) };
+ const normalizedOld = oldString.replace(/\r\n/g, '\n');
+ let selected: OriginalProjection | undefined;
+ let mostMatches = 0;
+ for (const projection of this.originalProjections(original.replace(/\r\n/g, '\n'))) {
+ if (!normalizedOld) break;
+ let count = 0;
+ for (let offset = projection.text.indexOf(normalizedOld); offset >= 0; offset = projection.text.indexOf(normalizedOld, offset + normalizedOld.length)) count++;
+ if (count > mostMatches) { selected = projection; mostMatches = count; }
+ }
+ // Read 的逐行文本与 Bash/fs.read 的 JSON 视图可能不同;来源未知时保守保留更多匹配,要求补充上下文。
+ if (selected) return { oldString, newString, text: selected.text, restore: (updated) => this.mapContentFromAgent(updated, original) };
+ const spellings = this.contentSpellings(original, 'raw');
+ const haystack = original.replace(/\r\n/g, '\n');
+ const found = (value: string) => haystack.includes(value.replace(/\r\n/g, '\n'));
+ let mappedOld = this.contentFromAgent(oldString, spellings);
+ let chosen = new Map<string, string>();
+ if (!found(mappedOld)) {
+ const alternatives = spellings.alternatives().slice(0, 4);
+ let combinations: Array<Map<string, string>> = [new Map()];
+ for (const [key, values] of alternatives) {
+ combinations = combinations.flatMap((choice) => values.map((value) => new Map(choice).set(key, value))).slice(0, 64);
+ }
+ for (const choice of combinations) {
+ spellings.force(choice);
+ const candidate = this.contentFromAgent(oldString, spellings);
+ if (found(candidate)) {
+ mappedOld = candidate;
+ chosen = choice;
+ break;
+ }
+ }
+ }
+ spellings.force(chosen);
+ return { oldString: mappedOld, newString: this.contentFromAgent(newString, spellings) };
+ }
+
+ private contentFromAgent(text: string, spellings?: PathSpellings, options: ProjectPathTextOptions = {}, pass?: 'A' | 'B' | 'unique'): string {
+ return projectPathText(text, this.agentPathsToLocal(), 'text', (mapped) => fs.existsSync(mapped), {
+ ...options, separators: 'source', wholeSeparators: 'source', spellings: spellings?.restorer(pass), continuesName: this.localContinuesName,
+ });
+ }
+
+ /** 按 Agent 读这个文件时看到的两种投影(Read 工具逐行、fs.read 整体)记下路径的原写法。 */
+ private contentSpellings(original: string, view: 'raw' | 'decoded'): PathSpellings {
+ const spellings = new PathSpellings(view);
+ spellings.projectedTexts.push(this.projectForAgent(original, 'text', { json: false, spellings: spellings.recorder('A') }));
+ const json = this.projectForAgent(original, 'text', { spellings: spellings.recorder('B') });
+ if (!spellings.projectedTexts.includes(json)) spellings.projectedTexts.push(json);
+ return spellings;
+ }
+
+ /** 在完整旧投影上恢复一次,记录每个路径/JSON字面量的精确位置与原写法。 */
+ private originalProjections(original: string): OriginalProjection[] {
+ const spellings = this.contentSpellings(original, 'raw');
+ return spellings.projectedTexts.map((text, index) => {
+ spellings.force(new Map());
+ const entries = new Map<number, OriginalSpelling>();
+ const restored = this.contentFromAgent(text, spellings, { recordReplacement: (offset, input, output) => { entries.set(offset, { input, output }); } }, index === 0 ? 'A' : 'B');
+ // 逆投影必须确实得到整份原文,才能把其中的位置信息用于局部恢复。
+ if (restored !== original) entries.clear();
+ return { text, spellings: entries };
+ });
}
/** 展示层延迟尚未传完整的虚拟路径;别名仍由当前执行器维护。 */
@@ -315,10 +789,11 @@ export class ExecutorWorkspace {
return projected === text ? data : Buffer.from(projected, 'utf8');
}
- mapInputFromAgent(data: Buffer): Buffer {
+ /** Agent 写入的文件字节;original 为写入前的文本内容(见 mapContentFromAgent)。 */
+ mapInputFromAgent(data: Buffer, original?: string | null): Buffer {
const text = data.toString('utf8');
if (data.includes(0) || !Buffer.from(text, 'utf8').equals(data)) return data;
- const projected = this.mapTextFromAgent(text);
+ const projected = this.mapContentFromAgent(text, original);
return projected === text ? data : Buffer.from(projected, 'utf8');
}
@@ -332,9 +807,10 @@ export class ExecutorWorkspace {
if (!aliases.length) return command;
// 路径尾部遇到引号即止:闭合引号属于外层 shell 语法,吞进路径会被按引号上下文转义
// ('…mjs' → '…mjs'\''),留下未闭合的引号。
- const pattern = pathTextPattern(aliases, true);
- const quoteContext = (input: string, end: number): 'none' | 'single' | 'double' => {
+ const prefixes = aliasPrefixes(aliases);
+ const commandContext = (input: string, end: number): { quote: 'none' | 'single' | 'double'; wordStart: number } => {
let quote: 'none' | 'single' | 'double' = 'none';
+ let wordStart = 0;
let escaped = false;
for (let i = 0; i < end; i += 1) {
const char = input[i];
@@ -342,12 +818,13 @@ export class ExecutorWorkspace {
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 (quote === 'none' && /[\s;|&()<>]/.test(char)) wordStart = i + 1;
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';
}
- return quote;
+ return { quote, wordStart };
};
const quote = (value: string, context: 'none' | 'single' | 'double'): string => {
if (dialect === 'cmd') {
@@ -361,18 +838,39 @@ export class ExecutorWorkspace {
? "'" + value.replace(/'/g, "'\\''") + "'"
: value;
};
+ const inPathList = (input: string, index: number): boolean => {
+ const { wordStart } = commandContext(input, index);
+ const word = input.slice(wordStart, index);
+ const assignment = (dialect === 'cmd' ? /^"?([A-Za-z_][A-Za-z0-9_]*)=/ : /^([A-Za-z_][A-Za-z0-9_]*)\+?=/).exec(word);
+ if (!assignment) return false;
+ const name = dialect === 'cmd' ? assignment[1].toUpperCase() : assignment[1];
+ // 常见环境路径列表也包括 NODE_PATH、CLASSPATH、XDG_DATA_DIRS 等。
+ // 文件名变量(如 FILE)里的冒号/分号仍按字面路径处理。
+ return /(?:PATH|_DIRS)$/.test(name) || ['PERL5LIB', 'PERLLIB', 'RUBYLIB', 'TEXINPUTS', 'INCLUDE', 'LIB'].includes(name);
+ };
+ const listSeparator = dialect === 'cmd' ? ';' : ':';
+ // Shell 里的边界由引号与展开语法决定。引号内的空格/标点属于目录名;动态后缀保留给 shell。
+ const commandBoundary = (text: string, index: number, start: number): 'separator' | 'punctuation' | null => {
+ const char = text[index];
+ if (char === undefined || char === '/' || char === '\\') return 'separator';
+ const { quote: context } = commandContext(text, index);
+ if ((context === 'single' && char === "'") || (context === 'double' && char === '"')) return 'separator';
+ if (dialect === 'cmd' && /[%!^]/.test(char)) return 'separator';
+ if (dialect === 'bash' && context !== 'single' && /[$\x60]/.test(char)) return 'separator';
+ // PATH 列表在引号内仍分隔目录;普通文件名里的冒号/分号保持字面语义。
+ if (char === listSeparator && inPathList(text, start)) return 'separator';
+ if (context !== 'none') return null;
+ return /[\s'"*?\[{};|&()<>]/.test(char) ? 'separator' : null;
+ };
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) continue;
+ for (let hit = nextAliasPrefix(command, 0, prefixes, undefined, commandBoundary); hit; hit = nextAliasPrefix(command, end, prefixes, undefined, commandBoundary)) {
+ const { alias, index: start } = hit;
const separator = alias.to.includes('\\') ? '\\' : '/';
- const context = quoteContext(command, start);
- const windowsPath = /^[A-Za-z]:|^[/\\]{2}/.test(prefix);
- let suffixEnd = start + prefix.length;
+ const { quote: context } = commandContext(command, start);
+ const pathList = inPathList(command, start);
+ const windowsPath = WINDOWS_PATH.test(command.slice(start, hit.end));
+ let suffixEnd = hit.end;
const suffixStart = suffixEnd;
if ((windowsPath || dialect === 'cmd') && /[/\\]/.test(command[suffixEnd] ?? '')) {
// 只转换静态路径段。转义、变量与命令替换从原文原样保留,尤其不能把转义
@@ -382,6 +880,7 @@ export class ExecutorWorkspace {
if (char === '\r' || char === '\n') break;
if (context === 'single' && char === "'") break;
if (context === 'double' && char === '"') break;
+ if (pathList && char === listSeparator) break;
if (context === 'none' && /[\s'"\x60;:|&()<>}\]]/.test(char)) break;
if (dialect === 'bash' && context !== 'single'
&& (/[$\x60]/.test(char) || (char === '\\'
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index b406e78274..f6e531478e 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -882,8 +882,10 @@ handler 无 sender 依赖;不加入共享任务访客白名单,不进入自
- **Codex 依赖**:B 的 Codex 通过 app-server 的实验接口 `environment/add` + `environments` 把 A 注册为
exec-server 执行环境,A 为每条连接起本机 `codex exec-server --listen stdio://`。该接口随 Codex 版本
可能变化,升级 Codex 时需回归 `remote-agent/__tests__/codexHosted.e2e.test.ts`。A 的中继按方法语义
- 过本机闸门(`controller/execServerRelay.ts`):`fs/readFile`、`fs/open` 的 read 模式与目录读取按读取,
- `fs/open` 的 replace/write 模式按写入(后续 `fs/writeBlock` 只有句柄,权限必须在 open 时检查),`fs/walk` 按
+ 过本机闸门(`controller/execServerRelay.ts`):当前固定 Codex 0.159.2 的 `fs/open` 只读,文件写入使用
+ `fs/writeFile` 的 `dataBase64`,没有 `fs/writeBlock`;协议依据为
+ [固定版本源码](https://github.com/openai/codex/blob/ff6aec96948b70d94983af2641a6b67c94faeff5/codex-rs/exec-server-protocol/src/protocol.rs#L558)。
+ `fs/readFile`、`fs/open` 的缺省/read 模式与目录读取按读取,显式非 read 的 open 模式仍从严按写入;`fs/walk` 按
目录级读取,`fs/getMetadata`、`fs/canonicalize` 等只看元数据的不过闸门,其余 `fs/` 方法按写入;
升级 Codex 后核对 exec-server 新增的方法,只读的要显式归类,否则会被当成写入拒掉(#5764)。
- **影子目录与配置同步**:`open` 载荷除项目说明文件(含 `.claude/CLAUDE.md`、`.claude/rules`、
@@ -925,8 +927,23 @@ handler 无 sender 依赖;不加入共享任务访客白名单,不进入自
流式正文按来源、轮次和子代理 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`。
+ 正文与命令里的目录前缀只按完整目录段匹配,与文件操作的路径解析一致:以工作目录名开头的同级目录(`xxx.git`、
+ `xxx-v1`)按上级目录投影,不能切成「工作目录 + `.git`」,否则文字与命令落在 `xxx.git`、文件工具却写进 `p.git`;
+ 空白、引号与句末标点后面是否接着同级目录名(`xxx copy`、`xxx (1)`),投影给 B 前在 A 上按磁盘核对。
+ 命令按执行端 shell 的引号语义识别边界:引号内空格属于完整目录名,不依赖目标已经存在;紧接前缀的变量与
+ 未引用的通配符由 shell 展开,保持原语义,不把它们当成静态目录名。
+ Agent 写回文件(Claude Write / Edit / NotebookEdit、Pi `fs.write`、Codex `fs/write*`)时,按写入前的文件内容查回
+ 路径的原写法(分隔符、Git Bash `/c/…`、`/tmp`、大小写、符号链接),完整原样往返及能按上下文定位的未改内容保留原写法;
+ 多种原写法折叠成同一虚拟文本且缺少可定位上下文时,不能保证任意重写逐字节无损。Edit 按 Agent 读到的投影视图
+ 检查唯一性与批量替换,避免同一虚拟路径的多种原写法漏改;新出现的路径
+ 沿用 Agent 的分隔符,A 为 Windows 时不把 `/` 改成 `\`,避免源码字符串里出现 `\f`、`\b` 等转义。Codex 的
+ `fs/write*` 的路径和命令在权限检查前改写,原内容只在授权通过、实际转发前读取,凭证类文件不预读。正文、代码段与链接里还原的路径同样沿用 Agent 的分隔符,
+ Markdown 不会把 `\.git` 当转义吞掉;结构化路径字段仍用 A 本机写法。
+ 事件身份、Agent 元信息、权限与提问的回执不改写,原生 Agent 会话继续使用 B 的虚拟路径;计划审阅的计划正文与
+ 计划文件按 A 的真实路径展示和保存,用户改过的计划及要求修订的反馈交回前换回 B 的虚拟路径。旧消息不回填。
+ 回归见 `remote-agent/executor/__tests__/virtualWorkspace.test.ts`、`remote-agent/executor/__tests__/pathFidelity.test.ts`
+ 与 `remote-agent/__tests__/eventProjection.test.ts`;固定 Codex 的真实写入协议回归见
+ `remote-agent/__tests__/execServerProjection.e2e.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 的