Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(codex): use bundled CLI inside task shells
fmfsaisai12641d47092e
diff --git a/apps/desktop/src/main/agent-binaries/__tests__/codex-cli-launcher.test.ts b/apps/desktop/src/main/agent-binaries/__tests__/codex-cli-launcher.test.tsnew file mode 100644index 0000000000..7f78efc5f8--- /dev/null+++ b/apps/desktop/src/main/agent-binaries/__tests__/codex-cli-launcher.test.ts@@ -0,0 +1,89 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++const mocks = vi.hoisted(() => ({ warn: vi.fn() }));+vi.mock('../../logger.js', () => ({ createLogger: () => ({ warn: mocks.warn }) }));++import { codexPackagePathPrepends, ensureCodexCliLauncher } from '../codex-cli-launcher.js';++// 测试价值:ensureCodexCliLauncher 的文件结果与 Windows PATH 选择;防止 shell+// 误用旧 Codex。现有下载测试不覆盖新增入口。最小输入:包已有 bin/codex、无入口。+// tier: unit;唯一临时目录和文件 I/O,不启动真实 CLI/Electron,不访问用户数据。+const roots: string[] = [];+afterEach(() => {+ vi.restoreAllMocks();+ mocks.warn.mockClear();+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });+});++function fixture() {+ const userDataPath = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-cli-launcher-'));+ roots.push(userDataPath);+ const packageRoot = path.join(userDataPath, 'codex-package', '0.159.2');+ fs.mkdirSync(path.join(packageRoot, 'bin'), { recursive: true });+ fs.mkdirSync(path.join(packageRoot, 'codex-path'));+ fs.writeFileSync(path.join(packageRoot, 'codex-package.json'), JSON.stringify({ pathDir: 'codex-path' }));+ const binaryPath = path.join(packageRoot, 'bin', 'codex');+ fs.writeFileSync(binaryPath, 'fake binary');+ return {+ packageRoot, binaryPath,+ destination: path.join(packageRoot, 'codex-path', 'codex'),+ options: { userDataPath, isPackaged: true, platform: 'darwin' as NodeJS.Platform },+ };+}++describe('packaged Codex shell launcher', () => {+ it('writes once, updates marked scripts, and preserves an upstream-owned executable', () => {+ const { binaryPath, destination, options } = fixture();+ ensureCodexCliLauncher(binaryPath, options);+ const content = fs.readFileSync(destination, 'utf8');+ expect(content).toContain('../bin/codex');+ if (process.platform !== 'win32') expect(fs.statSync(destination).mode & 0o777).toBe(0o755);+ const oldTime = new Date('2000-01-01T00:00:00Z');+ fs.utimesSync(destination, oldTime, oldTime);+ ensureCodexCliLauncher(binaryPath, options);+ expect(fs.statSync(destination).mtimeMs).toBe(oldTime.getTime());++ fs.writeFileSync(destination, content.replace('exec ', '# old\nexec '));+ ensureCodexCliLauncher(binaryPath, options);+ expect(fs.readFileSync(destination, 'utf8')).toBe(content);+ fs.writeFileSync(destination, 'upstream executable');+ ensureCodexCliLauncher(binaryPath, options);+ expect(fs.readFileSync(destination, 'utf8')).toBe('upstream executable');+ });++ it.each(['development', 'windows', 'outside-userData', 'single-binary', 'missing-manifest', 'wrong-pathDir', 'missing-pathDir'])+ ('does not write for %s', (scenario) => {+ const { binaryPath, destination, packageRoot, options } = fixture();+ let selectedBinary = binaryPath;+ if (scenario === 'development') options.isPackaged = false;+ if (scenario === 'windows') options.platform = 'win32';+ if (scenario === 'outside-userData') options.userDataPath = path.join(options.userDataPath, 'other');+ if (scenario === 'single-binary') selectedBinary = path.join(packageRoot, 'codex');+ if (scenario === 'missing-manifest') fs.rmSync(path.join(packageRoot, 'codex-package.json'));+ if (scenario === 'wrong-pathDir') fs.writeFileSync(path.join(packageRoot, 'codex-package.json'), '{"pathDir":"other"}');+ if (scenario === 'missing-pathDir') fs.rmdirSync(path.dirname(destination));+ expect(() => ensureCodexCliLauncher(selectedBinary, options)).not.toThrow();+ expect(fs.existsSync(destination)).toBe(false);+ });++ it('logs write failure and cleans the temporary file without blocking startup', () => {+ const { binaryPath, destination, options } = fixture();+ vi.spyOn(fs, 'renameSync').mockImplementation(() => { throw new Error('write denied'); });+ expect(() => ensureCodexCliLauncher(binaryPath, options)).not.toThrow();+ expect(mocks.warn).toHaveBeenCalledOnce();+ expect(fs.readdirSync(path.dirname(destination))).toEqual([]);+ });+});++it('prepends only a Windows Codex package bin directory, never a system directory', () => {+ const root = path.win32.join('C:\\', 'Cindy Data', 'codex-package', '0.159.2');+ vi.spyOn(fs, 'existsSync').mockImplementation((candidate) => candidate === path.win32.join(root, 'codex-package.json'));+ const binaryPath = path.win32.join(root, 'bin', 'codex.exe');+ expect(codexPackagePathPrepends(binaryPath, 'win32')).toEqual([path.win32.join(root, 'bin')]);+ expect(codexPackagePathPrepends(path.win32.join('C:\\', 'Windows', 'codex.exe'), 'win32')).toEqual([]);+ expect(codexPackagePathPrepends(path.win32.join('C:\\', 'System', 'bin', 'codex.exe'), 'win32')).toEqual([]);+ expect(codexPackagePathPrepends(binaryPath, 'darwin')).toEqual([]);+});diff --git a/apps/desktop/src/main/agent-binaries/codex-cli-launcher.ts b/apps/desktop/src/main/agent-binaries/codex-cli-launcher.tsnew file mode 100644index 0000000000..de223d83e9--- /dev/null+++ b/apps/desktop/src/main/agent-binaries/codex-cli-launcher.ts@@ -0,0 +1,57 @@+import fs from 'node:fs';+import path from 'node:path';+import { randomUUID } from 'node:crypto';+import { app } from 'electron';++import launcher from '../../../../../tools/codex-package/codex-path-launcher.sh?raw';+import { createLogger } from '../logger.js';++const log = createLogger('agent-binaries/codex-cli-launcher');+const managedMarker = launcher.split('\n')[1];++/** Windows keeps the inherited PATH; only prepend bin for an actual Codex package. */+export function codexPackagePathPrepends(binaryPath: string | undefined, platform: NodeJS.Platform): string[] {+ if (platform !== 'win32' || !binaryPath) return [];+ const paths = path.win32;+ const binDir = paths.dirname(binaryPath);+ if (paths.basename(binaryPath) !== 'codex.exe' || paths.basename(binDir) !== 'bin') return [];+ return fs.existsSync(paths.join(paths.dirname(binDir), 'codex-package.json')) ? [binDir] : [];+}++/**+ * Codex restores the login shell PATH on Unix, then prepends its own codex-path.+ * Patch only the selected packaged runtime. Dev installs own their strict manifest.+ * Failure must never prevent an otherwise usable Codex runtime from starting.+ */+export function ensureCodexCliLauncher(+ binaryPath: string,+ { isPackaged = app.isPackaged, platform = process.platform, userDataPath = app.getPath('userData') } = {},+): void {+ if (!isPackaged || platform === 'win32') return;+ let tempPath: string | undefined;+ try {+ const packageRoot = path.dirname(path.dirname(binaryPath));+ if (path.basename(binaryPath) !== 'codex'+ || path.basename(path.dirname(binaryPath)) !== 'bin'+ || path.dirname(packageRoot) !== path.resolve(userDataPath, 'codex-package')) return;+ const manifest = JSON.parse(fs.readFileSync(path.join(packageRoot, 'codex-package.json'), 'utf8'));+ if (manifest.pathDir !== 'codex-path') return;+ const pathDir = path.join(packageRoot, 'codex-path');+ if (!fs.statSync(pathDir).isDirectory()) return;+ const destination = path.join(pathDir, 'codex');+ if (fs.existsSync(destination)) {+ const existing = fs.readFileSync(destination, 'utf8');+ if (existing === launcher || existing.split(/\r?\n/)[1] !== managedMarker) return;+ }+ tempPath = `${destination}.launcher-${randomUUID()}`;+ fs.writeFileSync(tempPath, launcher, { encoding: 'utf8', mode: 0o755 });+ fs.chmodSync(tempPath, 0o755);+ fs.renameSync(tempPath, destination);+ } catch (error) {+ log.warn('Could not prepare bundled Codex shell launcher', { error });+ } finally {+ if (tempPath) {+ try { fs.rmSync(tempPath, { force: true }); } catch { /* best effort */ }+ }+ }+}diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex 7c245157a8..f5b534d929 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -7,6 +7,7 @@ import { createCompanionImportProvider } from '../bot-import/importProvider.js';import { createCompanionConnectionsProvider } from '../bot-import/connectionProvider.js';import { resolveCompanionRuntimeEnvironment } from '../bot-import/runtime.js';import { registerCodexTextOnlyPolicy } from './codex-text-only-policy.js';+import { ensureCodexCliLauncher } from '../agent-binaries/codex-cli-launcher.js';import { readDisabledSkillPaths } from '../skillhub/activationPreferences';import { cindyMakeManager } from '../cindy-make/manager.js';import { makeSourceRoot } from '../cindy-make/sourcePaths.js';@@ -1012,6 +1013,7 @@ export function getMaker(): Maker {'getMaker: Codex binary not provisioned (bootstrap must run agent-binaries.prepare("codex") before getMaker)',);}+ ensureCodexCliLauncher(codexPath);// bundled ripgrep 检查与上面 claude/codex 二进制同层:真正的启动期 fail-fast// 在 splash check-environment(Phase 2.5,缺 rg 时 splash 进失败态可重试);// 这里是防御性断言 —— 走到本函数说明 bootstrap 已完成环境检查,缺 rg 即顺序diff --git a/apps/desktop/src/main/maker-host/runtime-configs.ts b/apps/desktop/src/main/maker-host/runtime-configs.tsindex 2777eaa5fc..0571037be4 100644--- a/apps/desktop/src/main/maker-host/runtime-configs.ts+++ b/apps/desktop/src/main/maker-host/runtime-configs.ts@@ -9,6 +9,8 @@ import type { AgentRuntimeConfig } from '@cindy/maker-core';import { app } from 'electron';import fs from 'node:fs';import path from 'node:path';+import { getCachedBinaryStatus } from '../agent-binaries/index.js';+import { codexPackagePathPrepends } from '../agent-binaries/codex-cli-launcher.js';import {isModelDisabled,@@ -316,7 +318,12 @@ export const desktopCodexRuntimeConfig: AgentRuntimeConfig = {// fail-fast 由 maker-host 启动期的 ensureBundledRipgrepReady() 承担,此处 getter// 在 env-builder 每次 codex spawn 时求值(结果已 memoize)。get pathPrepends() {- return [bundledRipgrepDir()];+ return [+ bundledRipgrepDir(),+ ...(process.platform === 'win32'+ ? codexPackagePathPrepends(getCachedBinaryStatus('codex').binaryPath, process.platform)+ : []),+ ];},userDataPath: app.getPath('userData'),get memoryEnabled() {diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.mdindex 292403d3a7..7171897018 100644--- a/docs/dev-rules/credentials-and-local-storage.md+++ b/docs/dev-rules/credentials-and-local-storage.md@@ -196,6 +196,7 @@ refresh 与 relay 自救节流。在途 refresh 尚未返回时收到的恢复| 数据性质 | 正确位置 || ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Codex 包内 shell 入口 | `<userData>/codex-package/<版本>/codex-path/codex`,打包版 macOS/Linux 在 `getMaker()` 选定实际运行的 Codex 后由主进程原子写入,转发到同包的 `bin/codex`;只更新带 Cindy 标记的旧脚本,不覆盖外来文件。随旧版本目录整体删除,不含凭证。实现见 `agent-binaries/codex-cli-launcher.ts` || Cindy 管理的持久数据 | Desktop 使用 `app.getPath('userData')`,共享 package 由宿主注入等价根目录 || 浏览器用户配方 | `userData/browser-recipes/<site>/recipes/<id 的 SHA-256>.json`,每站多个流程,原子替换;兼容旧 `recipe.json`,新文件优先。只保存配方定义及 active/suspended 状态,不保存试跑的 inputs/页面返回值;禁止写入凭据,业务变动值用 inputs。试跑凭证与单轮修复预算只在 MCP 会话内存中,暂停状态跨重启保留。 || 本机应用 Agent 授权 | `owners/<owner-key>/local-agent/grants.json`,仅含令牌 SHA-256、自报应用资料、账号范围和按授权归属的原生恢复绑定,不存令牌明文、供应商凭据或消息。复用原子写入与恢复 helper;profile 根 `local-agent/host.lock` 复用跨进程锁,保证一个发现端点和写入者。开发连接码从当前服务内存按需生成,不新增公共实例登记或短码映射文件。临时输入与新授权的 Codex 运行历史在同一 owner 下的 `local-agent/clients/<grant-hash>/`;撤权同时关闭执行及工具入口,不允许跨授权恢复。协议与旧版兼容见 [本机应用接入](../local-agent-api.md) |diff --git a/docs/dev-rules/environment-setup.md b/docs/dev-rules/environment-setup.mdindex 2676e32e60..87f3a7398d 100644--- a/docs/dev-rules/environment-setup.md+++ b/docs/dev-rules/environment-setup.md@@ -30,6 +30,10 @@ pnpm install自动补下载,仍无法准备才会中止 dev 启动并给出明确错误。正常情况下无需手动安装二进制。+macOS/Linux 的 `apps/codex-package-bin/<平台>/codex-path/codex` 由上述检查流程在+完整包校验通过后补入,并更新目录清单;运行中的开发版不改包目录。脚本转发到同包的+`bin/codex`,使任务里的 shell 使用与任务相同的版本;已有的非 Cindy 脚本不会被覆盖。+postinstall 最后还会按 Electron `install.js` 的语义复核 `node_modules/electron/dist`,缺失或版本不符就补装(`node scripts/ensure-deps.mjs --electron-binary`;设置了`ELECTRON_SKIP_BINARY_DOWNLOAD` 或 `ELECTRON_OVERRIDE_DIST_PATH` 时跳过)。原因:pnpm 的diff --git a/packages/maker-core/src/interfaces/runtime-config.ts b/packages/maker-core/src/interfaces/runtime-config.tsindex 48bc285ed2..eb7e519c9b 100644--- a/packages/maker-core/src/interfaces/runtime-config.ts+++ b/packages/maker-core/src/interfaces/runtime-config.ts@@ -131,6 +131,8 @@ export interface AgentRuntimeConfig {/*** Host-managed executable directories to prepend to agent subprocess PATH.+ * On macOS/Linux, Codex restores the login shell environment, moving these after+ * the user's PATH; only the Codex package's own codex-path stays at the front.** Only agents whose executable lookup is safe for PATH-based discovery should consume this.* PI intentionally does not: Windows may resolve an executable from cwd before PATH.diff --git a/scripts/__tests__/ensure-agent-binaries.test.mjs b/scripts/__tests__/ensure-agent-binaries.test.mjsindex 4ee25e523a..688179ccf5 100644--- a/scripts/__tests__/ensure-agent-binaries.test.mjs+++ b/scripts/__tests__/ensure-agent-binaries.test.mjs@@ -13,6 +13,7 @@ import { execFileSync } from 'node:child_process';import {binaryRelativePathFor,binFileFor,+ ensureCodexPackageLauncher,isValidBinary,isValidDirDist,listSiblingWorktreeRoots,@@ -25,6 +26,57 @@ import {} from '../ensure-agent-binaries.mjs';import { verifyDirDistManifest, writeDirDistManifest } from '../../tools/shared/dir-dist-manifest.mjs';+// 测试价值:生产 ensureCodexPackageLauncher 为已验证包补入口并保持清单有效;+// 回归 Codex shell 被旧系统 CLI 抢占。原覆盖只验证下载/复用,未覆盖包内入口。+// 最小输入是有效但缺入口的包;node unit,POSIX 另执行一次脚本检查 argv 不变。+test('Codex launcher preserves the manifest, updates managed files and leaves upstream files alone', (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'codex launcher space-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ fs.mkdirSync(path.join(root, 'bin'));+ fs.mkdirSync(path.join(root, 'codex-path'));+ fs.writeFileSync(path.join(root, 'bin', 'codex'), '#!/bin/sh\nprintf \'%s\\0\' "$@"\n', { mode: 0o755 });+ fs.writeFileSync(path.join(root, 'codex-package.json'), JSON.stringify({ pathDir: 'codex-path' }));+ writeDirDistManifest(root);+ const destination = path.join(root, 'codex-path', 'codex');+ const manifestPath = path.join(root, '.manifest');+ assert.equal(verifyDirDistManifest(root), true);+ ensureCodexPackageLauncher(root, 'darwin-arm64');+ assert.equal(verifyDirDistManifest(root), true);+ const content = fs.readFileSync(destination, 'utf8');+ const previous = new Date('2000-01-01T00:00:00Z');+ fs.utimesSync(destination, previous, previous);+ fs.utimesSync(manifestPath, previous, previous);+ ensureCodexPackageLauncher(root, 'darwin-arm64');+ assert.equal(fs.statSync(destination).mtimeMs, previous.getTime());+ assert.equal(fs.statSync(manifestPath).mtimeMs, previous.getTime());+ if (process.platform !== 'win32') {+ assert.equal(fs.statSync(destination).mode & 0o777, 0o755);+ const args = ['a b', '"quoted"', "it's", '', '-n', '$HOME', '%^!'];+ assert.deepEqual(execFileSync(destination, args), Buffer.from(args.join('\0') + '\0'));+ }+ fs.writeFileSync(destination, content.replace('exec ', '# old\nexec '));+ writeDirDistManifest(root);+ ensureCodexPackageLauncher(root, 'linux-x64');+ assert.equal(fs.readFileSync(destination, 'utf8'), content);+ assert.equal(verifyDirDistManifest(root), true);+ fs.writeFileSync(destination, 'upstream executable');+ writeDirDistManifest(root);+ ensureCodexPackageLauncher(root, 'linux-x64');+ assert.equal(fs.readFileSync(destination, 'utf8'), 'upstream executable');+ assert.equal(verifyDirDistManifest(root), true);+});++test('Windows Codex targets never get a POSIX launcher, including cross-platform preparation', (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-launcher-win-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ fs.mkdirSync(path.join(root, 'codex-path'));+ fs.writeFileSync(path.join(root, 'codex-package.json'), '{}');+ writeDirDistManifest(root);+ ensureCodexPackageLauncher(root, 'win32-x64');+ assert.deepEqual(fs.readdirSync(path.join(root, 'codex-path')), []);+ assert.equal(verifyDirDistManifest(root), true);+});+test('directory distributions never use the single-binary CDN fallback', () => {assert.equal(supportsCdnFallback('pi'), false);assert.equal(supportsCdnFallback('codex'), false);diff --git a/scripts/ensure-agent-binaries.mjs b/scripts/ensure-agent-binaries.mjsindex 3abd30356a..5f3ab066e1 100644--- a/scripts/ensure-agent-binaries.mjs+++ b/scripts/ensure-agent-binaries.mjs@@ -18,10 +18,11 @@import fs from 'node:fs';import path from 'node:path';import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';import { fileURLToPath, pathToFileURL } from 'node:url';import { downloadFromCdn } from './agent-binary-cdn-fallback.mjs';-import { verifyDirDistManifest } from '../tools/shared/dir-dist-manifest.mjs';+import { verifyDirDistManifest, writeDirDistManifest } from '../tools/shared/dir-dist-manifest.mjs';const ROOT = path.resolve(fileURLToPath(new URL('..', import.meta.url)));const LFS_POINTER_HEADER = 'version https://git-lfs.github.com/spec/v1';@@ -271,6 +272,26 @@ export function tryReuseDirDistFromSiblingWorktree({return null;}+/** Called only after package validation: retain the strict manifest after adding our launcher. */+export function ensureCodexPackageLauncher(packageDir, platformKey) {+ if (platformKey.startsWith('win32')) return;+ const launcher = fs.readFileSync(new URL('../tools/codex-package/codex-path-launcher.sh', import.meta.url), 'utf8');+ const destination = path.join(packageDir, 'codex-path', 'codex');+ if (fs.existsSync(destination)) {+ const existing = fs.readFileSync(destination, 'utf8');+ if (existing === launcher || existing.split(/\r?\n/)[1] !== launcher.split('\n')[1]) return;+ }+ const tempPath = `${destination}.launcher-${randomUUID()}`;+ try {+ fs.writeFileSync(tempPath, launcher, { encoding: 'utf8', mode: 0o755 });+ fs.chmodSync(tempPath, 0o755);+ fs.renameSync(tempPath, destination);+ } finally {+ fs.rmSync(tempPath, { force: true });+ }+ writeDirDistManifest(packageDir);+}+/** 确保固定版本的运行包就位,返回主执行文件路径。 */export async function ensureBinary(kind, platformKey = currentPlatformKey(), { force = false } = {}) {const cfg = KINDS[kind];@@ -299,6 +320,7 @@ export async function ensureBinary(kind, platformKey = currentPlatformKey(), { f? isValidDirDist(binDirPath, binPath, requiredDirDistFilesFor(cfg, platformKey)): isValidBinary(binPath);if (!force && presentAndValid && readInstalledVersion(markerPath) === version) {+ if (kind === 'codex') ensureCodexPackageLauncher(binDirPath, platformKey);log(`${kind} ${platformKey}: already present @ ${version}, skip`);return binPath;}@@ -373,6 +395,7 @@ export async function ensureBinary(kind, platformKey = currentPlatformKey(), { f`The previous binary may be locked (app running); close it and retry, or run "pnpm update:${updateScript}".`,);}+ if (kind === 'codex') ensureCodexPackageLauncher(binDirPath, platformKey);return binPath;}diff --git a/tools/codex-package/codex-path-launcher.sh b/tools/codex-package/codex-path-launcher.shnew file mode 100644index 0000000000..9ef93c190a--- /dev/null+++ b/tools/codex-package/codex-path-launcher.sh@@ -0,0 +1,3 @@+#!/bin/sh+# cindy-managed: codex-path launcher v1+exec "$(dirname -- "$0")/../bin/codex" "$@"