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): 转换 Codex 沙箱权限里的路径,非完全访问档在两端系统不同时也能执行

fmfsaisaibd8383b3bbc4
diff --git a/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts b/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts
index 071beb5acc..6ec240c642 100644
--- a/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts
+++ b/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts
@@ -138,9 +138,100 @@ 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 (result.sandbox !== undefined) result.sandbox = mapExecServerSandbox(result.sandbox, workspace);
return mapFileData ? mapExecServerFileData(result, workspace, method) : result;
}
+type JsonRecord = Record<string, unknown>;
+
+function asJsonRecord(value: unknown): JsonRecord | null {
+ return value && typeof value === 'object' && !Array.isArray(value) ? value as JsonRecord : null;
+}
+
+/** 本机能用的绝对路径:任务电脑是 Windows 时必须带盘符或是 UNC,`/Users/…` 这类 POSIX 路径不算。 */
+function isLocalAbsolutePath(value: string): boolean {
+ return process.platform === 'win32' ? /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/])/.test(value) : path.posix.isAbsolute(value);
+}
+
+/** Agent 发来的 file URI 还原成它那边的路径写法(`file:///C:/x` → `C:/x`,UNC 带回主机名)。 */
+function agentPathFromUri(value: unknown): string | null {
+ if (typeof value !== 'string' || !value.startsWith('file://')) return null;
+ try {
+ const url = new URL(value);
+ const pathname = decodeURIComponent(url.pathname);
+ return url.host ? `//${url.host}${pathname}` : pathname.replace(/^\/([A-Za-z]:)/, '$1');
+ } catch {
+ return null;
+ }
+}
+
+/** 虚拟工作区内的 file URI 换成本机 file URI;Agent 主机自己的路径返回 null。 */
+function localUriFromAgent(value: unknown, workspace: ExecutorWorkspace): string | null {
+ const agentPath = agentPathFromUri(value);
+ const local = agentPath === null ? null : workspace.localPathFromAgent(agentPath);
+ return local === null ? null : pathToFileURL(local).href;
+}
+
+/** 沙箱上下文里解释权限条目用的目录(policyContext 里同名字段同样处理)。 */
+function mapSandboxDirs(record: JsonRecord, workspace: ExecutorWorkspace): JsonRecord {
+ const result = { ...record };
+ for (const key of ['cwd', 'userHomeDir']) {
+ if (result[key] === undefined) continue;
+ const local = localUriFromAgent(result[key], workspace);
+ if (local === null) delete result[key];
+ else result[key] = local;
+ }
+ for (const key of ['workspaceRoots', 'temporaryDirectories']) {
+ const items = result[key];
+ if (Array.isArray(items)) result[key] = items.flatMap((item) => localUriFromAgent(item, workspace) ?? []);
+ }
+ return result;
+}
+
+/**
+ * 一条文件权限:虚拟工作区内的路径换成本机路径。Agent 主机自己的路径(如它的 Codex 记忆目录)在本机
+ * 没有对应位置,读写授权直接丢掉,只收不放;禁止条目在本机也是合法绝对路径时原样保留,不删本机
+ * 有意义的禁止规则。相对 glob 与特殊路径(`:tmpdir`、项目根等)由本机 exec-server 按映射后的目录解释。
+ */
+function mapSandboxEntry(entry: unknown, workspace: ExecutorWorkspace): unknown[] {
+ const record = asJsonRecord(entry);
+ const target = asJsonRecord(record?.path);
+ if (!record || !target) return [entry];
+ const deny = record.access === 'deny' || record.access === 'none';
+ if (target.type === 'path') {
+ const local = localUriFromAgent(target.path, workspace);
+ if (local !== null) return [{ ...record, path: { ...target, path: local } }];
+ const agentPath = agentPathFromUri(target.path);
+ return deny && agentPath !== null && isLocalAbsolutePath(agentPath) ? [entry] : [];
+ }
+ if (target.type === 'glob_pattern' && typeof target.pattern === 'string' && /^(?:[A-Za-z]:|[\\/])/.test(target.pattern)) {
+ const local = workspace.localPathFromAgent(target.pattern);
+ if (local !== null) return [{ ...record, path: { ...target, pattern: local } }];
+ return deny && isLocalAbsolutePath(target.pattern) ? [entry] : [];
+ }
+ return [entry];
+}
+
+/**
+ * Codex 请求(process/start、fs/*)里的 `sandbox`:权限条目和解释它们用的目录都是 Agent 主机上看到的
+ * file URI。原样转给本机 exec-server,两端系统不同时会因路径不属于本机被拒(`invalid sandbox
+ * permission path URI`),相同时则放行的是本机不存在的虚拟目录。这里换成本机路径,规则见 mapSandboxEntry。
+ */
+function mapExecServerSandbox(value: unknown, workspace: ExecutorWorkspace): unknown {
+ const record = asJsonRecord(value);
+ if (!record || workspace.agentPathPrefixes().length === 0) return value;
+ const sandbox = mapSandboxDirs(record, workspace);
+ const policyContext = asJsonRecord(sandbox.policyContext);
+ if (policyContext) sandbox.policyContext = mapSandboxDirs(policyContext, workspace);
+ const permissions = asJsonRecord(sandbox.permissions);
+ const fileSystem = asJsonRecord(permissions?.file_system);
+ if (permissions && fileSystem && Array.isArray(fileSystem.entries)) {
+ const entries = fileSystem.entries.flatMap((entry) => mapSandboxEntry(entry, workspace));
+ sandbox.permissions = { ...permissions, file_system: { ...fileSystem, entries } };
+ }
+ return sandbox;
+}
+
/**
* 授权通过后、实际转发前才读写入目标的原内容,排队中的请求也在出队后读取最新内容。
* 路径与命令的映射仍在权限检查前完成,确保 gate 检查的是实际执行的操作。
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 bc17f4cf79..09239134fe 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
@@ -22,6 +22,12 @@ 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, '/'); }
+/** 转发给 exec-server 的 Codex 请求里与沙箱有关的字段。 */
+interface MappedSandboxRequest {
+ cwd?: string;
+ sandbox: { cwd?: string; permissions: { file_system: { entries: unknown[] } } };
+}
+
function setup(virtual: string) {
const project = path.join(root, 'real project');
fs.mkdirSync(project);
@@ -395,6 +401,77 @@ describe('virtual workspace', () => {
await executor.close();
});
+ it.skipIf(process.platform === 'win32')('maps Codex sandbox permissions from a Windows agent and drops paths that only exist on the agent computer', () => {
+ const project = path.join(root, 'real project');
+ const temp = path.join(root, 'temp');
+ fs.mkdirSync(project);
+ fs.mkdirSync(temp);
+ const workspace = new ExecutorWorkspace({ workingDir: project, aliases: [
+ { from: 'C:\\Agent\\mirror\\workspace', to: project },
+ { from: 'C:\\Agent\\mirror\\tmp', to: temp },
+ ] });
+ workspace.setVirtualRoot('C:\\Agent\\mirror');
+ const local = (target: string) => pathToFileURL(target).href;
+ const sandbox = {
+ permissions: { type: 'managed', network: 'restricted', file_system: { type: 'restricted', entries: [
+ { path: { type: 'special', value: { kind: 'root' } }, access: 'read' },
+ { path: { type: 'path', path: 'file:///C:/Agent/mirror/workspace' }, access: 'write' },
+ { path: { type: 'path', path: 'file:///c:/agent/mirror/workspace/.git' }, access: 'read' },
+ { path: { type: 'glob_pattern', pattern: 'C:\\Agent\\mirror\\workspace\\**\\*.env' }, access: 'deny' },
+ { path: { type: 'glob_pattern', pattern: '**/*.pem' }, access: 'deny' },
+ { path: { type: 'path', path: 'file:///C:/Agent/codex-home/memories' }, access: 'write' },
+ { path: { type: 'glob_pattern', pattern: 'C:\\Agent\\codex-home\\**' }, access: 'write' },
+ { path: { type: 'path', path: 'file:///C:/Agent/secrets' }, access: 'deny' },
+ ] } },
+ cwd: 'file:///C:/Agent/mirror/workspace',
+ policyContext: { cwd: 'file:///C:/Agent/mirror/workspace', workspaceRoots: ['file:///C:/Agent/mirror/workspace', 'file:///C:/Agent/other'] },
+ userHomeDir: 'file:///C:/Agent/home',
+ temporaryDirectories: ['file:///C:/Agent/mirror/tmp', 'file:///C:/Agent/AppTemp'],
+ windowsSandboxLevel: 'disabled',
+ };
+ const params = mapExecServerParams({ argv: ['/bin/zsh', '-lc', 'true'], cwd: 'file:///C:/Agent/mirror/workspace', sandbox }, workspace, 'process/start') as MappedSandboxRequest;
+ expect(params.cwd).toBe(local(project));
+ expect(params.sandbox).toEqual({
+ permissions: { type: 'managed', network: 'restricted', file_system: { type: 'restricted', entries: [
+ { path: { type: 'special', value: { kind: 'root' } }, access: 'read' },
+ { path: { type: 'path', path: local(project) }, access: 'write' },
+ { path: { type: 'path', path: local(path.join(project, '.git')) }, access: 'read' },
+ { path: { type: 'glob_pattern', pattern: path.join(project, '**', '*.env') }, access: 'deny' },
+ { path: { type: 'glob_pattern', pattern: '**/*.pem' }, access: 'deny' },
+ ] } },
+ cwd: local(project),
+ policyContext: { cwd: local(project), workspaceRoots: [local(project)] },
+ temporaryDirectories: [local(temp)],
+ windowsSandboxLevel: 'disabled',
+ });
+ // fs/* 请求带同一个沙箱上下文。
+ const read = mapExecServerParams({ path: 'file:///C:/Agent/mirror/workspace/a.txt', sandbox }, workspace, 'fs/readFile') as MappedSandboxRequest;
+ expect(read.sandbox).toEqual(params.sandbox);
+ });
+
+ it('maps Codex sandbox permissions from a POSIX agent and keeps deny rules that are valid on this computer', async () => {
+ const { workspace, project, executor } = setup('/home/agent/workspace');
+ const sandbox = {
+ permissions: { type: 'managed', network: 'restricted', file_system: { type: 'restricted', entries: [
+ { path: { type: 'path', path: 'file:///home/agent/workspace' }, access: 'write' },
+ { path: { type: 'path', path: 'file:///home/agent/.codex/memories' }, access: 'write' },
+ { path: { type: 'path', path: 'file:///home/agent/.ssh' }, access: 'deny' },
+ ] } },
+ cwd: 'file:///home/agent/workspace',
+ };
+ const params = mapExecServerParams({ path: 'file:///home/agent/workspace/a.txt', sandbox }, workspace, 'fs/readFile') as MappedSandboxRequest;
+ expect(params.sandbox.permissions.file_system.entries).toEqual([
+ { path: { type: 'path', path: pathToFileURL(project).href }, access: 'write' },
+ // 任务电脑是 Windows 时 POSIX 路径不是本机路径,禁止条目也无从对应。
+ ...(process.platform === 'win32' ? [] : [{ path: { type: 'path', path: 'file:///home/agent/.ssh' }, access: 'deny' }]),
+ ]);
+ expect(params.sandbox.cwd).toBe(pathToFileURL(project).href);
+ // 没有虚拟工作区(旧版对端)时沙箱原样转发,与之前一致。
+ const plain = new ExecutorWorkspace({ workingDir: project });
+ expect((mapExecServerParams({ sandbox }, plain) as MappedSandboxRequest).sandbox).toBe(sandbox);
+ await executor.close();
+ });
+
it('projects Cindy MCP path arguments and JSON/SSE results while leaving file content arguments intact', async () => {
const { workspace, project, executor } = setup('/Users/agent/workspace');
let received: any;
diff --git a/apps/desktop/src/main/remote-agent/executor/workspace.ts b/apps/desktop/src/main/remote-agent/executor/workspace.ts
index 0a2aa9e73c..d9493c3002 100644
--- a/apps/desktop/src/main/remote-agent/executor/workspace.ts
+++ b/apps/desktop/src/main/remote-agent/executor/workspace.ts
@@ -593,11 +593,16 @@ export class ExecutorWorkspace {
/** 影子路径映射回本机路径;不是影子路径时原样返回。 */
mapAlias(input: string): string {
+ return this.localPathFromAgent(input) ?? input;
+ }
+
+ /** 影子路径对应的本机路径;不是影子路径(Agent 主机自己的路径)时返回 null。 */
+ localPathFromAgent(input: string): string | null {
for (const alias of this.aliases) {
const rest = stripAliasPrefix(input, alias.from);
if (rest !== null) return rest ? path.join(alias.to, ...rest.split('/')) : alias.to;
}
- return input;
+ return null;
}
/** 本机真实路径投影到 Agent 主机上的路径;仅匹配完整路径段。 */
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 9bf40c5c4c..4d74d6ceee 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -1053,6 +1053,11 @@ handler 无 sender 依赖;不加入共享任务访客白名单,不进入自
`fs/readFile`、`fs/open` 的缺省/read 模式与目录读取按读取,显式非 read 的 open 模式仍从严按写入;`fs/walk` 按
目录级读取,`fs/getMetadata`、`fs/canonicalize` 等只看元数据的不过闸门,其余 `fs/` 方法按写入;
升级 Codex 后核对 exec-server 新增的方法,只读的要显式归类,否则会被当成写入拒掉(#5764)。
+ 非完全访问档下 `process/start` 与 `fs/*` 带 `sandbox`(固定版本 `codex-rs/file-system/src/lib.rs` 的
+ `WireFileSystemSandboxContext`),其中目录与权限条目都是 B 上看到的 file URI,中继换成 A 的路径:虚拟工作区内的
+ 映射为本机路径;不在其中的是 B 自己的目录(如它的 Codex 记忆目录),读写授权丢弃,禁止条目在 A 上也是合法
+ 绝对路径时原样保留,只收不放;网络与 Windows 沙箱档位不动。原样转发时两端系统不同会被 A 的 exec-server
+ 拒绝(`invalid sandbox permission path URI`)。
- **影子目录与配置同步**:`open` 载荷除项目说明文件(含 `.claude/CLAUDE.md`、`.claude/rules`、
`.codex/skills`)外还带 `ancestorFiles`(项目上级目录里的
`CLAUDE.md` / `CLAUDE.local.md` / `AGENTS.md` / `AGENTS.override.md`,按层级 `up`,最多 24 级)与