-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathrebuild_codex.js
More file actions
416 lines (356 loc) · 15.6 KB
/
rebuild_codex.js
File metadata and controls
416 lines (356 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const os = require('os');
// Configuration
const REPO_ROOT = __dirname;
const MOUNT_POINT = '/Volumes/CodexMount';
const DMG_PATH = path.join(REPO_ROOT, 'Codex.dmg');
const TEMP_DIR = path.join(REPO_ROOT, 'temp_build');
const FINAL_APP_PATH = path.join(REPO_ROOT, 'Codex_Intel.app');
const RESOURCES_DIR = path.join(REPO_ROOT, 'resources');
// detect CODEX_CLI_PATH dynamically
let CODEX_CLI_PATH = '/usr/local/lib/node_modules/@openai/codex';
try {
const globalRoot = execSync('npm root -g', { encoding: 'utf8' }).trim();
const possiblePath = path.join(globalRoot, '@openai/codex');
if (fs.existsSync(possiblePath)) {
CODEX_CLI_PATH = possiblePath;
console.log(`Detected Codex CLI at: ${CODEX_CLI_PATH}`);
} else {
console.log(`Could not find @openai/codex at ${possiblePath}, using default: ${CODEX_CLI_PATH}`);
}
} catch (e) {
console.warn("Could not auto-detect npm root. Using default path.");
}
// Helper for executing commands
function run(cmd, cwd = REPO_ROOT) {
console.log(`> ${cmd}`);
try {
execSync(cmd, { cwd, stdio: 'inherit' });
} catch (e) {
console.error(`Command failed: ${cmd}`);
process.exit(1);
}
}
async function main() {
// Handle --clean flag
const cleanBuild = process.argv.includes('--clean');
if (cleanBuild) {
console.log("Clean build requested. Removing cached/transient files...");
const toRemove = [
RESOURCES_DIR,
TEMP_DIR,
path.join(REPO_ROOT, 'native_build_temp'),
FINAL_APP_PATH,
path.join(REPO_ROOT, 'package.json'),
];
// Also remove any cached electron zips
const electronZips = fs.readdirSync(REPO_ROOT).filter(f => f.startsWith('electron-') && f.endsWith('.zip'));
electronZips.forEach(f => toRemove.push(path.join(REPO_ROOT, f)));
for (const p of toRemove) {
if (fs.existsSync(p)) {
console.log(` Removing ${path.basename(p)}`);
fs.rmSync(p, { recursive: true, force: true });
}
}
console.log("Clean complete.\n");
}
console.log("Starting Codex Rebuilder...");
// 1. Prepare Resources (Mount DMG if needed)
if (!fs.existsSync(RESOURCES_DIR)) {
fs.mkdirSync(RESOURCES_DIR);
}
const requiredResources = [
'app.asar',
'electron.icns',
'Info.plist'
];
// Check if we have resources locally
const missingResources = requiredResources.filter(r => !fs.existsSync(path.join(RESOURCES_DIR, r)));
if (missingResources.length > 0) {
console.log(`Missing resources (${missingResources.join(', ')}). Mounting DMG...`);
let mounted = false;
if (!fs.existsSync(MOUNT_POINT)) {
// Check if already mounted by user?
try {
// Try to mount
run(`hdiutil attach "${DMG_PATH}" -nobrowse -mountpoint "${MOUNT_POINT}"`);
mounted = true;
} catch (e) {
console.log("Mount failed or already mounted. Checking...");
}
} else {
console.log("Mount point exists, assuming mounted.");
mounted = true;
// If strictly it's just a folder, we might fail, but let's assume valid mount or previous run leftover
}
try {
const appPath = path.join(MOUNT_POINT, 'Codex.app/Contents');
const resPath = path.join(appPath, 'Resources');
if (fs.existsSync(path.join(resPath, 'app.asar'))) {
// Copy app.asar
if (!fs.existsSync(path.join(RESOURCES_DIR, 'app.asar'))) {
console.log("Extracting app.asar...");
run(`cp "${path.join(resPath, 'app.asar')}" "${path.join(RESOURCES_DIR, 'app.asar')}"`);
}
// Copy electron.icns
if (!fs.existsSync(path.join(RESOURCES_DIR, 'electron.icns'))) {
console.log("Extracting electron.icns...");
run(`cp "${path.join(resPath, 'electron.icns')}" "${path.join(RESOURCES_DIR, 'electron.icns')}"`);
}
// Copy Info.plist
if (!fs.existsSync(path.join(RESOURCES_DIR, 'Info.plist'))) {
console.log("Extracting Info.plist...");
run(`cp "${path.join(appPath, 'Info.plist')}" "${path.join(RESOURCES_DIR, 'Info.plist')}"`);
}
// Copy app.asar.unpacked structure
if (!fs.existsSync(path.join(RESOURCES_DIR, 'app.asar.unpacked'))) {
console.log("Extracting app.asar.unpacked...");
if (fs.existsSync(path.join(resPath, 'app.asar.unpacked'))) {
run(`cp -r "${path.join(resPath, 'app.asar.unpacked')}" "${path.join(RESOURCES_DIR, 'app.asar.unpacked')}"`);
} else {
fs.mkdirSync(path.join(RESOURCES_DIR, 'app.asar.unpacked'));
}
}
} else {
throw new Error("Could not find Codex.app/Contents/Resources/app.asar in DMG");
}
} finally {
if (mounted) {
// Try to detach, don't fail if busy
try {
run(`hdiutil detach "${MOUNT_POINT}"`);
} catch (e) {
console.warn("Failed to unmount, ignoring.");
}
}
}
}
// 2. Read Electron Version from extracted app.asar
console.log("Reading Electron version...");
const localAppAsar = path.join(RESOURCES_DIR, 'app.asar');
const pkgJsonPath = path.join(REPO_ROOT, 'package.json');
// We only extract if we haven't already or if we want to force check
run(`npx -y @electron/asar extract-file "${localAppAsar}" package.json > "${pkgJsonPath}"`);
if (!fs.existsSync(pkgJsonPath)) {
console.error("Failed to extract package.json");
process.exit(1);
}
const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8'));
let electronVersion = pkg.devDependencies?.electron || pkg.dependencies?.electron;
if (!electronVersion) {
console.log("Could not find electron version, defaulting to 40.0.0 based on previous analysis.");
electronVersion = '40.0.0';
}
// Clean version (remove ^ or ~)
electronVersion = electronVersion.replace(/^[\^~]/, '');
console.log(`Target Electron Version: ${electronVersion}`);
// 3. Download Electron x64
if (fs.existsSync(TEMP_DIR)) {
fs.rmSync(TEMP_DIR, { recursive: true, force: true });
}
fs.mkdirSync(TEMP_DIR);
const zipName = `electron-v${electronVersion}-darwin-x64.zip`;
const downloadUrl = `https://github.com/electron/electron/releases/download/v${electronVersion}/${zipName}`;
const zipPath = path.join(REPO_ROOT, zipName); // Cache zip in root
if (!fs.existsSync(zipPath)) {
console.log(`Downloading ${downloadUrl}...`);
run(`curl -L -o "${zipPath}" "${downloadUrl}"`);
} else {
console.log("Using cached Electron zip.");
}
// 4. Extract Electron
console.log("Extracting Electron...");
run(`unzip "${zipPath}" -d "${TEMP_DIR}"`);
// 5. Assemble Codex App
console.log("Assembling Codex.app...");
const electronApp = path.join(TEMP_DIR, 'Electron.app');
const targetApp = FINAL_APP_PATH;
if (fs.existsSync(targetApp)) {
fs.rmSync(targetApp, { recursive: true, force: true });
}
run(`mv "${electronApp}" "${targetApp}"`);
// Replace Resources
const targetResources = path.join(targetApp, 'Contents/Resources');
const defaultAsar = path.join(targetResources, 'default_app.asar');
if (fs.existsSync(defaultAsar)) {
fs.unlinkSync(defaultAsar);
}
fs.copyFileSync(localAppAsar, path.join(targetResources, 'app.asar'));
// Copy Icon
const localIcon = path.join(RESOURCES_DIR, 'electron.icns');
if (fs.existsSync(localIcon)) {
console.log("Applying custom App Icon...");
// Destination might be electron.icns or whatever Info.plist specifies
// We know from previous steps it expects 'electron.icns'
fs.copyFileSync(localIcon, path.join(targetResources, 'electron.icns'));
}
// 6. Native Modules Replacement
console.log("Handling native modules...");
const targetUnpacked = path.join(targetResources, 'app.asar.unpacked');
// Copy extracted unpacked folder from resources
const localUnpacked = path.join(RESOURCES_DIR, 'app.asar.unpacked');
if (fs.existsSync(localUnpacked)) {
run(`cp -r "${localUnpacked}" "${targetUnpacked}"`);
} else {
fs.mkdirSync(targetUnpacked, { recursive: true });
}
// Fix Rebuild needed modules
console.log("Rebuilding native modules (better-sqlite3, node-pty) for Electron x64...");
const tempBuildDir = path.join(REPO_ROOT, 'native_build_temp');
if (fs.existsSync(tempBuildDir)) {
fs.rmSync(tempBuildDir, { recursive: true, force: true });
}
fs.mkdirSync(tempBuildDir);
const nativePkg = {
"name": "temp-build",
"dependencies": {
"better-sqlite3": pkg.dependencies['better-sqlite3'],
"node-pty": pkg.dependencies['node-pty']
}
};
fs.writeFileSync(path.join(tempBuildDir, 'package.json'), JSON.stringify(nativePkg, null, 2));
const env = {
...process.env,
npm_config_target: electronVersion,
npm_config_arch: 'x64',
npm_config_target_arch: 'x64',
npm_config_dist_url: 'https://electronjs.org/headers',
npm_config_runtime: 'electron',
npm_config_build_from_source: 'true',
// Force C++20 for Electron 40 compatibility (fixes source_location error)
CXXFLAGS: '-std=c++20 -stdlib=libc++'
};
console.log("Running npm install with electron environment...");
try {
execSync(`npm install --no-bin-links --force`, { cwd: tempBuildDir, env, stdio: 'inherit' });
} catch (e) {
console.error("Build failed, continuing carefully...");
}
// Copy built modules
const bs3Src = path.join(tempBuildDir, 'node_modules/better-sqlite3');
const bs3Dest = path.join(targetUnpacked, 'node_modules/better-sqlite3');
if (fs.existsSync(bs3Dest)) {
fs.rmSync(bs3Dest, { recursive: true, force: true });
}
// Check if source exists
if (fs.existsSync(bs3Src)) {
run(`cp -r "${bs3Src}" "${bs3Dest}"`);
}
const ptySrc = path.join(tempBuildDir, 'node_modules/node-pty');
const ptyDest = path.join(targetUnpacked, 'node_modules/node-pty');
if (fs.existsSync(ptyDest)) {
fs.rmSync(ptyDest, { recursive: true, force: true });
}
if (fs.existsSync(ptySrc)) {
run(`cp -r "${ptySrc}" "${ptyDest}"`);
}
console.log("Native modules updated.");
// Config Info.plist and Executable
console.log("Configuring Info.plist and Executable...");
const infoPlistDest = path.join(targetApp, 'Contents/Info.plist');
const localInfoPlist = path.join(RESOURCES_DIR, 'Info.plist');
if (fs.existsSync(localInfoPlist)) {
fs.copyFileSync(localInfoPlist, infoPlistDest);
}
const macOsDir = path.join(targetApp, 'Contents/MacOS');
const electronBin = path.join(macOsDir, 'Electron');
const codexOrigBin = path.join(macOsDir, 'Codex.orig');
const codexWrapper = path.join(macOsDir, 'Codex');
if (fs.existsSync(electronBin)) {
// Rename the real binary to Codex.orig
fs.renameSync(electronBin, codexOrigBin);
// Create a wrapper script that launches with --no-sandbox
const wrapperScript = `#!/bin/bash
DIR="$(cd "$(dirname "$0")" && pwd)"
exec "$DIR/Codex.orig" --no-sandbox "$@"
`;
fs.writeFileSync(codexWrapper, wrapperScript);
fs.chmodSync(codexWrapper, '755');
console.log("Created --no-sandbox wrapper script at " + codexWrapper);
} else {
console.warn("Electron binary not found at checked path: " + electronBin);
}
// 7. Copy Codex Binary
console.log("Copying Codex x64 binary...");
// Dynamically find codex binary inside CLI path
let sourceCodexBin = null;
try {
const findCodex = execSync(`find "${CODEX_CLI_PATH}" -name codex -type f | grep "x86_64" | head -n 1`, { encoding: 'utf8' }).trim();
if (findCodex && fs.existsSync(findCodex)) {
sourceCodexBin = findCodex;
}
} catch (e) {
console.warn("Error searching for codex binary:", e.message);
}
if (sourceCodexBin) {
const targetCodexBin = path.join(targetResources, 'codex');
console.log(`Copying ${sourceCodexBin} to ${targetCodexBin}`);
fs.copyFileSync(sourceCodexBin, targetCodexBin);
fs.chmodSync(targetCodexBin, '755');
const binDir = path.join(targetResources, 'bin');
if (!fs.existsSync(binDir)) {
fs.mkdirSync(binDir);
}
const targetBinCodex = path.join(binDir, 'codex');
fs.copyFileSync(sourceCodexBin, targetBinCodex);
fs.chmodSync(targetBinCodex, '755');
// Copy rg (ripgrep)
let sourceRgBin = null;
try {
// Find 'rg' binary inside CLI path, prioritize x86_64
const findRg = execSync(`find "${CODEX_CLI_PATH}" -name rg -type f | grep "x86_64" | head -n 1`, { encoding: 'utf8' }).trim();
if (findRg && fs.existsSync(findRg)) {
sourceRgBin = findRg;
}
} catch (e) {
console.warn("Error searching for rg binary:", e.message);
}
if (sourceRgBin) {
const targetBinRg = path.join(binDir, 'rg');
console.log(`Copying ${sourceRgBin} to ${targetBinRg}`);
fs.copyFileSync(sourceRgBin, targetBinRg);
fs.chmodSync(targetBinRg, '755');
// Also copy to root resources if needed (mirroring codex behavior just in case)
const targetRgResource = path.join(targetResources, 'rg');
fs.copyFileSync(sourceRgBin, targetRgResource);
fs.chmodSync(targetRgResource, '755');
} else {
console.warn(`WARNING: Could not find local x86_64 rg binary in ${CODEX_CLI_PATH}`);
}
} else {
console.warn(`WARNING: Could not find local x64 Codex binary. Checked: ${potentialCodexPaths.join(', ')}`);
}
// 8. Fix Timestamps
console.log("Fixing app timestamps...");
run(`touch "${targetApp}"`);
// Fix creation date using SetFile if available (macOS specific)
try {
const now = new Date();
// Format: MM/DD/YYYY hh:mm:ss
const p = (n) => n.toString().padStart(2, '0');
const dateStr = `${p(now.getMonth() + 1)}/${p(now.getDate())}/${now.getFullYear()} ${p(now.getHours())}:${p(now.getMinutes())}:${p(now.getSeconds())}`;
console.log(`Setting creation date to ${dateStr}...`);
execSync(`SetFile -d "${dateStr}" "${targetApp}"`, { stdio: 'inherit' });
} catch (e) {
console.warn("SetFile failed or not available (this is normal on non-macOS or minimal envs). Creation date might be old.");
}
// 9. Cleanup temp files
console.log("Cleaning up temporary files...");
for (const dir of [TEMP_DIR, tempBuildDir]) {
if (fs.existsSync(dir)) {
fs.rmSync(dir, { recursive: true, force: true });
}
}
// Remove extracted package.json
const extractedPkgJson = path.join(REPO_ROOT, 'package.json');
if (fs.existsSync(extractedPkgJson)) {
fs.unlinkSync(extractedPkgJson);
}
console.log("Done! Codex_Intel.app is ready at " + targetApp);
}
main().catch(err => {
console.error(err);
process.exit(1);
});