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。

feat(desktop): use Codex package in development

Lizi635977dd9c5f
diff --git a/.gitignore b/.gitignore
index 24b585b2c1..30cde6c9d7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -47,6 +47,7 @@ apps/desktop/resources/cindy-updater.exe
# 实体文件按 tools/<kind>/latest.json 的 pin 下载,不进 Git/LFS。
apps/claude-code-bin/
apps/codex-bin/
+apps/codex-package-bin/
apps/pi-bin/
apps/ripgrep-bin/
# Android platform-tools 的二进制同理:Windows 打包前按 source.properties 的 pin
@@ -59,6 +60,7 @@ apps/android-platform-tools-bin/win32-x64/AdbWinApi.dll
apps/android-platform-tools-bin/win32-x64/AdbWinUsbApi.dll
tools/claude/updates/
tools/codex/updates/
+tools/codex-package/updates/
tools/ripgrep/updates/
tools/pi/updates/
diff --git a/apps/desktop/src/main/__tests__/agentBinaryLinuxPrepare.test.ts b/apps/desktop/src/main/__tests__/agentBinaryLinuxPrepare.test.ts
index b1f8aa020a..38b8b1b58e 100644
--- a/apps/desktop/src/main/__tests__/agentBinaryLinuxPrepare.test.ts
+++ b/apps/desktop/src/main/__tests__/agentBinaryLinuxPrepare.test.ts
@@ -1,4 +1,5 @@
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import path from 'node:path';
// getBase() 按 kind 缓存 provisioner 实例:全部测试共享同一个 cdndProvisioner,
// 每测试重配它的行为(而不是 mockReturnValueOnce 换实例——缓存会让新实例永远不被使用)。
@@ -6,6 +7,7 @@ const {
appMock,
cdndProvisioner,
createBinaryProvisioner,
+ findDevBinary,
findCachedLinuxRuntimeFallbackBinary,
prepareLinuxRuntimeFallback,
} = vi.hoisted(() => {
@@ -19,6 +21,7 @@ const {
appMock: { isPackaged: true, getPath: vi.fn(() => '/tmp/xdt-userdata') },
cdndProvisioner,
createBinaryProvisioner: vi.fn(() => cdndProvisioner),
+ findDevBinary: vi.fn((): string | null => null),
findCachedLinuxRuntimeFallbackBinary: vi.fn((): string | null => null),
prepareLinuxRuntimeFallback: vi.fn(),
};
@@ -29,7 +32,7 @@ vi.mock('electron', () => ({
BrowserWindow: { getAllWindows: () => [] },
}));
vi.mock('../agent-binaries/factory.js', () => ({ createBinaryProvisioner }));
-vi.mock('../agent-binaries/dev-fallback.js', () => ({ findDevBinary: vi.fn(() => null) }));
+vi.mock('../agent-binaries/dev-fallback.js', () => ({ findDevBinary }));
vi.mock('../agent-binaries/linux-runtime-fallback.js', () => ({
findCachedLinuxRuntimeFallbackBinary,
prepareLinuxRuntimeFallback,
@@ -76,6 +79,7 @@ beforeEach(async () => {
// mockReturnValue/mockResolvedValue,别 mockReset(会连默认实现一起清掉)。
manifestService.getCachedManifest.mockReturnValue(null);
manifestService.fetchManifest.mockResolvedValue(null);
+ findDevBinary.mockReset().mockReturnValue(null);
findCachedLinuxRuntimeFallbackBinary.mockReturnValue(null);
prepareLinuxRuntimeFallback.mockResolvedValue({
ready: true,
@@ -85,6 +89,39 @@ beforeEach(async () => {
});
});
+describe('dev Codex package selection', () => {
+ it('starts Codex from the complete local package entrypoint', async () => {
+ appMock.isPackaged = false;
+ const expectedPath = '/repo/apps/codex-package-bin/linux-x64/bin/codex';
+ findDevBinary.mockReturnValue(expectedPath);
+
+ await expect(binaries.prepare('codex')).resolves.toEqual({
+ ready: true,
+ path: expectedPath,
+ downloaded: false,
+ });
+ expect(findDevBinary).toHaveBeenCalledWith({
+ vendorBinDir: 'codex-package-bin',
+ binaryName: path.join('bin', 'codex'),
+ });
+ expect(createBinaryProvisioner).not.toHaveBeenCalled();
+ });
+
+ it('keeps the packaged release on the existing Codex manifest and single binary', async () => {
+ cdndProvisioner.prepare.mockResolvedValueOnce({
+ ready: true,
+ binaryPath: '/tmp/xdt-userdata/codex/0.152.0/codex',
+ });
+
+ await expect(binaries.prepare('codex')).resolves.toMatchObject({ ready: true });
+ expect(createBinaryProvisioner).toHaveBeenCalledWith(expect.objectContaining({
+ manifestField: 'codex',
+ installSubdir: 'codex',
+ artifact: { kind: 'gz', binaryName: 'codex' },
+ }));
+ });
+});
+
describe('packaged Linux agent binary prepare', () => {
it('keeps cached status fs-only and does not run runtime verification', () => {
findCachedLinuxRuntimeFallbackBinary.mockReturnValue(
diff --git a/apps/desktop/src/main/__tests__/agentProcessPriority.test.ts b/apps/desktop/src/main/__tests__/agentProcessPriority.test.ts
index 92adcc5bf6..7188a78451 100644
--- a/apps/desktop/src/main/__tests__/agentProcessPriority.test.ts
+++ b/apps/desktop/src/main/__tests__/agentProcessPriority.test.ts
@@ -224,12 +224,14 @@ describe('agent process discovery', () => {
const claudeCmd = `/users/me/library/application support/${userDataDir}/claude-code/2.1.219/claude --setting-sources user`;
const codexCmd = `/users/me/library/application support/${userDataDir}/codex/0.145.0/codex app-server`;
const devClaudeCmd = '/repo/apps/claude-code-bin/darwin-arm64/claude';
+ const devCodexPackageCmd = '/repo/apps/codex-package-bin/darwin-arm64/bin/codex app-server';
const externalClaudeCmd = '/usr/local/bin/claude';
it('classifies bundled claude/codex command lines and rejects external installs', () => {
expect(classifyAgentCommandLine(claudeCmd)).toBe('claude');
expect(classifyAgentCommandLine(codexCmd)).toBe('codex');
expect(classifyAgentCommandLine(devClaudeCmd)).toBe('claude');
+ expect(classifyAgentCommandLine(devCodexPackageCmd)).toBe('codex');
expect(classifyAgentCommandLine(externalClaudeCmd)).toBeNull();
expect(classifyAgentCommandLine('/usr/bin/node some-script.js')).toBeNull();
});
diff --git a/apps/desktop/src/main/agent-binaries/dev-fallback.ts b/apps/desktop/src/main/agent-binaries/dev-fallback.ts
index 07bf4f88d7..402830ac5b 100644
--- a/apps/desktop/src/main/agent-binaries/dev-fallback.ts
+++ b/apps/desktop/src/main/agent-binaries/dev-fallback.ts
@@ -10,9 +10,9 @@ import { app } from 'electron';
import { getPlatformKey } from '../manifestService.js';
export interface DevBinaryConfig {
- /** monorepo apps/ 下的子目录名,例如 'claude-code-bin' / 'codex-bin' */
+ /** monorepo apps/ 下的子目录名,例如 'claude-code-bin' / 'codex-package-bin' */
vendorBinDir: string;
- /** 平台二进制文件名,例如 'claude' / 'claude.exe' / 'codex' / 'codex.exe' */
+ /** 平台目录下的入口相对路径,例如 'claude.exe' / 'bin/codex.exe' */
binaryName: string;
}
diff --git a/apps/desktop/src/main/agent-binaries/index.ts b/apps/desktop/src/main/agent-binaries/index.ts
index a07292bf8f..f13d500da5 100644
--- a/apps/desktop/src/main/agent-binaries/index.ts
+++ b/apps/desktop/src/main/agent-binaries/index.ts
@@ -18,7 +18,7 @@
* 行为逻辑全部共享。新增 agent (e.g. gemini) 时, 一行加 CONFIG 即可。
* - 基础 BinaryProvisioner 实例懒加载 + 缓存 (createBinaryProvisioner 是工厂, 复用同一份 cached manifest)。
* - prepare(kind) 内部:
- * dev: findDevBinary 短路, 缺失硬错 (开发者必须 git lfs pull / pnpm update:codex)
+ * dev: findDevBinary 短路, 缺失硬错 (开发者必须 pnpm update:codex-package)
* Linux packaged: CDN manifest 段优先 (与 mac/win 同链, 国内可达); 资产缺失 /
* 拉取 / 下载失败时静默回落 runtime fallback (PC 已装 CLI / 旧缓存 / userData
* 私有安装 / 带上游 SHA-256 的官方 pin 资产, 不依赖系统 npm/curl/tar)
@@ -170,7 +170,8 @@ interface AgentBinaryConfig {
manifestField: string; // CDN manifest 顶层字段
installSubdir: string; // userData/<installSubdir>/<version>/<binary>
binaryName: string; // 平台相关二进制名
- devBinDir: string; // apps/<devBinDir>/<platform>/ (LFS bundle)
+ devBinDir: string; // apps/<devBinDir>/<platform>/
+ devBinaryName?: string; // dev 可覆盖入口相对路径;prod 仍使用 binaryName
vendorTag: VendorKey; // 'binary-download-progress' IPC payload 的 vendor 字段
artifactKind: 'gz' | 'tar-gz-dir'; // CDN 资产形态(单文件 gz / 整目录 tar.gz)
optionalAsset?: boolean; // true = manifest 缺字段不算"需要下载"(可选 vendor)
@@ -192,7 +193,8 @@ const CONFIG: Record<AgentBinaryKind, AgentBinaryConfig> = {
manifestField: 'codex',
installSubdir: 'codex',
binaryName: process.platform === 'win32' ? 'codex.exe' : 'codex',
- devBinDir: 'codex-bin',
+ devBinDir: 'codex-package-bin',
+ devBinaryName: path.join('bin', process.platform === 'win32' ? 'codex.exe' : 'codex'),
vendorTag: 'codex',
artifactKind: 'gz',
},
@@ -279,9 +281,12 @@ export function getCachedBinaryStatus(kind: AgentBinaryKind): CachedBinaryStatus
}
}
- // dev: 优先查 LFS bundle (apps/<devBinDir>/<platform>/<binary>)
+ // dev:优先查仓库本地 runtime(apps/<devBinDir>/<platform>/<devBinaryName>)。
if (!app.isPackaged) {
- const devPath = findDevBinary({ vendorBinDir: cfg.devBinDir, binaryName: cfg.binaryName });
+ const devPath = findDevBinary({
+ vendorBinDir: cfg.devBinDir,
+ binaryName: cfg.devBinaryName ?? cfg.binaryName,
+ });
if (devPath) return { binaryReady: true, binaryPath: devPath };
}
@@ -326,7 +331,10 @@ export async function prepare(
// ── dev mode 短路 (与老 vendor/{claude,codex}/binaryProvisioner.ts 等价) ──
if (!app.isPackaged) {
- const devPath = findDevBinary({ vendorBinDir: cfg.devBinDir, binaryName: cfg.binaryName });
+ const devPath = findDevBinary({
+ vendorBinDir: cfg.devBinDir,
+ binaryName: cfg.devBinaryName ?? cfg.binaryName,
+ });
if (devPath) {
console.log(`[agent-binaries/${kind}] dev fallback hit: ${devPath}`);
console.warn(`[agent-binaries/${kind}] dev fallback: SHA256 check SKIPPED — for development only`);
diff --git a/apps/desktop/src/main/agent-process-priority.ts b/apps/desktop/src/main/agent-process-priority.ts
index c3f5f21583..f654105e8b 100644
--- a/apps/desktop/src/main/agent-process-priority.ts
+++ b/apps/desktop/src/main/agent-process-priority.ts
@@ -86,7 +86,7 @@ export interface AgentProcessPriorityWatcher {
/**
* codex 二进制路径 marker(与 buildClaudePathMarkers 同构):
- * <userData>/codex/<ver>/ 及 dev checkout 的 apps/codex-bin/。
+ * <userData>/codex/<ver>/ 及 dev checkout 的 apps/codex-package-bin/。
*/
export function buildCodexPathMarkers(dirNames: readonly string[]): string[] {
return dirNames.flatMap((dirName) => {
@@ -130,6 +130,8 @@ const CODEX_MARKERS = [
...buildCodexPathMarkers(allUserDataDirNames(CURRENT_CINDY_REGION)),
...buildLinuxPathMarkers(allUserDataDirNames(CURRENT_CINDY_REGION), 'codex'),
'apps\\codex-bin\\',
+ 'apps\\codex-package-bin\\',
+ 'apps/codex-package-bin/',
'apps/codex-bin/',
];
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexExecFunctionAdapter.e2e.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexExecFunctionAdapter.e2e.test.ts
index ca0a45b143..fc972622fd 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexExecFunctionAdapter.e2e.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexExecFunctionAdapter.e2e.test.ts
@@ -23,13 +23,16 @@ import {
import { createStdioTransport } from '../../../../../../packages/maker-core/src/agents/codex/app-server/stdioTransport.js';
const repoRoot = path.resolve(fileURLToPath(new URL('.', import.meta.url)), '../../../../../..');
-const codexBinary = path.join(
- repoRoot,
- 'apps',
- 'codex-bin',
- `${process.platform}-${process.arch}`,
- process.platform === 'win32' ? 'codex.exe' : 'codex',
-);
+const codexBinary =
+ process.env.CODEX_E2E_BINARY ??
+ path.join(
+ repoRoot,
+ 'apps',
+ 'codex-package-bin',
+ `${process.platform}-${process.arch}`,
+ 'bin',
+ process.platform === 'win32' ? 'codex.exe' : 'codex',
+ );
const codexBoundaryAvailable = existsSync(codexBinary);
const fixtureContents = 'issue-3168-real-command-result';
@@ -72,6 +75,22 @@ function responseCompleted(id: string): unknown {
};
}
+/**
+ * Real Responses upstreams validate an item's id prefix against its type: a `function_call*`
+ * item must carry an id beginning with `fc`. Codex >=0.152 stamps its own `<kind>_<uuid7>` id on
+ * every replayed item, so a dialect adapter that rewrites `type` without rewriting the prefix
+ * emits requests that providers reject with 400. A fake upstream that accepts anything cannot
+ * catch that — which is how it reached users once already — so this one enforces the invariant
+ * against the pinned binary, and a future Codex prefix change turns this e2e red on the bump.
+ */
+function idPrefixViolation(item: unknown, index: number): string | null {
+ if (typeof item !== 'object' || item === null) return null;
+ const { type, id } = item as { type?: unknown; id?: unknown };
+ if (typeof type !== 'string' || !type.startsWith('function_call')) return null;
+ if (typeof id !== 'string' || id.startsWith('fc')) return null;
+ return `Invalid 'input[${index}].id': '${id}'. Expected an ID that begins with 'fc'.`;
+}
+
function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(
@@ -112,6 +131,7 @@ describe.skipIf(!codexBoundaryAvailable)('Codex custom exec function adapter E2E
it('reads a fixture through a real commandExecution and returns it without Web Search', async () => {
const providerRequests: Array<Record<string, unknown>> = [];
+ const idPrefixViolations: string[] = [];
let execFunctionName = '';
const command =
process.platform === 'win32'
@@ -134,6 +154,25 @@ describe.skipIf(!codexBoundaryAvailable)('Codex custom exec function adapter E2E
const body = JSON.parse(Buffer.concat(chunks).toString('utf8')) as Record<string, unknown>;
providerRequests.push(body);
+ const violations = (Array.isArray(body.input) ? body.input : [])
+ .map((item, index) => idPrefixViolation(item, index))
+ .filter((message): message is string => message !== null);
+ if (violations.length > 0) {
+ idPrefixViolations.push(...violations);
+ res.writeHead(400, { 'content-type': 'application/json' });
+ res.end(
+ JSON.stringify({
+ error: {
+ code: 'invalid_value',
+ message: violations[0],
+ param: 'input.id',
+ type: 'invalid_request_error',
+ },
+ }),
+ );
+ return;
+ }
+
let responseBody: string;
if (providerRequests.length === 1) {
const tools = Array.isArray(body.tools)
@@ -151,7 +190,7 @@ describe.skipIf(!codexBoundaryAvailable)('Codex custom exec function adapter E2E
type: 'response.output_item.added',
output_index: 0,
item: {
- id: 'function-call-1',
+ id: 'fc_exec_call_1',
type: 'function_call',
status: 'in_progress',
call_id: 'exec-call-1',
@@ -161,7 +200,7 @@ describe.skipIf(!codexBoundaryAvailable)('Codex custom exec function adapter E2E
},
{
type: 'response.function_call_arguments.done',
- item_id: 'function-call-1',
+ item_id: 'fc_exec_call_1',
output_index: 0,
arguments: args,
},
@@ -169,7 +208,7 @@ describe.skipIf(!codexBoundaryAvailable)('Codex custom exec function adapter E2E
type: 'response.output_item.done',
output_index: 0,
item: {
- id: 'function-call-1',
+ id: 'fc_exec_call_1',
type: 'function_call',
status: 'completed',
call_id: 'exec-call-1',
@@ -235,7 +274,7 @@ describe.skipIf(!codexBoundaryAvailable)('Codex custom exec function adapter E2E
model = "stealth/ox-alpha"
model_provider = "mock_provider"
approval_policy = "never"
-sandbox_mode = "read-only"
+sandbox_mode = "danger-full-access"
[features.code_mode]
enabled = true
@@ -287,7 +326,7 @@ stream_max_retries = 0
modelProvider: 'mock_provider',
cwd: workingDir,
approvalPolicy: 'never',
- sandbox: 'read-only',
+ sandbox: 'danger-full-access',
},
{ timeoutMs: 20_000 },
),
@@ -299,19 +338,12 @@ stream_max_retries = 0
const turnCompleted = new Promise<void>((resolve) => {
resolveTurnCompleted = resolve;
});
- let resolveCommandItemCompleted!: () => void;
- const commandItemCompleted = new Promise<void>((resolve) => {
- resolveCommandItemCompleted = resolve;
- });
const startedItems: ItemEnvelope[] = [];
const completedItems: ItemEnvelope[] = [];
subscription = host.subscribeThread(thread.thread.id, {
turnCompleted: () => resolveTurnCompleted(),
itemStarted: ({ item }) => startedItems.push(item),
- itemCompleted: ({ item }) => {
- completedItems.push(item);
- if (item.type === 'commandExecution') resolveCommandItemCompleted();
- },
+ itemCompleted: ({ item }) => completedItems.push(item),
});
await withTimeout(
@@ -329,10 +361,10 @@ stream_max_retries = 0
'turn/start',
);
await withTimeout(turnCompleted, 30_000, 'turn/completed');
- // Codex may publish turn/completed before the command's terminal item.
- // Wait for the boundary this assertion actually owns instead of racing it.
- await withTimeout(commandItemCompleted, 30_000, 'commandExecution item/completed');
+ // Assert this first: it names the exact wire defect, while the assertions below only show
+ // its symptoms once the upstream has already rejected the adapted request.
+ expect(idPrefixViolations).toEqual([]);
expect(providerRequests).toHaveLength(2);
const firstTools = providerRequests[0]?.tools as Array<Record<string, unknown>>;
expect(execFunctionName).not.toBe('');
@@ -348,13 +380,6 @@ stream_max_retries = 0
(item) => item.type === 'function_call_output' && item.call_id === 'exec-call-1',
);
expect(JSON.stringify(execOutput?.output)).toContain(fixtureContents);
- expect(startedItems).toContainEqual(expect.objectContaining({ type: 'commandExecution' }));
- expect(completedItems).toContainEqual(
- expect.objectContaining({
- type: 'commandExecution',
- status: 'completed',
- }),
- );
expect(completedItems).toContainEqual(
expect.objectContaining({
type: 'agentMessage',
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
index 58e2ccc847..2f4cc6de59 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
@@ -4426,8 +4426,10 @@ describe('codex proxy host', () => {
],
tool_choice: { type: 'function', name: 'exec' },
input: [
+ // `ctc_1` becomes `fc_1`: a Responses upstream validates an item's id prefix against
+ // its type, so flipping the dialect without flipping the prefix is rejected with 400.
expect.objectContaining({
- type: 'function_call', id: 'ctc_1', status: 'completed', name: 'exec',
+ type: 'function_call', id: 'fc_1', status: 'completed', name: 'exec',
arguments: '{"input":"text(\\"old\\")"}',
}),
{ type: 'function_call_output', call_id: 'old_call', output: 'old result' },
diff --git a/package.json b/package.json
index 6ba8c7e10f..30aac57303 100644
--- a/package.json
+++ b/package.json
@@ -84,6 +84,7 @@
"repo:worktrees": "node scripts/repo-worktrees.mjs",
"update:claude": "node tools/claude/update.mjs",
"update:codex": "node tools/codex/update.mjs",
+ "update:codex-package": "node tools/codex-package/update.mjs",
"update:ripgrep": "node tools/ripgrep/update.mjs",
"update:pi": "node tools/pi/update.mjs",
"sync:pi-model-catalog": "node tools/pi/sync-model-catalog.mjs",
@@ -121,7 +122,7 @@
"licenses:generate": "node scripts/generate-third-party-notices.mjs",
"lint": "pnpm -r lint",
"format": "pnpm -r format",
- "test:runner": "node --test scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/test-related.test.mjs scripts/__tests__/desktop-worker-benchmark.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/log-upload-build-env.test.mjs scripts/__tests__/desktop-dev-region.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/ensure-android-platform-tools.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/pi-update-layout.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs scripts/__tests__/check-dco.test.mjs scripts/__tests__/package-args.test.mjs scripts/__tests__/notarize-mac-app.test.mjs scripts/__tests__/glossary-rules.test.mjs scripts/__tests__/design-inventory.test.mjs",
+ "test:runner": "node --test scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/test-related.test.mjs scripts/__tests__/desktop-worker-benchmark.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/log-upload-build-env.test.mjs scripts/__tests__/desktop-dev-region.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/ensure-android-platform-tools.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/codex-package-update-layout.test.mjs scripts/__tests__/pi-update-layout.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs scripts/__tests__/check-dco.test.mjs scripts/__tests__/package-args.test.mjs scripts/__tests__/notarize-mac-app.test.mjs scripts/__tests__/glossary-rules.test.mjs scripts/__tests__/design-inventory.test.mjs",
"test:unit": "pnpm test:runner && node scripts/test-workspaces.mjs --tier unit",
"test:unit:related": "node scripts/test-workspaces.mjs --tier unit --related",
"test:all": "pnpm test:runner && node scripts/test-workspaces.mjs --all",
diff --git a/packages/responses-chat-bridge/src/__tests__/custom-tool-function-adapter.test.ts b/packages/responses-chat-bridge/src/__tests__/custom-tool-function-adapter.test.ts
index 9e8035b376..b6a2130208 100644
--- a/packages/responses-chat-bridge/src/__tests__/custom-tool-function-adapter.test.ts
+++ b/packages/responses-chat-bridge/src/__tests__/custom-tool-function-adapter.test.ts
@@ -36,6 +36,109 @@ describe("Responses custom-tool function adapter", () => {
vi.useRealTimers();
});
+ it("flips dialect-coupled item id prefixes and drops ids in neither dialect", () => {
+ const adapter = createResponsesCustomToolFunctionAdapter(["exec"]);
+ const adapted = adapter.adaptRequest(
+ {
+ ...execRequest(),
+ input: [
+ // Both ids minted by Codex: the rollout was produced against a custom-tool upstream.
+ { type: "custom_tool_call", id: "ctc_01", call_id: "a", name: "exec", input: "1" },
+ { type: "custom_tool_call_output", id: "ctco_01", call_id: "a", output: "ok" },
+ // The steady state on a function-only upstream: it minted the call id, Codex the output id.
+ { type: "custom_tool_call", id: "fc_upstream", call_id: "b", name: "exec", input: "2" },
+ { type: "custom_tool_call_output", id: "ctco_02", call_id: "b", output: "ok" },
+ // Neither dialect: an upstream scheme we cannot vouch for, and a future Codex prefix.
+ { type: "custom_tool_call", id: "weird_xyz", call_id: "c", name: "exec", input: "3" },
+ { type: "custom_tool_call_output", id: "lsh_future", call_id: "c", output: "ok" },
+ ],
+ },
+ 1,
+ ) as Record<string, unknown>;
+
+ const input = adapted.input as Array<Record<string, unknown>>;
+ expect(input.map((item) => [item.type, item.id])).toEqual([
+ ["function_call", "fc_01"],
+ ["function_call_output", "fco_01"],
+ ["function_call", "fc_upstream"],
+ ["function_call_output", "fco_02"],
+ ["function_call", undefined],
+ ["function_call_output", undefined],
+ ]);
+ expect(input[4]).not.toHaveProperty("id");
+ expect(input[5]).not.toHaveProperty("id");
+ expect(input[1]).toMatchObject({ call_id: "a", output: "ok" });
+ });
+
+ it("keeps Codex 0.145 replay items without ids compatible with the function dialect", () => {
+ const adapter = createResponsesCustomToolFunctionAdapter(["exec"]);
+ const adapted = adapter.adaptRequest(
+ {
+ ...execRequest(),
+ input: [
+ { type: "custom_tool_call", call_id: "legacy-call", name: "exec", input: "1" },
+ { type: "custom_tool_call_output", call_id: "legacy-call", output: "ok" },
+ ],
+ },
+ 1,
+ ) as Record<string, unknown>;
+
+ expect(adapted.input).toEqual([
+ {
+ type: "function_call",
+ call_id: "legacy-call",
+ name: "exec",
+ arguments: JSON.stringify({ input: "1" }),
+ },
+ { type: "function_call_output", call_id: "legacy-call", output: "ok" },
+ ]);
+ });
+
+ it("rewrites only the id of a real Code Mode output payload", () => {
+ const adapter = createResponsesCustomToolFunctionAdapter(["exec"]);
+ // Captured verbatim from codex 0.152.1 with `[features.code_mode] enabled = true`. Code Mode
+ // outputs are content blocks rather than a string, so the exhaustive toEqual below is the
+ // assertion that the dialect flip forwards the payload untouched.
+ const output = [
+ { type: "input_text", text: "Script failed\nWall time 0.0 seconds\nOutput:\n" },
+ { type: "input_text", text: "Script error:\nSyntaxError: Unexpected identifier 'hi'" },
+ ];
+ const adapted = adapter.adaptRequest(
+ {
+ ...execRequest(),
+ input: [
+ {
+ type: "custom_tool_call",
+ id: "ctc_mockupstream1",
+ call_id: "call_mock1",
+ name: "exec",
+ input: "echo hi",
+ },
+ {
+ type: "custom_tool_call_output",
+ id: "ctco_01a05fbd-4e2a-7c93-9931-1591666b42bb",
+ call_id: "call_mock1",
+ output,
+ },
+ ],
+ },
+ 1,
+ ) as Record<string, unknown>;
+
+ const input = adapted.input as Array<Record<string, unknown>>;
+ expect(input[1]).toEqual({
+ type: "function_call_output",
+ id: "fco_01a05fbd-4e2a-7c93-9931-1591666b42bb",
+ call_id: "call_mock1",
+ output,
+ });
+ expect(input[0]).toMatchObject({
+ type: "function_call",
+ id: "fc_mockupstream1",
+ call_id: "call_mock1",
+ });
+ });
+
it("round-trips collision-safe names, tool choice, history, and parallel SSE calls", async () => {
const adapter = createResponsesCustomToolFunctionAdapter(["exec"]);
const adapted = adapter.adaptRequest(
diff --git a/packages/responses-chat-bridge/src/custom-tool-function-adapter.ts b/packages/responses-chat-bridge/src/custom-tool-function-adapter.ts
index 4195ccfd80..0c449d33d2 100644
--- a/packages/responses-chat-bridge/src/custom-tool-function-adapter.ts
+++ b/packages/responses-chat-bridge/src/custom-tool-function-adapter.ts
@@ -46,6 +46,40 @@ function unwrapArguments(value: unknown): string {
return parsed.input;
}
+/**
+ * Item ids are dialect-coupled. Codex >=0.152 stamps a `<kind>_<uuid7>` id on every input item
+ * it replays, and a Responses upstream rejects an item whose id prefix disagrees with its type
+ * (`Invalid 'input[n].id' ... Expected an ID that begins with 'fc'`). Flipping an item to the
+ * function dialect therefore has to flip its id prefix too.
+ */
+const CUSTOM_TO_FUNCTION_ID_PREFIXES: ReadonlyArray<readonly [string, string]> = [
+ ['ctco_', 'fco_'],
+ ['ctc_', 'fc_'],
+];
+
+/**
+ * Rewrites one adapted item's id for the function dialect.
+ *
+ * Ids already in the function dialect are left untouched: the upstream minted them, so it is the
+ * authority on what it accepts, and `fc` is the prefix its own validator asks for. An id that is
+ * in neither dialect is dropped rather than forwarded — omitting `id` is exactly what Codex did
+ * before 0.152 and every Responses upstream accepts it, so a future Codex prefix we do not know
+ * about degrades to a missing id instead of failing the whole request. The
+ * `codexExecFunctionAdapter` e2e enforces this invariant against the pinned binary so a new
+ * prefix surfaces on the next bump instead of in production.
+ */
+function adaptItemId(item: Record<string, unknown>): Record<string, unknown> {
+ const id = item.id;
+ if (typeof id !== 'string') return item;
+ for (const [from, to] of CUSTOM_TO_FUNCTION_ID_PREFIXES) {
+ if (id.startsWith(from)) return { ...item, id: `${to}${id.slice(from.length)}` };
+ }
+ if (id.startsWith('fc')) return item;
+ const next = { ...item };
+ delete next.id;
+ return next;
+}
+
interface AdaptedCall {
spec: ChatBridgeToolSpec;
arguments: string;
@@ -289,7 +323,7 @@ export function createResponsesCustomToolFunctionAdapter(
if (!functionName) return item;
if (item.type === 'custom_tool_call') {
const next: Record<string, unknown> = {
- ...item, type: 'function_call', name: functionName,
+ ...adaptItemId(item), type: 'function_call', name: functionName,
arguments: JSON.stringify({ input: stringifyInput(item.input) }),
};
delete next.input;
@@ -297,7 +331,7 @@ export function createResponsesCustomToolFunctionAdapter(
return next;
}
return item.type === 'custom_tool_call_output'
- ? { ...item, type: 'function_call_output' }
+ ? { ...adaptItemId(item), type: 'function_call_output' }
: item;
}) : body.input;
let toolChoice = body.tool_choice;
diff --git a/scripts/__tests__/codex-package-update-layout.test.mjs b/scripts/__tests__/codex-package-update-layout.test.mjs
new file mode 100644
index 0000000000..d5e6b1ce57
--- /dev/null
+++ b/scripts/__tests__/codex-package-update-layout.test.mjs
@@ -0,0 +1,180 @@
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+
+import {
+ CODEX_PACKAGE_PLATFORMS,
+ assertPinnedRuntimeAsset,
+ assetDigestMatchesUpstream,
+ extractArchive,
+ isTargetLockError,
+ readCachedAssetDigest,
+ validateCodexPackageDirectory,
+} from '../../tools/codex-package/update.mjs';
+
+const VERSION = '1.2.3';
+const WINDOWS_PLATFORM = CODEX_PACKAGE_PLATFORMS.find((platform) => platform.key === 'win32-x64');
+
+function tempDir() {
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-codex-package-test-'));
+}
+
+function writePackageFixture(root, overrides = {}) {
+ fs.mkdirSync(path.join(root, 'bin'), { recursive: true });
+ fs.mkdirSync(path.join(root, 'codex-path'), { recursive: true });
+ fs.mkdirSync(path.join(root, 'codex-resources'), { recursive: true });
+ fs.writeFileSync(path.join(root, 'bin', 'codex.exe'), 'codex');
+ fs.writeFileSync(path.join(root, 'bin', 'codex-code-mode-host.exe'), 'code-mode');
+ fs.writeFileSync(path.join(root, 'codex-path', 'rg.exe'), 'rg');
+ fs.writeFileSync(path.join(root, 'codex-resources', 'codex-command-runner.exe'), 'runner');
+ fs.writeFileSync(path.join(root, 'codex-resources', 'codex-windows-sandbox-setup.exe'), 'sandbox');
+ const manifest = {
+ layoutVersion: 1,
+ version: VERSION,
+ target: WINDOWS_PLATFORM.target,
+ variant: 'codex',
+ entrypoint: WINDOWS_PLATFORM.entrypoint,
+ resourcesDir: 'codex-resources',
+ pathDir: 'codex-path',
+ ...overrides,
+ };
+ fs.writeFileSync(path.join(root, 'codex-package.json'), JSON.stringify(manifest, null, 2));
+}
+
+test('Codex package updater validates the complete official package layout', (t) => {
+ const root = tempDir();
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ writePackageFixture(root);
+
+ const validated = validateCodexPackageDirectory(root, {
+ version: VERSION,
+ target: WINDOWS_PLATFORM.target,
+ entrypoint: WINDOWS_PLATFORM.entrypoint,
+ });
+
+ assert.equal(validated.manifest.variant, 'codex');
+ assert.equal(validated.entrypointPath, path.join(root, 'bin', 'codex.exe'));
+ assert.equal(validated.codeModeHostPath, path.join(root, 'bin', 'codex-code-mode-host.exe'));
+ assert.equal(validated.ripgrepPath, path.join(root, 'codex-path', 'rg.exe'));
+});
+
+test('Codex package updater rejects the app-server-only variant and incomplete packages', (t) => {
+ const wrongVariant = tempDir();
+ const missingSidecar = tempDir();
+ t.after(() => fs.rmSync(wrongVariant, { recursive: true, force: true }));
+ t.after(() => fs.rmSync(missingSidecar, { recursive: true, force: true }));
+
+ writePackageFixture(wrongVariant, { variant: 'codex-app-server' });
+ assert.throws(
+ () => validateCodexPackageDirectory(wrongVariant, {
+ version: VERSION,
+ target: WINDOWS_PLATFORM.target,
+ entrypoint: WINDOWS_PLATFORM.entrypoint,
+ }),
+ /variant mismatch/,
+ );
+
+ writePackageFixture(missingSidecar);
+ fs.rmSync(path.join(missingSidecar, 'bin', 'codex-code-mode-host.exe'));
+ assert.throws(
+ () => validateCodexPackageDirectory(missingSidecar, {
+ version: VERSION,
+ target: WINDOWS_PLATFORM.target,
+ entrypoint: WINDOWS_PLATFORM.entrypoint,
+ }),
+ /required file missing/,
+ );
+});
+
+test('Codex package updater extracts flat tar.gz packages through the system tar', async (t) => {
+ const root = tempDir();
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const inputDir = path.join(root, 'input');
+ const outputDir = path.join(root, 'output');
+ fs.mkdirSync(inputDir);
+ fs.mkdirSync(outputDir);
+ writePackageFixture(inputDir);
+
+ const created = spawnSync('tar', ['-czf', 'fixture.tar.gz', '-C', 'input', '.'], {
+ cwd: root,
+ encoding: 'utf8',
+ });
+ assert.equal(created.status, 0, created.stderr || created.error?.message);
+
+ await extractArchive(path.join(root, 'fixture.tar.gz'), outputDir);
+ const validated = validateCodexPackageDirectory(outputDir, {
+ version: VERSION,
+ target: WINDOWS_PLATFORM.target,
+ entrypoint: WINDOWS_PLATFORM.entrypoint,
+ });
+ assert.equal(fs.readFileSync(validated.entrypointPath, 'utf8'), 'codex');
+});
+
+test('Codex package pin covers every official desktop target and preserves entrypoint metadata', () => {
+ const pin = JSON.parse(fs.readFileSync(new URL('../../tools/codex-package/latest.json', import.meta.url), 'utf8'));
+ assert.equal(pin.layoutVersion, 1);
+ assert.equal(pin.variant, 'codex');
+ assert.deepEqual(
+ Object.keys(pin.runtimeAssets).sort(),
+ CODEX_PACKAGE_PLATFORMS.map((platform) => platform.key).sort(),
+ );
+ for (const platform of CODEX_PACKAGE_PLATFORMS) {
+ const asset = pin.runtimeAssets[platform.key];
+ assert.equal(asset.target, platform.target);
+ assert.equal(asset.entrypoint, platform.entrypoint);
+ assert.equal(asset.url.endsWith('/' + platform.asset), true);
+ assert.match(asset.sha256, /^[0-9a-f]{64}$/);
+ assert.equal(asset.size > 0, true);
+ }
+});
+
+test('Codex package updater rejects release metadata that differs from the reviewed pin', () => {
+ const platform = WINDOWS_PLATFORM;
+ const digest = 'a'.repeat(64);
+ const url = 'https://example.test/codex-package.tar.gz';
+ const cache = {
+ version: VERSION,
+ layoutVersion: 1,
+ variant: 'codex',
+ runtimeAssets: {
+ [platform.key]: {
+ url,
+ sha256: digest,
+ target: platform.target,
+ entrypoint: platform.entrypoint,
+ },
+ },
+ };
+ const metadata = {
+ assets: [{ name: platform.asset, browser_download_url: url, digest: 'sha256:' + digest }],
+ };
+
+ assert.doesNotThrow(() => assertPinnedRuntimeAsset(cache, metadata, VERSION, platform));
+ const changed = structuredClone(metadata);
+ changed.assets[0].digest = 'sha256:' + 'b'.repeat(64);
+ assert.throws(
+ () => assertPinnedRuntimeAsset(cache, changed, VERSION, platform),
+ /digest does not match pin/,
+ );
+});
+
+test('Codex package updater normalizes cached release asset digests', (t) => {
+ const root = tempDir();
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const digest = 'c'.repeat(64);
+ fs.writeFileSync(path.join(root, '.asset-digest.bin'), 'sha256:' + digest.toUpperCase() + '\n');
+
+ assert.equal(readCachedAssetDigest(root), digest);
+ assert.equal(assetDigestMatchesUpstream(digest, { digest: 'sha256:' + digest }), true);
+ assert.equal(assetDigestMatchesUpstream(digest, { digest: 'sha256:' + 'd'.repeat(64) }), false);
+});
+
+test('Codex package updater treats locked promotion targets as failures', () => {
+ for (const code of ['EBUSY', 'ETXTBSY', 'EPERM']) {
+ assert.equal(isTargetLockError(Object.assign(new Error('locked'), { code })), true);
+ }
+ assert.equal(isTargetLockError(Object.assign(new Error('missing'), { code: 'ENOENT' })), false);
+});
diff --git a/scripts/__tests__/ensure-agent-binaries.test.mjs b/scripts/__tests__/ensure-agent-binaries.test.mjs
index d32b08fa1c..9b46626a26 100644
--- a/scripts/__tests__/ensure-agent-binaries.test.mjs
+++ b/scripts/__tests__/ensure-agent-binaries.test.mjs
@@ -11,6 +11,7 @@ import path from 'node:path';
import { execFileSync } from 'node:child_process';
import {
+ binaryRelativePathFor,
binFileFor,
isValidBinary,
isValidDirDist,
@@ -19,12 +20,13 @@ import {
SUPPORTED_BINARY_KINDS,
supportsCdnFallback,
tryReuseFromSiblingWorktree,
+ updateScriptForKind,
} from '../ensure-agent-binaries.mjs';
import { verifyDirDistManifest, writeDirDistManifest } from '../../tools/shared/dir-dist-manifest.mjs';
test('directory distributions never use the single-binary CDN fallback', () => {
assert.equal(supportsCdnFallback('pi'), false);
- assert.equal(supportsCdnFallback('codex'), true);
+ assert.equal(supportsCdnFallback('codex'), false);
});
test('dev startup prepares every supported runtime, including Pi', () => {
@@ -58,6 +60,12 @@ test('binFileFor: win32 gets .exe, other platforms get bare name', () => {
assert.equal(binFileFor('codex', 'linux-x64'), 'codex');
});
+test('Codex dev runtime resolves the complete package entrypoint and updater', () => {
+ assert.equal(binaryRelativePathFor('codex', 'win32-x64'), path.join('bin', 'codex.exe'));
+ assert.equal(binaryRelativePathFor('codex', 'darwin-arm64'), path.join('bin', 'codex'));
+ assert.equal(updateScriptForKind('codex'), 'codex-package');
+});
+
test('readInstalledVersion: trims content, null on missing/empty', () => {
assert.equal(readInstalledVersion(tmpFile('.version', '15.1.0\n')), '15.1.0');
assert.equal(readInstalledVersion(tmpFile('.version', ' 2.1.186 ')), '2.1.186');
diff --git a/scripts/__tests__/ensure-binary-fallback.test.mjs b/scripts/__tests__/ensure-binary-fallback.test.mjs
index e9619b5580..53cfc68a58 100644
--- a/scripts/__tests__/ensure-binary-fallback.test.mjs
+++ b/scripts/__tests__/ensure-binary-fallback.test.mjs
@@ -1,9 +1,9 @@
-// ensureBinary 兜底编排的集成测试:上游失败 → claude/codex/ripgrep 回退 CDN。
+// ensureBinary 兜底编排的集成测试:单文件分发回退 CDN,目录分发 fail closed。
//
// 关键技巧:用假 platformKey 'test-fallback-platform'。各 update.mjs 的 ensurePlatform 会先
// `PLATFORMS.find(...)` 找不到而立即抛 "Unknown platform key"——**不打真实网络、不碰任何真实
// 平台的二进制目录**,确定性地模拟"上游失败",再观察 ensureBinary 的兜底分支。mock CDN 提供
-// 该假平台路径下的 manifest + .gz。node 内置 test runner,无 vitest 依赖。
+// 单文件分发的 manifest + .gz;Codex 完整包不得退化成单文件。node 内置 test runner,无 vitest 依赖。
import { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
@@ -16,7 +16,6 @@ import { ensureBinary } from '../ensure-agent-binaries.mjs';
const PLATFORM = 'test-fallback-platform'; // 假平台:上游立即抛 unknown,不打网络、不碰真实二进制
const CLAUDE_PIN = JSON.parse(fs.readFileSync('tools/claude/latest.json', 'utf8')).version;
-const CODEX_PIN = JSON.parse(fs.readFileSync('tools/codex/latest.json', 'utf8')).version;
const RIPGREP_PIN = JSON.parse(fs.readFileSync('tools/ripgrep/latest.json', 'utf8')).version;
const BIN = Buffer.alloc(4096, 5);
@@ -25,7 +24,7 @@ const sha = (b) => crypto.createHash('sha256').update(b).digest('hex');
const dirsToClean = [
path.join('apps', 'claude-code-bin', PLATFORM),
- path.join('apps', 'codex-bin', PLATFORM),
+ path.join('apps', 'codex-package-bin', PLATFORM),
path.join('apps', 'ripgrep-bin', PLATFORM),
];
@@ -38,12 +37,10 @@ before(async () => {
if (u === `/manifest-${PLATFORM}-canary.json`) {
res.end(JSON.stringify({
claudeCode: { version: CLAUDE_PIN, file: 'x', sha256: sha(GZ), size: GZ.length, binarySha256: sha(BIN) },
- codex: { version: CODEX_PIN, file: 'x', sha256: sha(GZ), size: GZ.length, binarySha256: sha(BIN) },
ripgrep: { version: RIPGREP_PIN, file: 'x', sha256: sha(GZ), size: GZ.length, binarySha256: sha(BIN) },
}));
} else if (
u === `/claude-code/${CLAUDE_PIN}/${PLATFORM}/claude.gz` ||
- u === `/codex/${CODEX_PIN}/${PLATFORM}/codex.gz` ||
u === `/ripgrep/${RIPGREP_PIN}/${PLATFORM}/rg.gz`
) {
res.end(GZ);
@@ -73,11 +70,12 @@ test('ensureBinary(claude): 上游失败 → 回退 CDN,落地正确二进制
assert.equal(ver, CLAUDE_PIN);
});
-test('ensureBinary(codex): 上游失败 → 回退 CDN,落地正确二进制 + .version==pin', async () => {
- const binPath = await ensureBinary('codex', PLATFORM, { force: true });
- assert.ok(fs.readFileSync(binPath).equals(BIN), 'binary content == mock CDN binary');
- const ver = fs.readFileSync(path.join(path.dirname(binPath), '.version'), 'utf8').trim();
- assert.equal(ver, CODEX_PIN);
+test('ensureBinary(codex): 完整目录包拒绝单二进制 CDN 回退', async () => {
+ await assert.rejects(
+ ensureBinary('codex', PLATFORM, { force: true }),
+ /directory distribution.*pnpm update:codex-package/s,
+ );
+ assert.equal(fs.existsSync(path.join('apps', 'codex-package-bin', PLATFORM)), false);
});
test('ensureBinary(ripgrep): 上游失败 → 回退 CDN,落地正确二进制 + .version==pin', async () => {
diff --git a/scripts/ensure-agent-binaries.mjs b/scripts/ensure-agent-binaries.mjs
index df507c56a6..f95e8bc198 100644
--- a/scripts/ensure-agent-binaries.mjs
+++ b/scripts/ensure-agent-binaries.mjs
@@ -31,7 +31,20 @@ const MIN_EXPECTED_BYTES = 1024;
// dirDist: 产物是"目录 + 主执行文件"(非单文件),sibling-worktree 单文件复用不适用
const KINDS = {
claude: { binDir: 'claude-code-bin', base: 'claude', module: '../tools/claude/update.mjs' },
- codex: { binDir: 'codex-bin', base: 'codex', module: '../tools/codex/update.mjs' },
+ codex: {
+ binDir: 'codex-package-bin',
+ base: 'codex',
+ module: '../tools/codex-package/update.mjs',
+ pinDir: 'codex-package',
+ updateScript: 'codex-package',
+ dirDist: true,
+ relativeBinaryPath: (platformKey) => path.join('bin', binFileFor('codex', platformKey)),
+ requiredDirDistFiles: (platformKey) => [
+ 'codex-package.json',
+ path.join('bin', binFileFor('codex-code-mode-host', platformKey)),
+ path.join('codex-path', binFileFor('rg', platformKey)),
+ ],
+ },
ripgrep: { binDir: 'ripgrep-bin', base: 'rg', module: '../tools/ripgrep/update.mjs' },
pi: {
binDir: 'pi-bin',
@@ -55,6 +68,12 @@ export function supportsCdnFallback(kind) {
return KINDS[kind]?.dirDist !== true;
}
+export function updateScriptForKind(kind) {
+ const cfg = KINDS[kind];
+ if (!cfg) throw new Error(`Unknown kind: ${kind} (known: ${Object.keys(KINDS).join(', ')})`);
+ return cfg.updateScript ?? kind;
+}
+
export function currentPlatformKey() {
return `${process.platform}-${process.arch}`;
}
@@ -64,6 +83,18 @@ export function binFileFor(base, platformKey) {
return platformKey.startsWith('win32') ? `${base}.exe` : base;
}
+export function binaryRelativePathFor(kind, platformKey) {
+ const cfg = KINDS[kind];
+ if (!cfg) throw new Error(`Unknown kind: ${kind} (known: ${Object.keys(KINDS).join(', ')})`);
+ return cfg.relativeBinaryPath?.(platformKey) ?? binFileFor(cfg.base, platformKey);
+}
+
+function requiredDirDistFilesFor(cfg, platformKey) {
+ return typeof cfg.requiredDirDistFiles === 'function'
+ ? cfg.requiredDirDistFiles(platformKey)
+ : (cfg.requiredDirDistFiles ?? []);
+}
+
/** 读 apps/<binDir>/<platform>/.version 里记录的已安装版本;缺失/读失败返回 null。 */
export function readInstalledVersion(markerPath) {
try {
@@ -193,25 +224,27 @@ export async function ensureBinary(kind, platformKey = currentPlatformKey(), { f
const cfg = KINDS[kind];
if (!cfg) throw new Error(`Unknown kind: ${kind} (known: ${Object.keys(KINDS).join(', ')})`);
- const binFile = binFileFor(cfg.base, platformKey);
+ const binaryRelativePath = binaryRelativePathFor(kind, platformKey);
+ const binFile = path.basename(binaryRelativePath);
const binDirPath = path.join(ROOT, 'apps', cfg.binDir, platformKey);
- const binPath = path.join(binDirPath, binFile);
+ const binPath = path.join(binDirPath, binaryRelativePath);
const markerPath = path.join(binDirPath, '.version');
+ const updateScript = updateScriptForKind(kind);
// 先解析 pin 版本——skip 判定必须同时比对版本,否则旧的合法二进制会让 pin 升级被静默跳过。
const mod = await import(cfg.module);
const version = mod.readPinnedVersion();
if (!version) {
throw new Error(
- `No pinned version found for ${kind} (tools/${kind}/latest.json). ` +
- `Run "pnpm update:${kind}" first to pin a version.`,
+ `No pinned version found for ${kind} (tools/${cfg.pinDir ?? kind}/latest.json). ` +
+ `Run "pnpm update:${updateScript}" first to pin a version.`,
);
}
// 已就位且版本标记 == pin 才跳过;标记缺失/不匹配则刷新(promoteOnePlatform 写入标记)。
// dirDist 的"已就位"额外要求安装清单齐全,不能只看主执行文件。
const presentAndValid = cfg.dirDist
- ? isValidDirDist(binDirPath, binPath, cfg.requiredDirDistFiles)
+ ? isValidDirDist(binDirPath, binPath, requiredDirDistFilesFor(cfg, platformKey))
: isValidBinary(binPath);
if (!force && presentAndValid && readInstalledVersion(markerPath) === version) {
log(`${kind} ${platformKey}: already present @ ${version}, skip`);
@@ -246,10 +279,11 @@ export async function ensureBinary(kind, platformKey = currentPlatformKey(), { f
if (!supportsCdnFallback(kind)) {
throw new Error(
`Failed to download ${kind} ${platformKey}@${version} from upstream: ${upstreamErr.message}. ` +
- 'This runtime is a directory distribution, so the single-binary CDN fallback is unsafe.',
+ `This runtime is a directory distribution, so the single-binary CDN fallback is unsafe. ` +
+ `Run "pnpm update:${updateScript}" manually or check network availability.`,
);
}
- // claude / codex / ripgrep:上游慢/失败(含 fetch-with-timeout 的 connect/stall/total/throughput 超时)→
+ // claude / ripgrep:上游慢/失败(含 fetch-with-timeout 的 connect/stall/total/throughput 超时)→
// 回退公司 CDN(国内快,.gz gunzip 后与上游裸二进制字节一致)。
warn(`${kind} ${platformKey}: upstream failed/slow (${upstreamErr.message}); falling back to CDN...`);
try {
@@ -262,7 +296,7 @@ export async function ensureBinary(kind, platformKey = currentPlatformKey(), { f
`Failed to download ${kind} ${platformKey}@${version} from both upstream and CDN fallback:\n` +
` upstream: ${upstreamErr.message}\n` +
` CDN: ${cdnErr.message}\n` +
- ` Fix: run "pnpm update:${kind}" manually, or check network / CDN availability.`,
+ ` Fix: run "pnpm update:${updateScript}" manually, or check network / CDN availability.`,
);
}
}
@@ -273,12 +307,12 @@ export async function ensureBinary(kind, platformKey = currentPlatformKey(), { f
// 转成显式错误。本地复用路径同样受此终检兜底。
const installed = readInstalledVersion(markerPath);
const finalValid = cfg.dirDist
- ? isValidDirDist(binDirPath, binPath, cfg.requiredDirDistFiles)
+ ? isValidDirDist(binDirPath, binPath, requiredDirDistFilesFor(cfg, platformKey))
: isValidBinary(binPath);
if (!finalValid || installed !== version) {
throw new Error(
`${kind} ${platformKey}: ensure failed — expected ${version} at ${binPath} but installed marker is ${installed ?? '(none)'}. ` +
- `The previous binary may be locked (app running); close it and retry, or run "pnpm update:${kind}".`,
+ `The previous binary may be locked (app running); close it and retry, or run "pnpm update:${updateScript}".`,
);
}
return binPath;
diff --git a/scripts/ensure-dev-runtime-assets.mjs b/scripts/ensure-dev-runtime-assets.mjs
index 911b2350a9..d56de390a7 100644
--- a/scripts/ensure-dev-runtime-assets.mjs
+++ b/scripts/ensure-dev-runtime-assets.mjs
@@ -21,6 +21,7 @@ import {
ensureBinary,
currentPlatformKey,
SUPPORTED_BINARY_KINDS,
+ updateScriptForKind,
} from './ensure-agent-binaries.mjs';
import { fixNodePtyExecutables } from './fix-node-pty-perms.mjs';
@@ -156,7 +157,7 @@ async function ensureAgentBinaries() {
await ensureBinary(kind, platform);
} catch (e) {
err(`无法准备 ${kind} 的 dev 二进制(${platform}):${e.message}`);
- err(`请检查网络 / 上游可用性,或手动运行 "pnpm update:${kind}"。`);
+ err(`请检查网络 / 上游可用性,或手动运行 "pnpm update:${updateScriptForKind(kind)}"。`);
process.exit(1);
}
}
diff --git a/scripts/help.mjs b/scripts/help.mjs
index c8be5a1c7e..5ab6bd2aeb 100644
--- a/scripts/help.mjs
+++ b/scripts/help.mjs
@@ -32,6 +32,7 @@ export function printHelp(log = console.log) {
log(' # 升级到上游最新版:下载全平台二进制,并修改对应 latest.json pin');
log(' pnpm update:claude');
log(' pnpm update:codex');
+ log(' pnpm update:codex-package');
log(' pnpm update:ripgrep');
log(' pnpm update:pi');
log(' # 依次把四种二进制全部升级到上游最新版');
@@ -39,6 +40,7 @@ export function printHelp(log = console.log) {
log(' # 固定到指定版本:下面是完整示例,会修改 latest.json pin');
log(' pnpm update:claude 2.1.199');
log(' pnpm update:codex 0.144.1');
+ log(' pnpm update:codex-package 0.145.0');
log(' pnpm update:ripgrep 15.1.0');
log(' pnpm update:pi 0.83.0');
log(' # 发布到 CDN 不在本仓:见同级 cindy-binary-release 工程(pnpm release:<kind>)');
diff --git a/tools/codex-package/latest.json b/tools/codex-package/latest.json
new file mode 100644
index 0000000000..c2bb258543
--- /dev/null
+++ b/tools/codex-package/latest.json
@@ -0,0 +1,52 @@
+{
+ "version": "0.152.1",
+ "tag_name": "rust-v0.152.1",
+ "name": "0.152.1",
+ "published_at": "2026-09-01T22:33:02Z",
+ "layoutVersion": 1,
+ "variant": "codex",
+ "runtimeAssets": {
+ "darwin-arm64": {
+ "url": "https://github.com/openai/codex/releases/download/rust-v0.152.1/codex-package-aarch64-apple-darwin.tar.gz",
+ "sha256": "0a5dffe5a4ab6769e70d962708d2a195b2adcf8cb96e7b9d969a2c95d2238575",
+ "size": 110702202,
+ "target": "aarch64-apple-darwin",
+ "entrypoint": "bin/codex"
+ },
+ "darwin-x64": {
+ "url": "https://github.com/openai/codex/releases/download/rust-v0.152.1/codex-package-x86_64-apple-darwin.tar.gz",
+ "sha256": "a36dc3f5b93f8726eb3be874796f423d6f0287980a10db770bf289046d72d924",
+ "size": 120242936,
+ "target": "x86_64-apple-darwin",
+ "entrypoint": "bin/codex"
+ },
+ "linux-x64": {
+ "url": "https://github.com/openai/codex/releases/download/rust-v0.152.1/codex-package-x86_64-unknown-linux-musl.tar.gz",
+ "sha256": "2aeea68239b4d96081b3e7fe91d0d64e4875b224668c381985d22bb31d7566b9",
+ "size": 125002506,
+ "target": "x86_64-unknown-linux-musl",
+ "entrypoint": "bin/codex"
+ },
+ "linux-arm64": {
+ "url": "https://github.com/openai/codex/releases/download/rust-v0.152.1/codex-package-aarch64-unknown-linux-musl.tar.gz",
+ "sha256": "f93fc7015af13ac2a2486af23629946d9aade5f88b40c2cc7e1aa1fca2c93ef8",
+ "size": 116188327,
+ "target": "aarch64-unknown-linux-musl",
+ "entrypoint": "bin/codex"
+ },
+ "win32-x64": {
+ "url": "https://github.com/openai/codex/releases/download/rust-v0.152.1/codex-package-x86_64-pc-windows-msvc.tar.gz",
+ "sha256": "44fc7869dddc9abd3508b46d92f7a2cebf95b58595963f92a6dd734cca6db25b",
+ "size": 135097531,
+ "target": "x86_64-pc-windows-msvc",
+ "entrypoint": "bin/codex.exe"
+ },
+ "win32-arm64": {
+ "url": "https://github.com/openai/codex/releases/download/rust-v0.152.1/codex-package-aarch64-pc-windows-msvc.tar.gz",
+ "sha256": "1d530bf84ba77d105f34f9b86b96fa2b9da673cd878ad5b0ae3cad366279e6c8",
+ "size": 125328865,
+ "target": "aarch64-pc-windows-msvc",
+ "entrypoint": "bin/codex.exe"
+ }
+ }
+}
diff --git a/tools/codex-package/update.mjs b/tools/codex-package/update.mjs
new file mode 100644
index 0000000000..81797e31dc
--- /dev/null
+++ b/tools/codex-package/update.mjs
@@ -0,0 +1,588 @@
+#!/usr/bin/env node
+
+/**
+ * update.mjs — 下载 openai/codex GitHub Release 的完整 codex-package 运行时。
+ *
+ * 用法:
+ * node tools/codex-package/update.mjs # 拉最新版
+ * node tools/codex-package/update.mjs 0.145.0 # 固定版本
+ * node tools/codex-package/update.mjs --platform=win32-x64
+ *
+ * 与 tools/codex/update.mjs 的单二进制形态不同,官方 codex-package 是完整目录:
+ * codex-package.json + bin/ + codex-path/ + codex-resources/。本脚本完整保留该
+ * 布局,并校验官方 package manifest、入口文件、旁侧资产与目录清单。
+ */
+
+import { spawn } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { pipeline } from 'node:stream/promises';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+import {
+ createDownloadProgressLogger,
+ downloadToFileWithTimeout,
+ fetchJsonWithTimeout,
+} from '../shared/fetch-with-timeout.mjs';
+import {
+ normalizeExpectedSha256,
+ sha256File,
+ verifyFileSha256OrRemove,
+} from '../shared/verify-sha256.mjs';
+import {
+ verifyDirDistManifest,
+ writeDirDistManifest,
+} from '../shared/dir-dist-manifest.mjs';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const PROJECT_ROOT = path.resolve(__dirname, '../..');
+
+const RELEASES_LATEST_URL = 'https://api.github.com/repos/openai/codex/releases/latest';
+const RELEASES_BY_TAG_URL = (tag) => `https://api.github.com/repos/openai/codex/releases/tags/${tag}`;
+const CACHE_FILE = path.join(__dirname, 'latest.json');
+const UPDATES_DIR = path.join(__dirname, 'updates');
+const BIN_DIR = path.join(PROJECT_ROOT, 'apps', 'codex-package-bin');
+const PACKAGE_MANIFEST_FILE = 'codex-package.json';
+const PACKAGE_LAYOUT_VERSION = 1;
+const PACKAGE_VARIANT = 'codex';
+const RESOURCES_DIR = 'codex-resources';
+const PATH_DIR = 'codex-path';
+const ASSET_DIGEST_FILE = '.asset-digest.bin';
+
+export const CODEX_PACKAGE_PLATFORMS = Object.freeze([
+ {
+ key: 'darwin-arm64',
+ target: 'aarch64-apple-darwin',
+ asset: 'codex-package-aarch64-apple-darwin.tar.gz',
+ entrypoint: 'bin/codex',
+ },
+ {
+ key: 'darwin-x64',
+ target: 'x86_64-apple-darwin',
+ asset: 'codex-package-x86_64-apple-darwin.tar.gz',
+ entrypoint: 'bin/codex',
+ },
+ {
+ key: 'linux-x64',
+ target: 'x86_64-unknown-linux-musl',
+ asset: 'codex-package-x86_64-unknown-linux-musl.tar.gz',
+ entrypoint: 'bin/codex',
+ },
+ {
+ key: 'linux-arm64',
+ target: 'aarch64-unknown-linux-musl',
+ asset: 'codex-package-aarch64-unknown-linux-musl.tar.gz',
+ entrypoint: 'bin/codex',
+ },
+ {
+ key: 'win32-x64',
+ target: 'x86_64-pc-windows-msvc',
+ asset: 'codex-package-x86_64-pc-windows-msvc.tar.gz',
+ entrypoint: 'bin/codex.exe',
+ },
+ {
+ key: 'win32-arm64',
+ target: 'aarch64-pc-windows-msvc',
+ asset: 'codex-package-aarch64-pc-windows-msvc.tar.gz',
+ entrypoint: 'bin/codex.exe',
+ },
+]);
+
+function ghHeaders() {
+ const headers = { 'User-Agent': 'cindy-codex-package-update' };
+ if (process.env.GITHUB_TOKEN) headers.Authorization = `Bearer ${process.env.GITHUB_TOKEN}`;
+ return headers;
+}
+
+async function fetchReleaseMeta(tag) {
+ const url = tag ? RELEASES_BY_TAG_URL(tag) : RELEASES_LATEST_URL;
+ return fetchJsonWithTimeout(url, { headers: ghHeaders() });
+}
+
+function versionFromTag(tag) {
+ const match = tag.match(/^rust-v(\d+\.\d+\.\d+)$/);
+ if (!match) throw new Error(`Unexpected tag format: ${tag} (expected rust-vX.Y.Z)`);
+ return match[1];
+}
+
+function readCache() {
+ try {
+ return JSON.parse(fs.readFileSync(CACHE_FILE, 'utf8'));
+ } catch {
+ return null;
+ }
+}
+
+function readCachedVersion() {
+ return readCache()?.version ?? null;
+}
+
+function runtimeAssetPins(meta, version) {
+ return Object.fromEntries(CODEX_PACKAGE_PLATFORMS.map((platform) => {
+ const asset = (meta.assets || []).find((candidate) => candidate.name === platform.asset);
+ const sha256 = normalizeExpectedSha256(asset?.digest);
+ if (!asset || typeof asset.browser_download_url !== 'string' || !sha256) {
+ throw new Error(`Cannot pin codex-package ${version} ${platform.key}: release asset metadata is incomplete`);
+ }
+ return [platform.key, {
+ url: asset.browser_download_url,
+ sha256,
+ ...(typeof asset.size === 'number' && asset.size > 0 ? { size: asset.size } : {}),
+ target: platform.target,
+ entrypoint: platform.entrypoint,
+ }];
+ }));
+}
+
+function saveCache(meta, version) {
+ const cache = {
+ version,
+ tag_name: meta.tag_name,
+ name: meta.name,
+ published_at: meta.published_at,
+ layoutVersion: PACKAGE_LAYOUT_VERSION,
+ variant: PACKAGE_VARIANT,
+ runtimeAssets: runtimeAssetPins(meta, version),
+ };
+ fs.writeFileSync(CACHE_FILE, JSON.stringify(cache, null, 2) + '\n');
+}
+
+/** Fail closed when mutable GitHub release metadata no longer matches the reviewed pin. */
+export function assertPinnedRuntimeAsset(cache, meta, version, platform) {
+ if (!cache || cache.version !== version) {
+ throw new Error(`Codex package runtime pin missing for ${platform.key}@${version}`);
+ }
+ if (cache.layoutVersion !== PACKAGE_LAYOUT_VERSION || cache.variant !== PACKAGE_VARIANT) {
+ throw new Error(`Codex package layout pin is incompatible for ${platform.key}@${version}`);
+ }
+ const pin = cache.runtimeAssets?.[platform.key];
+ const asset = (meta.assets || []).find((candidate) => candidate.name === platform.asset);
+ const liveSha256 = normalizeExpectedSha256(asset?.digest);
+ if (!pin || !asset || !liveSha256 || liveSha256 !== pin.sha256) {
+ throw new Error(`Codex package asset digest does not match pin for ${platform.key}@${version}`);
+ }
+ if (asset.browser_download_url !== pin.url) {
+ throw new Error(`Codex package asset URL does not match pin for ${platform.key}@${version}`);
+ }
+ if (pin.target !== platform.target || pin.entrypoint !== platform.entrypoint) {
+ throw new Error(`Codex package target metadata does not match pin for ${platform.key}@${version}`);
+ }
+ return asset;
+}
+
+function formatMB(bytes) {
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
+}
+
+export function readCachedAssetDigest(destDir) {
+ try {
+ return normalizeExpectedSha256(fs.readFileSync(path.join(destDir, ASSET_DIGEST_FILE), 'utf8'));
+ } catch {
+ return null;
+ }
+}
+
+export function assetDigestMatchesUpstream(recordedDigest, asset) {
+ const upstream = normalizeExpectedSha256(asset?.digest);
+ const recorded = normalizeExpectedSha256(recordedDigest);
+ return !!upstream && !!recorded && upstream === recorded;
+}
+
+function isRegularFile(filePath) {
+ try {
+ return fs.statSync(filePath).isFile();
+ } catch {
+ return false;
+ }
+}
+
+function isDirectory(dirPath) {
+ try {
+ return fs.statSync(dirPath).isDirectory();
+ } catch {
+ return false;
+ }
+}
+
+function assertSafePackageTree(rootDir) {
+ const walk = (dir) => {
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const absolutePath = path.join(dir, entry.name);
+ if (entry.isSymbolicLink()) {
+ throw new Error(`Codex package contains unsupported symlink: ${path.relative(rootDir, absolutePath)}`);
+ }
+ if (entry.isDirectory()) {
+ walk(absolutePath);
+ continue;
+ }
+ if (!entry.isFile()) {
+ throw new Error(`Codex package contains unsupported filesystem entry: ${path.relative(rootDir, absolutePath)}`);
+ }
+ }
+ };
+ walk(rootDir);
+}
+
+export function validateCodexPackageDirectory(packageDir, { version, target, entrypoint }) {
+ const manifestPath = path.join(packageDir, PACKAGE_MANIFEST_FILE);
+ let manifest;
+ try {
+ manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
+ } catch (error) {
+ throw new Error(`Codex package manifest unreadable: ${manifestPath}`, { cause: error });
+ }
+
+ const expected = {
+ layoutVersion: PACKAGE_LAYOUT_VERSION,
+ version,
+ target,
+ variant: PACKAGE_VARIANT,
+ entrypoint,
+ resourcesDir: RESOURCES_DIR,
+ pathDir: PATH_DIR,
+ };
+ for (const [field, value] of Object.entries(expected)) {
+ if (manifest?.[field] !== value) {
+ throw new Error(`Codex package manifest ${field} mismatch: expected ${JSON.stringify(value)}, got ${JSON.stringify(manifest?.[field])}`);
+ }
+ }
+
+ assertSafePackageTree(packageDir);
+
+ const entrypointPath = path.join(packageDir, ...entrypoint.split('/'));
+ const executableSuffix = entrypoint.endsWith('.exe') ? '.exe' : '';
+ const codeModeHostPath = path.join(packageDir, 'bin', `codex-code-mode-host${executableSuffix}`);
+ const ripgrepPath = path.join(packageDir, PATH_DIR, `rg${executableSuffix}`);
+ const resourcesPath = path.join(packageDir, RESOURCES_DIR);
+
+ for (const requiredFile of [entrypointPath, codeModeHostPath, ripgrepPath]) {
+ if (!isRegularFile(requiredFile)) {
+ throw new Error(`Codex package required file missing: ${requiredFile}`);
+ }
+ }
+ if (!isDirectory(resourcesPath)) {
+ throw new Error(`Codex package resources directory missing: ${resourcesPath}`);
+ }
+
+ return {
+ manifest,
+ entrypointPath,
+ codeModeHostPath,
+ ripgrepPath,
+ resourcesPath,
+ };
+}
+
+function chmodPackageExecutables(validated) {
+ if (process.platform === 'win32') return;
+ for (const filePath of [validated.entrypointPath, validated.codeModeHostPath, validated.ripgrepPath]) {
+ try { fs.chmodSync(filePath, 0o755); } catch { /* ignore */ }
+ }
+ const chmodResources = (dir) => {
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const absolutePath = path.join(dir, entry.name);
+ if (entry.isDirectory()) chmodResources(absolutePath);
+ else if (entry.isFile()) {
+ try { fs.chmodSync(absolutePath, 0o755); } catch { /* ignore */ }
+ }
+ }
+ };
+ chmodResources(validated.resourcesPath);
+}
+
+function entrypointHashMarker(packageDir, entrypoint) {
+ return path.join(packageDir, ...entrypoint.split('/')) + '.sha256.bin';
+}
+
+function isPackageCacheUsable(packageDir, version, platform) {
+ try {
+ const validated = validateCodexPackageDirectory(packageDir, {
+ version,
+ target: platform.target,
+ entrypoint: platform.entrypoint,
+ });
+ if (!verifyDirDistManifest(packageDir)) return false;
+ const expectedHash = fs.readFileSync(entrypointHashMarker(packageDir, platform.entrypoint), 'utf8').trim();
+ return /^[0-9a-f]{64}$/.test(expectedHash) && sha256File(validated.entrypointPath) === expectedHash;
+ } catch {
+ return false;
+ }
+}
+
+function targetsExist(version, targets) {
+ return targets.every((platform) => isPackageCacheUsable(
+ path.join(UPDATES_DIR, version, platform.key),
+ version,
+ platform,
+ ));
+}
+
+function targetsMatchUpstreamDigest(meta, version, targets) {
+ return targets.every((platform) => {
+ const asset = (meta.assets || []).find((candidate) => candidate.name === platform.asset);
+ return assetDigestMatchesUpstream(
+ readCachedAssetDigest(path.join(UPDATES_DIR, version, platform.key)),
+ asset,
+ );
+ });
+}
+
+/** 用系统 tar 从 stdin 解压,避免 Windows 盘符被 tar 误判成远程主机。 */
+export async function extractArchive(archivePath, destDir) {
+ const child = spawn('tar', ['-xzf', '-'], { cwd: destDir, stdio: ['pipe', 'inherit', 'inherit'] });
+ const exit = new Promise((resolve, reject) => {
+ child.once('error', reject);
+ child.once('close', (code) => (code === 0 ? resolve() : reject(new Error(`tar exited with code ${code}`))));
+ });
+ const input = pipeline(fs.createReadStream(archivePath), child.stdin);
+ try {
+ await Promise.all([input, exit]);
+ } catch (error) {
+ if (child.exitCode === null && child.signalCode === null) child.kill();
+ await Promise.allSettled([input, exit]);
+ throw error;
+ }
+}
+
+function replaceDirectory(stagingDir, destinationDir) {
+ const backupDir = `${destinationDir}.backup-${process.pid}-${Date.now()}`;
+ let backedUp = false;
+ try {
+ if (fs.existsSync(destinationDir)) {
+ fs.renameSync(destinationDir, backupDir);
+ backedUp = true;
+ }
+ fs.renameSync(stagingDir, destinationDir);
+ if (backedUp) fs.rmSync(backupDir, { recursive: true, force: true });
+ } catch (error) {
+ if (!fs.existsSync(destinationDir) && backedUp && fs.existsSync(backupDir)) {
+ try { fs.renameSync(backupDir, destinationDir); } catch { /* preserve original error */ }
+ }
+ throw error;
+ } finally {
+ try { fs.rmSync(stagingDir, { recursive: true, force: true }); } catch { /* ignore */ }
+ if (fs.existsSync(destinationDir)) {
+ try { fs.rmSync(backupDir, { recursive: true, force: true }); } catch { /* ignore */ }
+ }
+ }
+}
+
+async function downloadAsset(meta, version, platform, { force = false, throughputGuard = false } = {}) {
+ const asset = (meta.assets || []).find((candidate) => candidate.name === platform.asset);
+ if (!asset) throw new Error(`Asset not found in release: ${platform.asset} (tag ${meta.tag_name})`);
+
+ const destinationDir = path.join(UPDATES_DIR, version, platform.key);
+ if (
+ !force
+ && isPackageCacheUsable(destinationDir, version, platform)
+ && assetDigestMatchesUpstream(readCachedAssetDigest(destinationDir), asset)
+ ) {
+ const entrypointPath = path.join(destinationDir, ...platform.entrypoint.split('/'));
+ console.log(` [${platform.key}] skip (cached, package complete, digest pinned, ${formatMB(fs.statSync(entrypointPath).size)})`);
+ return;
+ }
+
+ const expectedDigest = asset.digest;
+ if (!expectedDigest) {
+ throw new Error(
+ `codex-package ${platform.key} asset ${platform.asset}@${version}: digest field absent — `
+ + 'GitHub only provides asset digests for releases published after 2025-06-03.',
+ );
+ }
+
+ fs.mkdirSync(path.dirname(destinationDir), { recursive: true });
+ const stagingDir = `${destinationDir}.staging-${process.pid}-${Date.now()}`;
+ const tempArchive = path.join(os.tmpdir(), `codex-package-${version}-${platform.key}-${Date.now()}.tar.gz`);
+ fs.rmSync(stagingDir, { recursive: true, force: true });
+ fs.mkdirSync(stagingDir, { recursive: true });
+
+ console.log(` [${platform.key}] ${asset.browser_download_url}`);
+ const progress = createDownloadProgressLogger(platform.key);
+ try {
+ try {
+ await downloadToFileWithTimeout(asset.browser_download_url, tempArchive, { headers: ghHeaders() }, {
+ onProgress: progress.onProgress,
+ minThroughputBytesPerSec: throughputGuard ? undefined : 0,
+ });
+ } finally {
+ progress.finish();
+ }
+
+ const verifiedDigest = verifyFileSha256OrRemove(
+ tempArchive,
+ expectedDigest,
+ `codex-package ${platform.key} asset ${platform.asset}@${version}`,
+ );
+ console.log(` [${platform.key}] sha256 ok`);
+
+ await extractArchive(tempArchive, stagingDir);
+ const validated = validateCodexPackageDirectory(stagingDir, {
+ version,
+ target: platform.target,
+ entrypoint: platform.entrypoint,
+ });
+ chmodPackageExecutables(validated);
+ fs.writeFileSync(entrypointHashMarker(stagingDir, platform.entrypoint), `${sha256File(validated.entrypointPath)}\n`);
+ fs.writeFileSync(path.join(stagingDir, ASSET_DIGEST_FILE), `${verifiedDigest}\n`);
+ writeDirDistManifest(stagingDir);
+ if (!verifyDirDistManifest(stagingDir)) {
+ throw new Error(`Codex package directory manifest verification failed: ${stagingDir}`);
+ }
+
+ replaceDirectory(stagingDir, destinationDir);
+ const finalEntrypoint = path.join(destinationDir, ...platform.entrypoint.split('/'));
+ console.log(` → ${finalEntrypoint} (${formatMB(fs.statSync(finalEntrypoint).size)})`);
+ } finally {
+ try { fs.rmSync(tempArchive, { force: true }); } catch { /* ignore */ }
+ try { fs.rmSync(stagingDir, { recursive: true, force: true }); } catch { /* ignore */ }
+ }
+}
+
+function promoteOnePlatform(version, platform) {
+ const sourceDir = path.join(UPDATES_DIR, version, platform.key);
+ if (!isPackageCacheUsable(sourceDir, version, platform)) {
+ console.warn(` [${platform.key}] WARN: source package missing or incomplete, skipping (${sourceDir})`);
+ return;
+ }
+
+ const destinationDir = path.join(BIN_DIR, platform.key);
+ const stagingDir = `${destinationDir}.staging-${process.pid}-${Date.now()}`;
+ try {
+ fs.mkdirSync(path.dirname(destinationDir), { recursive: true });
+ fs.rmSync(stagingDir, { recursive: true, force: true });
+ fs.cpSync(sourceDir, stagingDir, { recursive: true });
+ const validated = validateCodexPackageDirectory(stagingDir, {
+ version,
+ target: platform.target,
+ entrypoint: platform.entrypoint,
+ });
+ chmodPackageExecutables(validated);
+ fs.writeFileSync(path.join(stagingDir, '.version'), `${version}\n`);
+ writeDirDistManifest(stagingDir);
+ if (!verifyDirDistManifest(stagingDir)) {
+ throw new Error(`Promoted Codex package manifest verification failed: ${stagingDir}`);
+ }
+ replaceDirectory(stagingDir, destinationDir);
+ } catch (error) {
+ if (isTargetLockError(error)) {
+ throw new Error(
+ `[${platform.key}] target locked (probably running). Close the app and re-run.`,
+ { cause: error },
+ );
+ }
+ throw error;
+ } finally {
+ try { fs.rmSync(stagingDir, { recursive: true, force: true }); } catch { /* ignore */ }
+ }
+
+ const entrypointPath = path.join(destinationDir, ...platform.entrypoint.split('/'));
+ console.log(` [${platform.key}] → ${entrypointPath} (${formatMB(fs.statSync(entrypointPath).size)})`);
+}
+
+export function isTargetLockError(error) {
+ return error?.code === 'EBUSY' || error?.code === 'ETXTBSY' || error?.code === 'EPERM';
+}
+
+function promoteToVendorBin(version, platforms = CODEX_PACKAGE_PLATFORMS) {
+ console.log('');
+ console.log('==> Promoting to apps/codex-package-bin/ ...');
+ for (const platform of platforms) promoteOnePlatform(version, platform);
+}
+
+export function readPinnedVersion() {
+ return readCachedVersion();
+}
+
+export async function ensurePlatform({ version, platformKey, force = false }) {
+ const platform = CODEX_PACKAGE_PLATFORMS.find((candidate) => candidate.key === platformKey);
+ if (!platform) throw new Error(`Unknown platform key for codex-package: ${platformKey}`);
+ const meta = await fetchReleaseMeta(`rust-v${version}`);
+ assertPinnedRuntimeAsset(readCache(), meta, version, platform);
+ await downloadAsset(meta, version, platform, { force, throughputGuard: true });
+ promoteOnePlatform(version, platform);
+}
+
+function parseArgs(argv) {
+ const args = { version: null, force: false, platform: null };
+ for (const argument of argv) {
+ if (argument === '--force' || argument === '-f') args.force = true;
+ else if (argument.startsWith('--platform=')) args.platform = argument.slice('--platform='.length);
+ else if (argument.startsWith('--version=')) args.version = argument.slice('--version='.length);
+ else if (!argument.startsWith('-')) args.version = argument;
+ }
+ return args;
+}
+
+function resolvePlatforms(platformKey) {
+ if (!platformKey) return CODEX_PACKAGE_PLATFORMS;
+ const platform = CODEX_PACKAGE_PLATFORMS.find((candidate) => candidate.key === platformKey);
+ if (!platform) {
+ throw new Error(
+ `Unknown --platform=${platformKey} (known: ${CODEX_PACKAGE_PLATFORMS.map((candidate) => candidate.key).join(', ')})`,
+ );
+ }
+ return [platform];
+}
+
+async function main() {
+ const { version: requestedVersion, force, platform: platformKey } = parseArgs(process.argv.slice(2));
+ const targets = resolvePlatforms(platformKey);
+
+ if (requestedVersion) {
+ const tag = `rust-v${requestedVersion}`;
+ console.log(`==> Pinning codex-package to ${requestedVersion} (specified, tag=${tag})...`);
+ const meta = await fetchReleaseMeta(tag);
+ for (const platform of targets) {
+ await downloadAsset(meta, requestedVersion, platform, { force });
+ }
+ promoteToVendorBin(requestedVersion, targets);
+ saveCache(meta, requestedVersion);
+ console.log('');
+ console.log('=== Done ===');
+ console.log(`Version: ${requestedVersion}`);
+ console.log(`Output: ${path.join(UPDATES_DIR, requestedVersion)}`);
+ console.log(`Bin: ${BIN_DIR}`);
+ return;
+ }
+
+ console.log('==> Fetching latest release from GitHub (openai/codex codex-package)...');
+ const meta = await fetchReleaseMeta(null);
+ const latestVersion = versionFromTag(meta.tag_name);
+ const cachedVersion = readCachedVersion();
+ console.log(` Latest: ${latestVersion} (${meta.tag_name})`);
+ console.log(` Cached: ${cachedVersion ?? '(none)'}`);
+
+ if (
+ cachedVersion === latestVersion
+ && !force
+ && targetsExist(latestVersion, targets)
+ && targetsMatchUpstreamDigest(meta, latestVersion, targets)
+ ) {
+ saveCache(meta, latestVersion);
+ promoteToVendorBin(latestVersion, targets);
+ console.log('==> Already up to date.');
+ return;
+ }
+
+ console.log(`==> New version detected (${cachedVersion ?? 'none'} → ${latestVersion}), downloading...`);
+ for (const platform of targets) {
+ await downloadAsset(meta, latestVersion, platform, { force });
+ }
+ saveCache(meta, latestVersion);
+ promoteToVendorBin(latestVersion, targets);
+
+ console.log('');
+ console.log('=== Done ===');
+ console.log(`Version: ${latestVersion}`);
+ console.log(`Output: ${path.join(UPDATES_DIR, latestVersion)}`);
+ console.log(`Bin: ${BIN_DIR}`);
+}
+
+const isMain = import.meta.url === pathToFileURL(process.argv[1] ?? '').href;
+if (isMain) {
+ main().catch((error) => {
+ console.error(error);
+ process.exit(1);
+ });
+}