Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(codex): restore Review startup and scoped reads on Windows
DavidShenc0b5c073c841
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex dec17e867e..62e73f634e 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -692,7 +692,7 @@ describe('Codex official OAuth host isolation', () => {});it.each([false, true])('retires scoped snapshots and blocks new hosts during configuration persistence (review=%s)', async (reviewMode) => {- if (reviewMode) MockCodexTransport.userAgent = 'mock-codex/0.145.0';+ if (reviewMode) MockCodexTransport.userAgent = 'mock-codex/0.156.0';if (reviewMode) MockCodexTransport.onCreate = (transport) => transport.setMockResponse('config/read', { result: { config: { cli_auth_credentials_store: 'ephemeral', mcp_servers: { node_repl: { command: 'synthetic-node-repl' } } } } });const workingDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-scope-change-'));const deps = isolatedDeps();@@ -725,7 +725,7 @@ describe('Codex official OAuth host isolation', () => {});it.each([false, true])('supersedes an in-flight scoped creation at the configuration boundary (review=%s)', async (reviewMode) => {- MockCodexTransport.userAgent = 'mock-codex/0.145.0';+ MockCodexTransport.userAgent = 'mock-codex/0.156.0';if (reviewMode) MockCodexTransport.onCreate = (transport) => transport.setMockResponse('config/read', { result: { config: { cli_auth_credentials_store: 'ephemeral', mcp_servers: { node_repl: { command: 'synthetic-node-repl' } } } } });const workingDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-scope-inflight-'));const deps = isolatedDeps();@@ -1633,7 +1633,11 @@ describe('CodexAgent permissions', () => {});});- it('starts Review on an isolated memory-free host with an immutable read-only sandbox', async () => {+ it.each([+ { transport: 'absent', memoryConfig: undefined },+ { transport: 'stdio', memoryConfig: { command: 'memory-server', enabled: true } },+ { transport: 'http', memoryConfig: { url: 'http://127.0.0.1:45831/mcp', enabled: true } },+ ])('starts Review on an isolated memory-free host with an immutable read-only sandbox (memory: $transport)', async ({ memoryConfig }) => {const artifactDir = await fs.mkdtemp(path.join(os.tmpdir(), 'codex-review-artifact-'));tempRoots.push(artifactDir);const artifactPath = path.join(artifactDir, 'artifact.txt');@@ -1683,7 +1687,10 @@ describe('CodexAgent permissions', () => {if (method === Method.ConfigRead) {return {config: {- mcp_servers: { local_docs: { command: '/usr/bin/local-docs', enabled: true } },+ mcp_servers: {+ local_docs: { command: '/usr/bin/local-docs', enabled: true },+ ...(memoryConfig ? { cindy_memory: memoryConfig } : {}),+ },plugins: {'configured@personal': {mcp_servers: {@@ -1700,6 +1707,7 @@ describe('CodexAgent permissions', () => {{ name: 'codex_apps', tools: {} },{ name: 'local_docs', tools: {} },{ name: 'configured_server', tools: {} },+ ...(memoryConfig ? [{ name: 'cindy_memory', tools: {} }] : []),],nextCursor: null,};@@ -1709,7 +1717,7 @@ describe('CodexAgent permissions', () => {},{buildSessionMcpConfig: () => ({ 'mcp_servers.should_not_exist': { command: 'write' } }),- userAgent: 'mock-codex/0.145.0',+ userAgent: 'mock-codex/0.156.0',},);@@ -1777,7 +1785,22 @@ describe('CodexAgent permissions', () => {},});expect(threadStart).not.toHaveProperty('sandbox');- expect(threadStart).not.toHaveProperty('dynamicTools');+ if (process.platform === 'win32') {+ expect(threadStart.config).toMatchObject({+ project_doc_max_bytes: 0,+ 'features.shell_tool': false,+ 'features.unified_exec': false,+ });+ expect(threadStart.dynamicTools).toEqual([+ expect.objectContaining({ name: 'review_read_file' }),+ expect.objectContaining({ name: 'review_list_directory' }),+ expect.objectContaining({ name: 'review_view_image' }),+ ]);+ } else {+ expect(threadStart.config).not.toHaveProperty('project_doc_max_bytes');+ expect(threadStart).not.toHaveProperty('dynamicTools');+ }+ expect(threadStart.config).not.toHaveProperty(['windows.sandbox']);expect((threadStart.config as Record<string, unknown>)['skills.config']).toEqual([{path: '/home/test/.codex/plugins/cache/personal/unsafe-plugin/1.0.0/skills/review/SKILL.md',@@ -1787,6 +1810,11 @@ describe('CodexAgent permissions', () => {expect(threadStart.config).not.toHaveProperty(['mcp_servers.should_not_exist']);expect(threadStart.config).not.toHaveProperty(['mcp_servers.codex_apps.enabled']);expect(threadStart.config).not.toHaveProperty(['mcp_servers.configured_server.enabled']);+ if (memoryConfig) {+ expect(threadStart.config).toHaveProperty(['mcp_servers.cindy_memory.enabled'], false);+ } else {+ expect(threadStart.config).not.toHaveProperty(['mcp_servers.cindy_memory.enabled']);+ }expect(handle.getPlanMode?.()).toBe(false);await expect(@@ -1852,9 +1880,44 @@ describe('CodexAgent permissions', () => {await handle.setPermissionMode('bypassPermissions');await handle.setPlanMode?.(true);expect(handle.getPlanMode?.()).toBe(false);+ if (process.platform === 'win32') {+ const read = (overrides = {}) => handlers.dynamicToolCall!({+ threadId: 'start-thread-id', turnId: 'turn-review', callId: 'read-1',+ namespace: null, tool: 'review_read_file', arguments: { path: artifactPath },+ ...overrides,+ }, { requestId: 'read-request' });+ await expect(read()).resolves.toMatchObject({ success: true });+ await expect(read({ threadId: 'child-thread' })).resolves.toMatchObject({ success: false });+ await expect(read({ namespace: 'untrusted' })).resolves.toMatchObject({ success: false });+ await expect(read({ tool: 'exec_command' })).resolves.toMatchObject({ success: false });+ await expect(read({ arguments: { path: dotenvPath } })).resolves.toMatchObject({ success: false });+ // Stop after the descriptor opens, before any bytes are returned.+ const open = fs.open.bind(fs);+ const opening = vi.spyOn(fs, 'open').mockImplementationOnce(async (...args) => {+ const file = await open(...args);+ await handle.abort();+ return file;+ });+ await expect(read()).resolves.toMatchObject({ success: false });+ opening.mockRestore();+ await expect(read()).resolves.toMatchObject({ success: false });+ await handle.close();+ await expect(read()).resolves.toMatchObject({ success: false });+ }await handle.close();});+ it.skipIf(process.platform !== 'win32')('rejects Windows Review runtimes without a disableable native image reader', async () => {+ const workingDir = await fs.mkdtemp(path.join(os.tmpdir(), 'codex-review-old-windows-'));+ tempRoots.push(workingDir);+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent, undefined, { userAgent: 'mock-codex/0.145.0' });+ await expect(agent.startSession({+ sessionId: 'review-old-windows', model: 'gpt-5.5', workingDir, reviewMode: true,+ })).rejects.toThrow('Windows Cindy Review requires Codex app-server 0.156.0');+ expect(host.request.mock.calls.some(([method]) => method === Method.ThreadStart)).toBe(false);+ });+it('keeps Bot identity and MCP config while honoring the selected task permission mode', async () => {const agent = new CodexAgent(createDeps());const host = installFakeHost(agent, undefined, {@@ -1976,7 +2039,7 @@ describe('CodexAgent permissions', () => {}return undefined;},- { userAgent: 'mock-codex/0.145.0' },+ { userAgent: 'mock-codex/0.156.0' },);await expect(diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex efab6ea9a8..74d314409c 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -93,6 +93,7 @@ import {assertReviewMessageContentPaths,buildReviewReadGrants,} from '../shared/review-read-scope.js';+import { REVIEW_READ_TOOLS, callReviewReadTool, reviewReadDenied } from './review-read-tools.js';import {annotatePermissionRequestForUnavailableReview,composeAutoReviewIntentWithApprovedPlan,@@ -4902,6 +4903,7 @@ assertRouteCurrent();}const registeredHostDynamicToolKeys = new Set(hostDynamicTools.map(dynamicToolKey));const sessionDynamicTools = [+ ...(reviewMode && process.platform === 'win32' ? REVIEW_READ_TOOLS : []),...(!reviewMode && shouldRegisterAskUserDynamicTool(opts) ? [ASK_USER_DYNAMIC_TOOL] : []),...(!reviewMode ? hostDynamicTools : []),];@@ -5488,6 +5490,14 @@ assertRouteCurrent();}const readonlyReferenceDirsSupported = supportsCodexReadonlyReferenceDirs(initResp.userAgent);const resumeExcludeTurnsSupported = supportsCodexResumeExcludeTurns(initResp.userAgent);+ // Verified with 0.156.0: features.view_image removes the native reader.+ // 0.145.0 ignores this flag and reads images outside the permission scope.+ if (reviewMode && process.platform === 'win32' && !codexUserAgentAtLeast(initResp.userAgent, [0, 156, 0])) {+ releaseHostBindingLeaseIfNeeded();+ throw new Error(+ `Windows Cindy Review requires Codex app-server 0.156.0 or newer to enforce scoped reads (current: ${initResp.userAgent ?? 'unknown'})`,+ );+ }if (reviewMode && !readonlyReferenceDirsSupported) {releaseHostBindingLeaseIfNeeded();throw new Error(@@ -6276,6 +6286,24 @@ assertRouteCurrent();: {}),...(reviewMode? {+ // Windows native sandboxes cannot enforce this split read scope.+ // Keep the deny policy, and route evidence reads through the host.+ // Native AGENTS discovery also invokes that incompatible sandbox.+ ...(process.platform === 'win32' ? {+ project_doc_max_bytes: 0,+ 'features.shell_tool': false,+ 'features.unified_exec': false,+ 'features.shell_snapshot': false,+ 'features.view_image': false,+ 'features.code_mode': false,+ 'features.code_mode_only': false,+ 'features.js_repl': false,+ 'features.browser_use': false,+ 'features.browser_use_external': false,+ 'features.computer_use': false,+ 'features.image_generation': false,+ 'features.multi_agent_v2': false,+ } : {}),web_search: 'disabled','features.apps': false,'features.goals': false,@@ -6284,7 +6312,10 @@ assertRouteCurrent();'features.remote_plugin': false,}: {}),- ...(!makerMemoryEnabled && !opts.botRuntimeProfile+ // Review disables only transport-bearing entries discovered above.+ // Its host omits Cindy's MCP bridge, so a bare memory override would+ // create an invalid transport even though the entry is disabled.+ ...(!reviewMode && !makerMemoryEnabled && !opts.botRuntimeProfile? { 'mcp_servers.cindy_memory.enabled': false }: {}),// Configure the native window and its 90% compaction budget together.@@ -9686,7 +9717,7 @@ assertRouteCurrent();params: DynamicToolCallParams,meta: { requestId: string | number },): Promise<DynamicToolCallResponse> => {- if (reviewMode) {+ if (reviewMode && process.platform !== 'win32') {return {contentItems: [{ type: 'inputText', text: 'Cindy Review does not allow dynamic tools.' }],success: false,@@ -9710,6 +9741,16 @@ assertRouteCurrent();success: false,};}+ if (reviewMode) {+ const readIsActive = () => !closed && isCurrentHost()+ && params.threadId === threadId && params.turnId === currentTurnId+ && !turnInterruptOrigins.has(params.turnId)+ && !resolvedWhileBufferedRequestIds.has(String(meta.requestId));+ if (!readIsActive() || params.namespace) return reviewReadDenied();+ const response = await callReviewReadTool(params.tool, params.arguments, opts.workingDir, reviewReadGrants);+ return await gateServerRequestTurn(params.turnId, params.threadId) && readIsActive()+ ? response : reviewReadDenied();+ }const toolUseId = activeDynamicToolUseId(params);if (isAskUserDynamicTool(params)) {// Codex app-server keeps dynamic tools at the root thread and may makediff --git a/packages/maker-core/src/agents/codex/review-read-tools.test.ts b/packages/maker-core/src/agents/codex/review-read-tools.test.tsnew file mode 100644index 0000000000..cc3d929599--- /dev/null+++ b/packages/maker-core/src/agents/codex/review-read-tools.test.ts@@ -0,0 +1,115 @@+import { promises as fs } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { buildReviewReadGrants, type ReviewReadGrant } from '../shared/review-read-scope.js';+import { callReviewReadTool } from './review-read-tools.js';++describe('Windows Review host reads', () => {+ let root: string;+ let work: string;+ let grants: ReviewReadGrant[];+ beforeEach(async () => {+ root = await fs.mkdtemp(path.join(tmpdir(), 'cindy-review-tools-'));+ work = path.join(root, 'work');+ await fs.mkdir(work);+ grants = await buildReviewReadGrants(work, []);+ });+ afterEach(async () => {+ vi.restoreAllMocks();+ await fs.rm(root, { recursive: true, force: true });+ });+ const text = (result: Awaited<ReturnType<typeof callReviewReadTool>>) => {+ expect(result.success).toBe(true);+ const item = result.contentItems[0];+ if (item.type !== 'inputText') throw new Error('Expected text');+ return JSON.parse(item.text);+ };+ it('paginates numbered evidence without modifying the file', async () => {+ const content = Array.from({ length: 250 }, (_, i) => `line ${i}`).join('\n');+ await fs.writeFile(path.join(work, 'code.ts'), content);+ const first = text(await callReviewReadTool('review_read_file', { path: 'code.ts' }, work, grants));+ expect(first.text).toContain('200: line 199\n');+ expect(first.nextOffset).toBe(200);+ const last = text(await callReviewReadTool('review_read_file', { path: 'code.ts', offset: 200 }, work, grants));+ expect(last.text).toMatch(/^201: line 200/);+ expect(last.nextOffset).toBeNull();+ expect(await fs.readFile(path.join(work, 'code.ts'), 'utf8')).toBe(content);+ });+ it('allows an explicitly granted external file, but not its siblings', async () => {+ const artifact = path.join(root, 'artifact.md');+ await fs.writeFile(artifact, 'evidence');+ await fs.writeFile(path.join(root, 'sibling.md'), 'private');+ grants = await buildReviewReadGrants(work, [artifact]);+ expect(text(await callReviewReadTool('review_read_file', { path: artifact }, work, grants)).text).toContain('evidence');+ expect((await callReviewReadTool('review_read_file', { path: '../sibling.md' }, work, grants)).success).toBe(false);+ });+ it('filters secrets and escaping junctions from directory listings and reads', async () => {+ await fs.mkdir(path.join(work, '.git'));+ await fs.writeFile(path.join(work, '.env'), 'SYNTHETIC_SECRET');+ await fs.writeFile(path.join(work, 'safe.md'), 'safe');+ const outside = path.join(root, 'outside');+ await fs.mkdir(outside);+ await fs.writeFile(path.join(outside, 'private.md'), 'SYNTHETIC_PRIVATE');+ await fs.symlink(outside, path.join(work, 'escape'), process.platform === 'win32' ? 'junction' : 'dir');+ const result = text(await callReviewReadTool('review_list_directory', { path: '.' }, work, grants));+ expect(result.entries).toEqual([{ name: 'safe.md', directory: false }]);+ for (const target of ['.env', '.git', 'escape/private.md', '../outside/private.md']) {+ const result = await callReviewReadTool('review_read_file', { path: target }, work, grants);+ expect(result.success).toBe(false);+ expect(JSON.stringify(result)).not.toContain('SYNTHETIC');+ }+ });+ it('rejects external hard links', async () => {+ const outside = path.join(root, 'private.md');+ await fs.writeFile(outside, 'SYNTHETIC_PRIVATE');+ await fs.link(outside, path.join(work, 'alias.md'));+ expect((await callReviewReadTool('review_read_file', { path: 'alias.md' }, work, grants)).success).toBe(false);+ });+ it('rejects file substitution between validation and opening', async () => {+ const target = path.join(work, 'evidence.md');+ await fs.writeFile(target, 'safe');+ const open = fs.open.bind(fs);+ vi.spyOn(fs, 'open').mockImplementationOnce(async (...args) => {+ await fs.rename(target, `${target}.original`);+ await fs.writeFile(target, 'replaced');+ return open(...args);+ });+ expect((await callReviewReadTool('review_read_file', { path: target }, work, grants)).success).toBe(false);+ });+ it('bounds directory pages and permits continuing past excluded entries', async () => {+ await Promise.all(Array.from({ length: 205 }, (_, i) => fs.writeFile(path.join(work, `file-${i}.txt`), '')));+ const first = text(await callReviewReadTool('review_list_directory', { path: '.' }, work, grants));+ const second = text(await callReviewReadTool('review_list_directory', { path: '.', offset: first.nextOffset }, work, grants));+ expect(first.entries).toHaveLength(200);+ expect(second.entries).toHaveLength(5);+ expect(second.nextOffset).toBeNull();+ });+ it('rejects unsupported tools, malformed arguments, binary and oversized text', async () => {+ await fs.writeFile(path.join(work, 'binary'), Buffer.from([0, 1, 2]));+ await fs.writeFile(path.join(work, 'large'), Buffer.alloc(2 * 1024 * 1024 + 1, 65));+ await fs.writeFile(path.join(work, 'long-line'), 'a'.repeat(70_000));+ for (const file of ['binary', 'large', 'long-line']) {+ expect((await callReviewReadTool('review_read_file', { path: file }, work, grants)).success).toBe(false);+ }+ for (const args of [null, [], {}, { path: '.', offset: -1 }, { path: '.', offset: 0.5 }, { path: '.', command: 'anything' }]) {+ expect((await callReviewReadTool('review_list_directory', args, work, grants)).success).toBe(false);+ }+ expect((await callReviewReadTool('exec_command', { path: '.' }, work, grants)).success).toBe(false);+ });+ it('returns image bytes only for scoped image evidence', async () => {+ const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC', 'base64');+ await fs.writeFile(path.join(work, 'image.png'), png);+ await fs.writeFile(path.join(work, 'fake.png'), 'not an image');+ const result = await callReviewReadTool('review_view_image', { path: 'image.png' }, work, grants);+ expect(result).toEqual({ success: true, contentItems: [{ type: 'inputImage', imageUrl: `data:image/png;base64,${png.toString('base64')}` }] });+ expect((await callReviewReadTool('review_view_image', { path: 'fake.png' }, work, grants)).success).toBe(false);+ });+ it.skipIf(process.platform !== 'win32')('rejects device paths, UNC paths and alternate streams before filesystem access', async () => {+ const realpath = vi.spyOn(fs, 'realpath');+ for (const target of ['\\\\server\\share\\file', '\\\\?\\C:\\file', 'C:\\work\\file:stream']) {+ expect((await callReviewReadTool('review_read_file', { path: target }, work, grants)).success).toBe(false);+ }+ expect(realpath).not.toHaveBeenCalled();+ });+});diff --git a/packages/maker-core/src/agents/codex/review-read-tools.ts b/packages/maker-core/src/agents/codex/review-read-tools.tsnew file mode 100644index 0000000000..b1e21e9cb6--- /dev/null+++ b/packages/maker-core/src/agents/codex/review-read-tools.ts@@ -0,0 +1,128 @@+import { promises as fs } from 'node:fs';+import path from 'node:path';+import { resolveReviewReadPath, type ReviewReadGrant } from '../shared/review-read-scope.js';+import type { DynamicToolCallResponse, DynamicToolSpec } from './app-server/protocol.js';++const MAX_FILE_BYTES = 2 * 1024 * 1024;+const MAX_IMAGE_BYTES = 10 * 1024 * 1024;+const PAGE_SIZE = 200;+const DENIED = 'Review refused this read: invalid arguments, unavailable file, or outside the approved read scope.';++export const REVIEW_READ_TOOLS: DynamicToolSpec[] = [+ {+ type: 'function', name: 'review_read_file',+ description: 'Read a UTF-8 evidence file within the approved Review scope. Returns up to 200 numbered lines (maximum file size 2 MiB). Use offset for the next page. Read applicable AGENTS.md files explicitly with this tool.',+ inputSchema: { type: 'object', properties: { path: { type: 'string' }, offset: { type: 'integer', minimum: 0 } }, required: ['path'], additionalProperties: false },+ },+ {+ type: 'function', name: 'review_list_directory',+ description: 'List an evidence directory within the approved Review scope. Sensitive files and paths outside the scope are excluded. Returns up to 200 entries; use nextOffset for the next page.',+ inputSchema: { type: 'object', properties: { path: { type: 'string' }, offset: { type: 'integer', minimum: 0 } }, required: ['path'], additionalProperties: false },+ },+ {+ type: 'function', name: 'review_view_image',+ description: 'View a PNG, JPEG, GIF or WebP evidence image within the approved Review scope (maximum 10 MiB).',+ inputSchema: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'], additionalProperties: false },+ },+];++export function reviewReadDenied(): DynamicToolCallResponse {+ return { success: false, contentItems: [{ type: 'inputText', text: DENIED }] };+}++/** No subprocess, general host tool, or network capability is available here. */+export async function callReviewReadTool(+ name: string,+ args: unknown,+ workingDir: string,+ grants: readonly ReviewReadGrant[],+): Promise<DynamicToolCallResponse> {+ if (!REVIEW_READ_TOOLS.some((tool) => tool.name === name)) return reviewReadDenied();+ if (!args || typeof args !== 'object' || Array.isArray(args)) return reviewReadDenied();+ const input = args as Record<string, unknown>;+ const offset = input.offset ?? 0;+ if (typeof input.path !== 'string' || !Number.isSafeInteger(offset) || Number(offset) < 0+ || Number(offset) > 1_000_000 || Object.keys(input).some((key) => key !== 'path' && key !== 'offset')) {+ return reviewReadDenied();+ }+ // Reject Windows device paths, network shares and alternate data streams+ // before making any filesystem request (including realpath).+ const localPath = path.resolve(workingDir, input.path);+ if (process.platform === 'win32' && (localPath.startsWith('\\\\') || localPath.slice(2).includes(':'))) {+ return reviewReadDenied();+ }+ try {+ const realPath = await resolveReviewReadPath(input.path, workingDir, grants);+ if (!realPath) return reviewReadDenied();+ const before = await fs.stat(realPath);+ const unchanged = async () => {+ const checked = await resolveReviewReadPath(input.path as string, workingDir, grants);+ if (checked !== realPath) return false;+ const after = await fs.stat(realPath);+ return before.ino !== 0 && before.ino === after.ino && before.dev === after.dev+ && before.nlink === after.nlink && before.mtimeMs === after.mtimeMs;+ };+ if (name === 'review_list_directory') {+ if (!before.isDirectory()) return reviewReadDenied();+ const entries: { name: string; directory: boolean }[] = [];+ let scanned = 0;+ let more = false;+ const directory = await fs.opendir(realPath);+ for await (const entry of directory) {+ if (scanned++ < Number(offset)) continue;+ if (scanned > Number(offset) + PAGE_SIZE) { more = true; break; }+ const resolved = await resolveReviewReadPath(path.join(realPath, entry.name), workingDir, grants);+ if (resolved) entries.push({ name: entry.name, directory: (await fs.stat(resolved)).isDirectory() });+ }+ if (!(await unchanged())) return reviewReadDenied();+ return { success: true, contentItems: [{ type: 'inputText', text: JSON.stringify({ entries, nextOffset: more ? Number(offset) + PAGE_SIZE : null }) }] };+ }+ if (!before.isFile()) return reviewReadDenied();+ const maxBytes = name === 'review_view_image' ? MAX_IMAGE_BYTES : MAX_FILE_BYTES;+ if (before.size > maxBytes) return reviewReadDenied();+ const file = await fs.open(realPath, 'r');+ let data: Buffer;+ try {+ const opened = await file.stat();+ if (!opened.isFile() || !before.ino || opened.ino !== before.ino || opened.dev !== before.dev+ || opened.nlink !== before.nlink || !(await unchanged())) return reviewReadDenied();+ // Bounded descriptor reads, even if another process grows the file.+ const buffer = Buffer.alloc(maxBytes + 1);+ let size = 0;+ while (size < buffer.length) {+ const { bytesRead } = await file.read(buffer, size, buffer.length - size, size);+ if (!bytesRead) break;+ size += bytesRead;+ }+ if (size > maxBytes || !(await unchanged())) return reviewReadDenied();+ data = buffer.subarray(0, size);+ } finally {+ await file.close();+ }+ if (name === 'review_view_image') {+ const mime = data.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) ? 'image/png'+ : data[0] === 255 && data[1] === 216 && data[2] === 255 ? 'image/jpeg'+ : /^GIF8[79]a$/.test(data.subarray(0, 6).toString('ascii')) ? 'image/gif'+ : data.subarray(0, 4).toString() === 'RIFF' && data.subarray(8, 12).toString() === 'WEBP' ? 'image/webp' : null;+ if (!mime) return reviewReadDenied();+ return { success: true, contentItems: [{ type: 'inputImage', imageUrl: `data:${mime};base64,${data.toString('base64')}` }] };+ }+ if (data.includes(0)) return reviewReadDenied();+ const lines = data.toString('utf8').split('\n');+ const start = Number(offset);+ let text = '';+ let end = start;+ for (; end < Math.min(lines.length, start + PAGE_SIZE); end++) {+ // Bound single-line/minified files too. Never silently truncate evidence.+ if (text.length + lines[end].length > 64 * 1024) {+ if (end === start) return reviewReadDenied();+ break;+ }+ text += `${end + 1}: ${lines[end]}\n`;+ }+ return { success: true, contentItems: [{ type: 'inputText', text: JSON.stringify({ text, nextOffset: end < lines.length ? end : null }) }] };+ } catch {+ // Do not disclose filesystem errors or paths outside the read scope.+ return reviewReadDenied();+ }+}diff --git a/packages/maker-core/src/agents/codex/review-start.native.test.ts b/packages/maker-core/src/agents/codex/review-start.native.test.tsnew file mode 100644index 0000000000..93f049c50c--- /dev/null+++ b/packages/maker-core/src/agents/codex/review-start.native.test.ts@@ -0,0 +1,158 @@+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { createServer } from 'node:http';+import type { AddressInfo } from 'node:net';+import { describe, expect, it } from 'vitest';+import type { Logger } from '../../interfaces/logger.js';+import { CodexAgent } from './index.js';++// Explicit opt-in; never load the user's Codex home or credentials.+const binaryPath = process.env.CINDY_CODEX_TEST_BINARY;+const legacyBinaryPath = process.env.CINDY_CODEX_LEGACY_TEST_BINARY;+const logger: Logger = {+ trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {},+ child: () => logger,+};++describe.skipIf(!binaryPath || process.platform !== 'win32')('Windows Codex Review with real app-server', () => {+ it.each([+ { binary: binaryPath!, configuredMemory: false, compatible: true },+ { binary: binaryPath!, configuredMemory: true, compatible: true },+ ...(legacyBinaryPath ? [{ binary: legacyBinaryPath, configuredMemory: false, compatible: false }] : []),+ ])('enforces scoped reads (configured memory: $configuredMemory, compatible runtime: $compatible)', async ({ binary, configuredMemory, compatible }) => {+ const root = await mkdtemp(path.join(tmpdir(), 'cindy-review-start-'));+ const home = path.join(root, 'codex');+ const workingDir = path.join(root, 'work');+ const model = configuredMemory ? 'gpt-5.4' : 'fixture-model';+ await mkdir(home);+ await mkdir(workingDir);+ await writeFile(path.join(workingDir, 'evidence.md'), 'REVIEW_EVIDENCE');+ await writeFile(path.join(workingDir, 'AGENTS.md'), 'REVIEW_PROJECT_RULE');+ await writeFile(path.join(workingDir, '.env'), 'SYNTHETIC_SECRET');+ await writeFile(path.join(root, 'private.md'), 'SYNTHETIC_PRIVATE');+ const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC', 'base64');+ await writeFile(path.join(workingDir, 'evidence.png'), png);+ await writeFile(path.join(root, 'private.png'), png);+ const requests: { tools: { name: string }[]; input: { type: string; call_id?: string; output?: unknown }[] }[] = [];+ // The scripted local provider exercises tool round trips without a real+ // model, cloud credentials, administrator setup, or the user's Codex home.+ const calls = [+ ['review_read_file', { path: 'evidence.md' }],+ ['review_list_directory', { path: '.' }],+ ['review_read_file', { path: '.env' }],+ ['review_read_file', { path: '../private.md' }],+ ['review_read_file', { path: 'AGENTS.md' }],+ ['review_view_image', { path: 'evidence.png' }],+ // Also send unadvertised native tools: they must not execute.+ ['shell_command', { command: 'echo unsafe > mutated.txt' }],+ ['view_image', { path: path.join(root, 'private.png') }],+ ['apply_patch', { patch: '*** Begin Patch\n*** Add File: mutated.txt\n+unsafe\n*** End Patch' }],+ ] as const;+ const server = createServer(async (req, res) => {+ const chunks = [];+ for await (const chunk of req) chunks.push(chunk);+ requests.push(JSON.parse(Buffer.concat(chunks).toString()));+ const step = requests.length - 1;+ const call = calls[step];+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'close' });+ const events = [+ { type: 'response.created', response: { id: 'response-fixture' } },+ { type: 'response.output_item.done', item: call+ ? call[0] === 'apply_patch'+ ? { type: 'custom_tool_call', id: `item-${step}`, call_id: `call-${step}`, name: call[0], input: call[1].patch }+ : { type: 'function_call', id: `item-${step}`, call_id: `call-${step}`, name: call[0], arguments: JSON.stringify(call[1]) }+ : { type: 'message', role: 'assistant', id: 'message-fixture', content: [{ type: 'output_text', text: 'fixture complete' }] } },+ { type: 'response.completed', response: { id: 'response-fixture', usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 } } },+ ];+ res.end(events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(''));+ });+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));+ const endpoint = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+ await writeFile(path.join(home, 'config.toml'), [+ `model="${model}"`,+ 'model_provider="fixture"',+ 'cli_auth_credentials_store="ephemeral"',+ 'check_for_update_on_startup=false',+ // Review must override user-enabled execution/visual capabilities.+ '[features]', 'shell_tool=true', 'unified_exec=true', 'view_image=true',+ 'code_mode=true', 'code_mode_only=true', 'multi_agent_v2=true',+ '[analytics]', 'enabled=false',+ // A missing transport is the production regression. The configured case+ // also exercises Review's existing transport-aware isolation path.+ ...(configuredMemory ? [+ '[mcp_servers.cindy_memory]', 'command="unused-memory-server"', 'enabled=false',+ ] : []),+ '[model_providers.fixture]', 'name="Fixture"',+ `base_url="${endpoint}"`, 'wire_api="responses"',+ 'requires_openai_auth=false', 'request_max_retries=0',+ ].join('\n'));+ const agent = new CodexAgent({+ binaryPath: binary, logger, runtimeConfig: {},+ resolveCodexLocalAuthPolicy: () => 'isolated',+ prepareCodexExtraSpawnConfig: async () => ({+ extraArgs: [], extraEnv: {}, codexProxyActive: true,+ }),+ auth: {+ getState: async () => ({ authenticated: true }),+ triggerLogin: async () => ({ authenticated: true }),+ logout: async () => {},+ getAuthEnv: async () => ({+ HOME: root, USERPROFILE: root, APPDATA: root, LOCALAPPDATA: root,+ CODEX_HOME: home, TMPDIR: root,+ OPENAI_API_KEY: '', CODEX_API_KEY: '',+ HTTP_PROXY: 'http://127.0.0.1:1', HTTPS_PROXY: 'http://127.0.0.1:1',+ ALL_PROXY: 'http://127.0.0.1:1', NO_PROXY: '127.0.0.1,localhost',+ }),+ },+ });+ try {+ const started = agent.startSession({+ sessionId: `review-${configuredMemory}`, providerId: 'cprov-fixture',+ model, workingDir, reviewMode: true,+ makerMemoryEnabled: false,+ });+ if (!compatible) {+ await expect(started).rejects.toThrow('Windows Cindy Review requires Codex app-server 0.156.0');+ expect(requests).toHaveLength(0);+ return;+ }+ const handle = await started;+ expect(handle.id).toBeTruthy();+ expect(handle.codexHostKey).toContain('local-review:');+ expect(handle.getPlanMode?.()).toBe(false);+ const events = (async () => {+ for await (const event of handle.events()) {+ if (event.type === 'error') throw new Error(JSON.stringify(event));+ if (event.type === 'done') return;+ }+ })();+ await handle.send({ type: 'user', content: 'Review the fixture' }, { throwOnStartFailure: true });+ await events;+ expect(requests).toHaveLength(calls.length + 1);+ expect(requests[0].tools.map((tool) => tool.name).sort()).toEqual([+ ...(configuredMemory ? ['apply_patch'] : []),+ 'request_user_input', 'review_list_directory', 'review_read_file', 'review_view_image',+ ]);+ const output = (step: number) => JSON.stringify(requests[step + 1].input.find((item) => item.type.endsWith('_call_output') && item.call_id === `call-${step}`)?.output);+ expect(output(0)).toContain('REVIEW_EVIDENCE');+ expect(output(1)).toContain('evidence.md');+ expect(output(1)).not.toContain('.env');+ expect(output(2)).toContain('Review refused');+ expect(output(3)).toContain('Review refused');+ expect(output(4)).toContain('REVIEW_PROJECT_RULE');+ expect(output(5)).toContain('data:image/png;base64,');+ expect(output(6)).toMatch(/unknown|unsupported|not found/i);+ expect(output(7)).toMatch(/unknown|unsupported|not found/i);+ expect(output(8)).toMatch(/unknown|unsupported|reject|denied|not permitted/i);+ expect(JSON.stringify(requests)).not.toMatch(/SYNTHETIC_SECRET|SYNTHETIC_PRIVATE/);+ expect(await readFile(path.join(workingDir, 'evidence.md'), 'utf8')).toBe('REVIEW_EVIDENCE');+ await expect(readFile(path.join(workingDir, 'mutated.txt'))).rejects.toMatchObject({ code: 'ENOENT' });+ await handle.close();+ } finally {+ await agent.dispose();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });+ }+ }, 30_000);+});