Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - Effect has no incremental digest.
2import {
3 ProviderDriverKind,
4 type ProviderInstallState,
5 type ServerProviderCompatibilityAdvisory,
6} from "@t3tools/contracts";
7import { cliArchiveTarCommand, parseChecksums } from "@t3tools/shared/cliRelease";
8import { compareSemverVersions } from "@t3tools/shared/semver";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10import { resolveCommandPath, resolveSpawnCommand } from "@t3tools/shared/shell";
11import * as Clock from "effect/Clock";
12import * as Cause from "effect/Cause";
13import * as Context from "effect/Context";
14import * as SecureRandom from "effect/crypto/SecureRandom";
15import * as Effect from "effect/Effect";
16import * as Exit from "effect/Exit";
17import * as Fiber from "effect/Fiber";
18import * as FileSystem from "effect/FileSystem";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import * as Path from "effect/Path";
22import * as Schedule from "effect/Schedule";
23import * as Schema from "effect/Schema";
24import * as Scope from "effect/Scope";
25import * as Semaphore from "effect/Semaphore";
26import * as Stream from "effect/Stream";
27import * as SubscriptionRef from "effect/SubscriptionRef";
28import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
29import { ChildProcess, ChildProcessSpawner } from "effect/process";
30import * as NodeCrypto from "node:crypto";
31import * as ServerConfig from "../config.ts";
32import { selectManagedRelease } from "./managedRelease.ts";
33import * as ModelManifest from "./ModelManifest.ts";
34
35const DRIVER = ProviderDriverKind.make("codex");
36const STAGING_STALE_AFTER_MS = 24 * 60 * 60_000;
37const UPDATE_CHECK_INTERVAL_MS = 60 * 60_000;
38const UPDATE_CHECK_TIMEOUT = "20 seconds";
39const UPSTREAM_LATEST_URL = "https://registry.npmjs.org/@openai/codex/latest";
40const UPSTREAM_RELEASES_URL = "https://github.com/openai/codex/releases/download";
41// An upstream release has no recorded size; current packages are about 160 MB.
42const UPSTREAM_MAX_ARCHIVE_BYTES = 1024 * 1024 * 1024;
43const Version = Schema.String.check(Schema.isPattern(/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/u));
44const ActiveRelease = Schema.Struct({ version: Version });
45const InstalledRelease = Schema.Struct({
46 version: Version,
47 target: Schema.String,
48 sha256: Schema.String,
49});
50const PackageManifest = Schema.Struct({
51 layoutVersion: Schema.Literal(1),
52 version: Version,
53 target: Schema.String,
54 entrypoint: Schema.String,
55});
56const LocalProbe = Schema.fromJsonString(
57 Schema.Struct({ executablePath: Schema.String, fingerprint: Schema.String, version: Version }),
58);
59const decodeLocalProbe = Schema.decodeEffect(LocalProbe);
60const encodeLocalProbe = Schema.encodeEffect(LocalProbe);
61const decodeNpmCodexPackage = Schema.decodeEffect(
62 Schema.fromJsonString(
63 Schema.Struct({ name: Schema.Literal("@openai/codex"), version: Schema.String }),
64 ),
65);
66const decodeVersion = Schema.decodeUnknownEffect(Version);
67const decodeNpmLatest = Schema.decodeUnknownEffect(Schema.Struct({ version: Version }));
68const encodeRecord = Schema.encodeEffect(Schema.fromJsonString(InstalledRelease));
69const encodeActive = Schema.encodeEffect(Schema.fromJsonString(ActiveRelease));
70export interface CodexReleaseAsset {
71 readonly version: string;
72 readonly target: string;
73 readonly url: string;
74 readonly sha256: string;
75 /** Null for an upstream release, whose package checksum is published without a size. */
76 readonly archiveBytes: number | null;
77}
78const RELEASES: Readonly<Record<string, CodexReleaseAsset>> = {
79 "darwin-arm64": {
80 version: "0.166.0",
81 target: "aarch64-apple-darwin",
82 url: "https://github.com/openai/codex/releases/download/rust-v0.166.0/codex-package-aarch64-apple-darwin.tar.gz",
83 sha256: "55a440cb579f970abe7c79ab181e54b0ea4c419be99f333bbd868eebac9c21f0",
84 archiveBytes: 165951869,
85 },
86 "darwin-x64": {
87 version: "0.166.0",
88 target: "x86_64-apple-darwin",
89 url: "https://github.com/openai/codex/releases/download/rust-v0.166.0/codex-package-x86_64-apple-darwin.tar.gz",
90 sha256: "1cb65690230be5982c654ba2655e3a3b594dce9c55b780e78bfdfeff829d7ad9",
91 archiveBytes: 180076524,
92 },
93 "linux-arm64": {
94 version: "0.166.0",
95 target: "aarch64-unknown-linux-musl",
96 url: "https://github.com/openai/codex/releases/download/rust-v0.166.0/codex-package-aarch64-unknown-linux-musl.tar.gz",
97 sha256: "7821b77dda2e6283fb1f63f3165177a271da8833e857cf673c6ca1c9db3bfcc6",
98 archiveBytes: 187370368,
99 },
100 "linux-x64": {
101 version: "0.166.0",
102 target: "x86_64-unknown-linux-musl",
103 url: "https://github.com/openai/codex/releases/download/rust-v0.166.0/codex-package-x86_64-unknown-linux-musl.tar.gz",
104 sha256: "1d44b28bc4ac9937d7d3532264baa68a507ce364956a0d4ebb856f331cdee254",
105 archiveBytes: 199694962,
106 },
107 "win32-arm64": {
108 version: "0.166.0",
109 target: "aarch64-pc-windows-msvc",
110 url: "https://github.com/openai/codex/releases/download/rust-v0.166.0/codex-package-aarch64-pc-windows-msvc.tar.gz",
111 sha256: "9383152a72f97bb5dd148493c8214e4fed38d805aa2c3297cb3739f7f130becf",
112 archiveBytes: 187024318,
113 },
114 "win32-x64": {
115 version: "0.166.0",
116 target: "x86_64-pc-windows-msvc",
117 url: "https://github.com/openai/codex/releases/download/rust-v0.166.0/codex-package-x86_64-pc-windows-msvc.tar.gz",
118 sha256: "d559bb88e74d471265857b93b7f19bc250dae527673b9191b33534478093f6bc",
119 archiveBytes: 202589789,
120 },
121};
122const resolveCodexReleaseAsset = (platform: NodeJS.Platform, arch: string) =>
123 RELEASES[`${platform}-${arch}`] ?? null;
124export class CodexInstallationError extends Schema.TaggedError<CodexInstallationError>()(
125 "CodexInstallationError",
126 {
127 operation: Schema.String,
128 detail: Schema.String,
129 cause: Schema.optional(Schema.Defect()),
130 },
131) {
132 override get message() {
133 return this.detail;
134 }
135}
136const isInstallationError = Schema.is(CodexInstallationError);
137const installationError = (operation: string, detail: string, cause?: unknown) =>
138 new CodexInstallationError({ operation, detail, ...(cause === undefined ? {} : { cause }) });
139const wrapFailure = (operation: string, detail: string) => (cause: unknown) =>
140 isInstallationError(cause) ? cause : installationError(operation, detail, cause);
141export interface CodexExecutable {
142 readonly executablePath: string;
143 readonly source: "managed" | "local";
144 readonly version: string;
145 readonly managedVersionDirectory: string | null;
146}
147interface CodexInstallationService {
148 readonly managedDirectory: string;
149 readonly resolve: () => Effect.Effect<CodexExecutable, CodexInstallationError>;
150 readonly acquire: () => Effect.Effect<CodexExecutable, CodexInstallationError, Scope.Scope>;
151 readonly compatibility: (
152 version: string,
153 ) => Effect.Effect<ServerProviderCompatibilityAdvisory | undefined>;
154 readonly start: Effect.Effect<ProviderInstallState, CodexInstallationError>;
155 readonly cancel: (
156 operationId: string,
157 ) => Effect.Effect<ProviderInstallState, CodexInstallationError>;
158 readonly state: Effect.Effect<ProviderInstallState>;
159 readonly changes: Stream.Stream<ProviderInstallState>;
160 /**
161 * Looks up OpenAI's newest Codex release, at most hourly, and offers it
162 * through `state.version` when it is newer than the managed install.
163 */
164 readonly checkForUpdate: Effect.Effect<void>;
165 readonly remove: (
166 protectedBinaryPaths?: ReadonlyArray<string>,
167 ) => Effect.Effect<void, CodexInstallationError>;
168}
169export class CodexInstallation extends Context.Service<
170 CodexInstallation,
171 CodexInstallationService
172>()("t3/provider/CodexInstallation") {
173 static readonly layer = Layer.effect(
174 CodexInstallation,
175 Effect.gen(function* () {
176 const config = yield* ServerConfig.ServerConfig;
177 return yield* makeCodexInstallation({ baseDir: config.baseDir });
178 }),
179 );
180}
181export interface CodexInstallationOptions {
182 readonly baseDir: string;
183 readonly releaseAsset?: CodexReleaseAsset | null;
184 readonly validate?: (
185 executable: CodexExecutable,
186 expectedVersion: string,
187 ) => Effect.Effect<void, CodexInstallationError, Scope.Scope>;
188}
189const isRunning = (state: ProviderInstallState) =>
190 ["downloading", "extracting", "verifying"].includes(state.phase);
191export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function* (
192 options: CodexInstallationOptions,
193) {
194 const manifestService = yield* ModelManifest.ModelManifest;
195 const fs = yield* FileSystem.FileSystem;
196 const path = yield* Path.Path;
197 const random = yield* SecureRandom.SecureRandom;
198 const http = yield* HttpClient.HttpClient;
199 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
200 const serviceScope = yield* Effect.scope;
201 const platform = yield* HostProcess.Platform;
202 const environment = yield* HostProcess.Environment;
203 const arch = yield* HostProcess.Architecture;
204 const asset =
205 options.releaseAsset === undefined
206 ? resolveCodexReleaseAsset(platform, arch)
207 : options.releaseAsset;
208 const managedDirectory = path.join(options.baseDir, "tools", "codex");
209 const activePath = path.join(managedDirectory, "active.json");
210 const localProbePath = path.join(options.baseDir, "caches", "codex-local-probe.json");
211 const executableName = platform === "win32" ? "codex.exe" : "codex";
212 const gate = yield* Semaphore.make(1);
213 const updateCheckGate = yield* Semaphore.make(1);
214 const leases = new Map<string, number>();
215 let running: { readonly operationId: string; readonly fiber: Fiber.Fiber<void> } | undefined;
216 let upstream: CodexReleaseAsset | null = null;
217 let upstreamCheckedAt: number | null = null;
218
219 // A local Codex is used as is, so only a managed install is ever updated.
220 const managedVersion = (current: ProviderInstallState) =>
221 current.source === "managed" ? current.installedVersion : null;
222 // What `start` installs next. Clients compare `version` with
223 // `installedVersion` to offer an update.
224 const offer = (installedVersion: string | null) => {
225 const release = selectManagedRelease(installedVersion, asset, upstream);
226 return {
227 version: release?.version ?? installedVersion,
228 totalBytes: release?.archiveBytes ?? null,
229 };
230 };
231
232 const state = yield* SubscriptionRef.make<ProviderInstallState>({
233 driver: DRIVER,
234 operationId: null,
235 phase: "idle",
236 downloadedBytes: 0,
237 ...offer(null),
238 installedVersion: null,
239 executablePath: null,
240 canRemove: false,
241 message: null,
242 });
243 const readRecord = Effect.fn("CodexInstallation.readRecord")(function* <A>(
244 file: string,
245 schema: Schema.Codec<A>,
246 ) {
247 const info = yield* fs.stat(file);
248 if (info.type !== "File" || Number(info.size) > 8192)
249 return yield* installationError(
250 "resolve",
251 "The managed Codex installation record is invalid. Reinstall Codex.",
252 );
253 return yield* Schema.decodeEffect(Schema.fromJsonString(schema))(
254 yield* fs.readFileString(file),
255 );
256 });
257 const fromDirectory = Effect.fn("CodexInstallation.fromDirectory")(function* (
258 directory: string,
259 version: string,
260 target: string,
261 ) {
262 const manifest = yield* readRecord(path.join(directory, "codex-package.json"), PackageManifest);
263 if (
264 manifest.version !== version ||
265 manifest.target !== target ||
266 manifest.entrypoint !== `bin/${executableName}`
267 )
268 return yield* installationError(
269 "verify",
270 "The downloaded Codex package does not match the expected release.",
271 );
272 for (const name of [
273 `bin/${executableName}`,
274 `bin/codex-code-mode-host${platform === "win32" ? ".exe" : ""}`,
275 `codex-path/rg${platform === "win32" ? ".exe" : ""}`,
276 ]) {
277 const info = yield* fs.stat(path.join(directory, name));
278 if (
279 info.type !== "File" ||
280 Number(info.size) === 0 ||
281 (platform !== "win32" && (info.mode & 0o111) === 0)
282 )
283 return yield* installationError(
284 "verify",
285 "The managed Codex package is incomplete. Reinstall Codex.",
286 );
287 }
288 return {
289 executablePath: path.join(directory, "bin", executableName),
290 source: "managed",
291 version,
292 managedVersionDirectory: directory,
293 } satisfies CodexExecutable;
294 });
295 const completedRelease = Effect.fn("CodexInstallation.completedRelease")(function* (
296 version: string,
297 ) {
298 yield* decodeVersion(version);
299 const directory = path.join(managedDirectory, version);
300 const record = yield* readRecord(
301 path.join(directory, ".install-complete.json"),
302 InstalledRelease,
303 );
304 if (record.version !== version)
305 return yield* installationError(
306 "resolve",
307 "The managed Codex installation record has the wrong version.",
308 );
309 return yield* fromDirectory(directory, version, record.target);
310 });
311 const compatibility = Effect.fn("CodexInstallation.compatibility")(function* (version: string) {
312 return ModelManifest.providerCompatibility(yield* manifestService.current, DRIVER, version);
313 });
314 const isSupported = (version: string) =>
315 compatibility(version).pipe(Effect.map((advisory) => advisory?.status === "supported"));
316 // Forgets what the manifest withdrew after it was seen. Managed resolution
317 // refuses a withdrawn install, so the pin replaces it rather than a re-check.
318 const keptInstall = Effect.fn("CodexInstallation.keptInstall")(function* (
319 installedVersion: string | null,
320 ) {
321 if (upstream && !(yield* isSupported(upstream.version))) upstream = null;
322 return installedVersion !== null && (yield* isSupported(installedVersion))
323 ? installedVersion
324 : null;
325 });
326 // npm names the latest stable release; its GitHub release lists the package
327 // checksums, so an upstream update stays SHA-256 verified.
328 const lookupUpstream = Effect.gen(function* () {
329 if (!asset) return null;
330 const latest = yield* http
331 .execute(HttpClientRequest.get(UPSTREAM_LATEST_URL))
332 .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk));
333 const { version } = yield* latest.json.pipe(Effect.flatMap(decodeNpmLatest));
334 // Managed resolution refuses anything else, so offering it would break sessions.
335 if (!(yield* isSupported(version))) return null;
336 const releaseUrl = `${UPSTREAM_RELEASES_URL}/rust-v${version}`;
337 const checksums = yield* http
338 .execute(HttpClientRequest.get(`${releaseUrl}/codex-package_SHA256SUMS`))
339 .pipe(
340 Effect.flatMap(HttpClientResponse.filterStatusOk),
341 Effect.flatMap((response) => response.text),
342 );
343 const fileName = `codex-package-${asset.target}.tar.gz`;
344 const sha256 = parseChecksums(checksums).get(fileName);
345 if (!sha256) return null;
346 return {
347 version,
348 target: asset.target,
349 url: `${releaseUrl}/${fileName}`,
350 sha256,
351 archiveBytes: null,
352 } satisfies CodexReleaseAsset;
353 });
354 // A check already in flight covers concurrent subscribers, including when it fails.
355 const checkForUpdate = updateCheckGate
356 .withPermitsIfAvailable(1)(
357 Effect.gen(function* () {
358 const now = yield* Clock.currentTimeMillis;
359 if (upstreamCheckedAt === null || now - upstreamCheckedAt >= UPDATE_CHECK_INTERVAL_MS) {
360 // A failed lookup counts too, and keeps whatever release was offered before.
361 upstreamCheckedAt = now;
362 upstream = yield* lookupUpstream.pipe(
363 Effect.timeout(UPDATE_CHECK_TIMEOUT),
364 Effect.orElseSucceed(() => upstream),
365 );
366 }
367 // A running install already published the release it is installing.
368 yield* SubscriptionRef.updateEffect(state, (current) =>
369 isRunning(current)
370 ? Effect.succeed(current)
371 : keptInstall(managedVersion(current)).pipe(
372 Effect.map((kept) => ({ ...current, ...offer(kept) })),
373 ),
374 );
375 }),
376 )
377 .pipe(Effect.ignore);
378 const resolveManaged = Effect.fn("CodexInstallation.resolveManaged")(
379 function* () {
380 const active = yield* readRecord(activePath, ActiveRelease);
381 const executable = yield* completedRelease(active.version);
382 const advisory = yield* compatibility(executable.version);
383 if (advisory?.status !== "supported")
384 return yield* installationError(
385 "resolve",
386 advisory?.message ?? "Update the managed Codex installation to continue.",
387 );
388 return executable;
389 },
390 Effect.mapError(
391 wrapFailure("resolve", "Codex is not installed in T3 Code. Install it to continue."),
392 ),
393 );
394 const acquire = Effect.fn("CodexInstallation.acquire")(function* () {
395 return yield* Effect.acquireRelease(
396 gate.withPermit(
397 resolve().pipe(
398 Effect.tap((executable) =>
399 Effect.sync(() => {
400 const key = executable.managedVersionDirectory ?? executable.executablePath;
401 leases.set(key, (leases.get(key) ?? 0) + 1);
402 }),
403 ),
404 ),
405 ),
406 (executable) =>
407 Effect.sync(() => {
408 const key = executable.managedVersionDirectory ?? executable.executablePath;
409 const remaining = (leases.get(key) ?? 1) - 1;
410 if (remaining > 0) leases.set(key, remaining);
411 else leases.delete(key);
412 }),
413 );
414 });
415 const runCommand = Effect.fn("CodexInstallation.runCommand")(function* (
416 command: string,
417 args: ReadonlyArray<string>,
418 ) {
419 const resolved = yield* resolveSpawnCommand(command, args).pipe(
420 Effect.provideService(HostProcess.Platform, platform),
421 );
422 const child = yield* spawner.spawn(
423 ChildProcess.make(resolved.command, resolved.args, { shell: resolved.shell }),
424 );
425 const [output, , exitCode] = yield* Effect.all(
426 [
427 child.stdout.pipe(Stream.decodeText(), Stream.mkString),
428 child.stderr.pipe(Stream.runDrain),
429 child.exitCode,
430 ],
431 { concurrency: "unbounded" },
432 );
433 if (exitCode !== 0)
434 return yield* installationError(
435 "verify",
436 "Could not unpack or start the downloaded Codex package.",
437 );
438 return output;
439 }, Effect.scoped);
440 // Native Codex needs its adjacent host; launchers resolve their own payloads.
441 const localKind = Effect.fn("CodexInstallation.localKind")(
442 function* (realExecutablePath: string) {
443 if (/^(?:volta-shim|mise|aqua-proxy)(?:\.exe)?$/iu.test(path.basename(realExecutablePath)))
444 return "launcher";
445 if (platform === "win32") {
446 if (path.extname(realExecutablePath).toLowerCase() !== ".exe") return "launcher";
447 for (const extension of [".bunx", ".shim"]) {
448 const marker = yield* fs
449 .stat(realExecutablePath.slice(0, -4) + extension)
450 .pipe(Effect.option);
451 if (
452 Option.isSome(marker) &&
453 marker.value.type === "File" &&
454 Number(marker.value.size) > 0
455 )
456 return "launcher";
457 }
458 } else {
459 const header = yield* fs.open(realExecutablePath, { flag: "r" }).pipe(
460 Effect.flatMap((file) => file.readAlloc(2)),
461 Effect.orElseSucceed(() => Option.none()),
462 );
463 if (Option.isSome(header) && header.value[0] === 0x23 && header.value[1] === 0x21)
464 return "launcher";
465 }
466 const info = yield* fs.stat(
467 path.join(
468 path.dirname(realExecutablePath),
469 `codex-code-mode-host${platform === "win32" ? ".exe" : ""}`,
470 ),
471 );
472 return info.type === "File" &&
473 Number(info.size) > 0 &&
474 (platform === "win32" || (info.mode & 0o111) !== 0)
475 ? "native"
476 : null;
477 },
478 Effect.scoped,
479 Effect.orElseSucceed(() => null),
480 );
481 // npm's shim (Windows) or bin symlink (POSIX) stays the same across upgrades; its package does not.
482 const npmCodexVersion = Effect.fn("CodexInstallation.npmCodexVersion")(function* (
483 executablePath: string,
484 realExecutablePath: string,
485 ) {
486 for (const manifest of [
487 path.join(path.dirname(executablePath), "node_modules", "@openai", "codex", "package.json"),
488 path.join(path.dirname(realExecutablePath), "..", "package.json"),
489 ]) {
490 const pkg = yield* fs
491 .readFileString(manifest)
492 .pipe(Effect.flatMap(decodeNpmCodexPackage), Effect.option);
493 if (Option.isSome(pkg)) return pkg.value.version;
494 }
495 return null;
496 });
497 const localCache = new Map<string, { fingerprint: string; executable: CodexExecutable | null }>();
498 const resolveLocal = Effect.fn("CodexInstallation.resolveLocal")(
499 function* () {
500 const executablePath = yield* resolveCommandPath("codex", { env: environment }).pipe(
501 Effect.provideService(HostProcess.Platform, platform),
502 Effect.provideService(FileSystem.FileSystem, fs),
503 Effect.provideService(Path.Path, path),
504 );
505 if (executablePath === null) return null;
506 // Keep launcher symlinks intact: version-manager shims dispatch by their invoked name.
507 const realExecutablePath = yield* fs.realPath(executablePath);
508 const realManaged = yield* fs.realPath(managedDirectory).pipe(Effect.option);
509 if (
510 realExecutablePath.startsWith(
511 `${Option.getOrElse(realManaged, () => managedDirectory)}${path.sep}`,
512 )
513 )
514 return null;
515 const kind = yield* localKind(realExecutablePath);
516 if (kind === null) return null;
517 // A launcher's own file cannot show a Codex switch, so only a native binary or npm's package persists.
518 const npmVersion =
519 kind === "launcher" ? yield* npmCodexVersion(executablePath, realExecutablePath) : null;
520 const persists = kind === "native" || npmVersion !== null;
521 const info = yield* fs.stat(executablePath);
522 const fingerprint = `${realExecutablePath}:${info.size}:${Option.getOrUndefined(info.mtime)?.getTime()}:${Option.getOrUndefined(info.ino)}:${npmVersion ?? ""}`;
523 const cached = localCache.get(executablePath);
524 const local = (version: string) =>
525 ({
526 executablePath,
527 source: "local",
528 version,
529 managedVersionDirectory: null,
530 }) satisfies CodexExecutable;
531 // Only successful probes persist, so a slow or failed one is retried on the next start.
532 const persisted = fs.readFileString(localProbePath).pipe(
533 Effect.flatMap(decodeLocalProbe),
534 Effect.map((record) =>
535 record.executablePath === executablePath && record.fingerprint === fingerprint
536 ? local(record.version)
537 : null,
538 ),
539 Effect.orElseSucceed(() => null),
540 );
541 const probe = Effect.gen(function* () {
542 const output = yield* runCommand(executablePath, ["--version"]);
543 const version = /^codex-cli (\d+\.\d+\.\d+)$/u.exec(output.trim())?.[1];
544 if (!version) return null;
545 yield* runCommand(executablePath, ["app-server", "--help"]);
546 if (persists)
547 yield* fs.makeDirectory(path.dirname(localProbePath), { recursive: true }).pipe(
548 Effect.andThen(encodeLocalProbe({ executablePath, fingerprint, version })),
549 Effect.flatMap((record) => fs.writeFileString(localProbePath, record)),
550 Effect.ignore,
551 );
552 return local(version);
553 }).pipe(
554 Effect.timeout("5 seconds"),
555 Effect.orElseSucceed(() => null),
556 );
557 const executable =
558 cached?.fingerprint === fingerprint
559 ? cached.executable
560 : ((yield* persisted) ?? (yield* probe));
561 localCache.set(executablePath, { fingerprint, executable });
562 if (!executable) return null;
563 const advisory = yield* compatibility(executable.version);
564 return advisory?.status === "supported" ? executable : null;
565 },
566 Effect.orElseSucceed(() => null),
567 );
568 const resolve = Effect.fn("CodexInstallation.resolve")(function* () {
569 const local = yield* resolveLocal();
570 return local ?? (yield* resolveManaged());
571 });
572 const reuseLocal = Effect.fn("CodexInstallation.reuseLocal")(function* () {
573 const local = yield* resolveLocal();
574 if (!local) return false;
575 yield* SubscriptionRef.update(
576 state,
577 (current) =>
578 ({
579 ...current,
580 phase: "succeeded",
581 source: "local",
582 operationId: null,
583 installedVersion: local.version,
584 executablePath: local.executablePath,
585 downloadedBytes: 0,
586 totalBytes: null,
587 message: null,
588 }) satisfies ProviderInstallState,
589 );
590 return true;
591 });
592 const withValidationTimeout = Effect.timeoutOrElse({
593 duration: "90 seconds",
594 orElse: () =>
595 Effect.fail(
596 installationError(
597 "verify",
598 "Codex runtime verification timed out after 90 seconds. Check this environment's server logs for startup errors, then retry installation.",
599 ),
600 ),
601 });
602 const validate =
603 options.validate ??
604 Effect.fn("CodexInstallation.validate")(
605 function* (executable: CodexExecutable, version: string) {
606 const output = yield* runCommand(executable.executablePath, ["--version"]);
607 if (output.trim() !== `codex-cli ${version}`)
608 return yield* installationError(
609 "verify",
610 "The downloaded Codex executable has the wrong version.",
611 );
612 },
613 Effect.mapError(wrapFailure("verify", "The downloaded Codex runtime could not start.")),
614 );
615 // Each update lands in its own directory. Best effort: a busy gate means a session is
616 // resolving, so the next start or update finishes the cleanup.
617 const pruneInactiveReleases = Effect.gen(function* () {
618 const active = yield* readRecord(activePath, ActiveRelease);
619 for (const entry of yield* fs.readDirectory(managedDirectory)) {
620 if (
621 entry === active.version ||
622 Option.isNone(yield* decodeVersion(entry).pipe(Effect.option))
623 )
624 continue;
625 const directory = path.join(managedDirectory, entry);
626 if (leases.has(directory)) continue;
627 yield* fs.remove(directory, { recursive: true, force: true }).pipe(Effect.ignore);
628 }
629 }).pipe(
630 gate.withPermitsIfAvailable(1),
631 Effect.ignore,
632 Effect.withSpan("CodexInstallation.pruneInactiveReleases"),
633 );
634
635 const install = Effect.fn("CodexInstallation.install")(
636 function* (release: CodexReleaseAsset) {
637 const ensureEligible = Effect.fn("CodexInstallation.ensureEligible")(function* () {
638 if (release.version !== asset?.version && !(yield* isSupported(release.version))) {
639 return yield* installationError(
640 "verify",
641 "This Codex release was withdrawn. Check for updates and try again.",
642 );
643 }
644 });
645 yield* decodeVersion(release.version);
646 yield* fs.makeDirectory(managedDirectory, { recursive: true });
647 yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove: true }));
648 const destination = path.join(managedDirectory, release.version);
649 const activate = Effect.fn("CodexInstallation.activate")(
650 function* () {
651 const executable = yield* completedRelease(release.version);
652 const temporary = yield* fs.makeTempDirectoryScoped({
653 directory: managedDirectory,
654 prefix: ".active-",
655 });
656 const pointer = path.join(temporary, "active.json");
657 yield* fs.writeFileString(pointer, yield* encodeActive({ version: release.version }), {
658 mode: 0o600,
659 flag: "wx",
660 });
661 yield* ensureEligible();
662 yield* fs.rename(pointer, activePath);
663 yield* pruneInactiveReleases;
664 yield* SubscriptionRef.update(
665 state,
666 (current) =>
667 ({
668 ...current,
669 ...offer(release.version),
670 phase: "succeeded",
671 source: "managed",
672 installedVersion: release.version,
673 executablePath: executable.executablePath,
674 message: null,
675 }) satisfies ProviderInstallState,
676 );
677 },
678 Effect.scoped,
679 Effect.uninterruptible,
680 );
681 if (yield* fs.exists(destination)) {
682 const existing = yield* completedRelease(release.version);
683 const record = yield* readRecord(
684 path.join(destination, ".install-complete.json"),
685 InstalledRelease,
686 );
687 if (record.sha256 !== release.sha256 || record.target !== release.target)
688 return yield* installationError(
689 "verify",
690 "The existing managed Codex release differs from the official package. Remove it and reinstall.",
691 );
692 yield* ensureEligible();
693 yield* validate(existing, release.version).pipe(Effect.scoped, withValidationTimeout);
694 yield* activate();
695 return;
696 }
697 const staging = yield* fs.makeTempDirectoryScoped({
698 directory: managedDirectory,
699 prefix: ".install-",
700 });
701 const archivePath = path.join(staging, "download.tar.gz");
702 const runtime = path.join(staging, "runtime");
703 yield* fs.makeDirectory(runtime);
704 const hash = NodeCrypto.createHash("sha256");
705 const maxArchiveBytes = release.archiveBytes ?? UPSTREAM_MAX_ARCHIVE_BYTES;
706 let downloadedBytes = 0;
707 let lastProgressAt = yield* Clock.currentTimeMillis;
708 const response = yield* http
709 .execute(HttpClientRequest.get(release.url))
710 .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk));
711 yield* response.stream.pipe(
712 Stream.tap((chunk) =>
713 Effect.gen(function* () {
714 downloadedBytes += chunk.byteLength;
715 if (downloadedBytes > maxArchiveBytes)
716 return yield* installationError(
717 "download",
718 "The Codex download exceeded the expected release size.",
719 );
720 hash.update(chunk);
721 const now = yield* Clock.currentTimeMillis;
722 if (now - lastProgressAt >= 250 || downloadedBytes === release.archiveBytes) {
723 lastProgressAt = now;
724 yield* SubscriptionRef.update(state, (current) => ({ ...current, downloadedBytes }));
725 }
726 }),
727 ),
728 Stream.run(fs.sink(archivePath, { flag: "wx", mode: 0o600 })),
729 Effect.timeout("45 minutes"),
730 Effect.catchTags({
731 TimeoutError: (cause) =>
732 installationError(
733 "download",
734 "The Codex download timed out. Retry installation.",
735 cause,
736 ),
737 }),
738 );
739 if (
740 (release.archiveBytes !== null && downloadedBytes !== release.archiveBytes) ||
741 hash.digest("hex") !== release.sha256
742 )
743 return yield* installationError(
744 "download",
745 "The Codex download failed its size or SHA-256 check. Nothing was installed.",
746 );
747 yield* SubscriptionRef.update(
748 state,
749 (current) =>
750 ({
751 ...current,
752 phase: "extracting",
753 message: "Extracting Codex.",
754 }) satisfies ProviderInstallState,
755 );
756 // Bare `tar` on Windows can resolve to Git's MSYS tar, which reads `C:\...` as a remote host.
757 const tarCommand = cliArchiveTarCommand(platform, environment);
758 const entries = (yield* runCommand(tarCommand, ["-tzf", archivePath])).trim().split(/\r?\n/u);
759 const types = (yield* runCommand(tarCommand, ["-tvzf", archivePath])).trim().split(/\r?\n/u);
760 if (
761 entries.length > 10000 ||
762 entries.length !== types.length ||
763 types.some((line) => !["-", "d"].includes(line[0] ?? "")) ||
764 entries.some((entry) => {
765 const parts = entry.replace(/\/$/u, "").split("/");
766 return (
767 !entry ||
768 entry.includes("\\") ||
769 entry.startsWith("/") ||
770 parts.some((part) => part === ".." || part === "." || part === "" || part.includes(":"))
771 );
772 })
773 )
774 return yield* installationError("extract", "The Codex archive contains unsafe entries.");
775 yield* runCommand(tarCommand, ["-xzf", archivePath, "-C", runtime]);
776 yield* SubscriptionRef.update(
777 state,
778 (current) =>
779 ({
780 ...current,
781 phase: "verifying",
782 message: "Checking Codex.",
783 }) satisfies ProviderInstallState,
784 );
785 const executable = yield* fromDirectory(runtime, release.version, release.target);
786 yield* ensureEligible();
787 yield* validate(executable, release.version).pipe(Effect.scoped, withValidationTimeout);
788 yield* fs.writeFileString(
789 path.join(runtime, ".install-complete.json"),
790 yield* encodeRecord({
791 version: release.version,
792 target: release.target,
793 sha256: release.sha256,
794 }),
795 { flag: "wx", mode: 0o600 },
796 );
797 // Windows Defender or process rundown may retain codex.exe handles briefly after --version exits.
798 const renameRuntime = fs.rename(runtime, destination);
799 yield* platform === "win32"
800 ? renameRuntime.pipe(Effect.retry({ times: 10, schedule: Schedule.spaced("100 millis") }))
801 : renameRuntime;
802 yield* activate();
803 },
804 Effect.scoped,
805 Effect.catchTags({
806 HttpClientError: (cause) => {
807 const httpStatus =
808 cause.reason._tag === "StatusCodeError" ? cause.reason.response.status : undefined;
809 return new CodexInstallationError({
810 operation: "download",
811 detail:
812 httpStatus === undefined
813 ? "The Codex download was interrupted. Check your internet connection, then retry installation."
814 : `The Codex download server returned HTTP ${httpStatus}. Try again later.`,
815 cause,
816 });
817 },
818 }),
819 Effect.mapError(
820 wrapFailure(
821 "install",
822 "Could not install Codex. Check disk space and directory access, then try again.",
823 ),
824 ),
825 );
826 // Nothing newer is known, so "reinstall" re-checks the active runtime rather
827 // than replacing it with an older pinned release.
828 const reverify = Effect.fn("CodexInstallation.reverify")(
829 function* () {
830 const active = yield* readRecord(activePath, ActiveRelease);
831 const executable = yield* completedRelease(active.version);
832 yield* validate(executable, executable.version).pipe(Effect.scoped, withValidationTimeout);
833 const kept = yield* keptInstall(executable.version);
834 if (kept === null) {
835 yield* SubscriptionRef.update(state, (current) => ({ ...current, ...offer(kept) }));
836 return yield* installationError(
837 "verify",
838 "This Codex release was withdrawn. Check for updates and try again.",
839 );
840 }
841 yield* SubscriptionRef.update(
842 state,
843 (current) =>
844 ({
845 ...current,
846 ...offer(kept),
847 phase: "succeeded",
848 source: "managed",
849 installedVersion: executable.version,
850 executablePath: executable.executablePath,
851 message: null,
852 }) satisfies ProviderInstallState,
853 );
854 },
855 Effect.mapError(
856 wrapFailure(
857 "verify",
858 "The installed Codex runtime could not start. Remove it and reinstall.",
859 ),
860 ),
861 );
862 const start = gate
863 .withPermit(
864 Effect.gen(function* () {
865 const current = yield* SubscriptionRef.get(state);
866 if (isRunning(current)) return current;
867 if (yield* reuseLocal()) return yield* SubscriptionRef.get(state);
868 const installedVersion = yield* keptInstall(managedVersion(current));
869 const release = selectManagedRelease(installedVersion, asset, upstream);
870 if (!release && installedVersion === null) {
871 return yield* installationError(
872 "start",
873 `OpenAI does not publish a Codex runtime for ${platform}-${arch}. Use a supported remote environment or a custom executable.`,
874 );
875 }
876 const operationId = yield* random.uuidV4();
877 const next: ProviderInstallState = {
878 ...current,
879 operationId,
880 phase: release ? "downloading" : "verifying",
881 downloadedBytes: 0,
882 ...offer(installedVersion),
883 message: release ? "Downloading Codex." : "Checking Codex.",
884 };
885 yield* SubscriptionRef.set(state, next);
886 const work = (release ? install(release) : reverify()).pipe(
887 Effect.onExit((exit) =>
888 Exit.isFailure(exit)
889 ? SubscriptionRef.update(state, (value) => {
890 if (value.operationId !== operationId || value.phase === "succeeded")
891 return value;
892 const error = Cause.findErrorOption(exit.cause);
893 const cancelled = Cause.hasInterruptsOnly(exit.cause);
894 return {
895 ...value,
896 phase: cancelled ? "cancelled" : "failed",
897 message: cancelled
898 ? "Installation cancelled. The previous runtime is unchanged."
899 : Option.isSome(error)
900 ? error.value.detail
901 : "Could not finish the Codex installation. Check disk space and directory access.",
902 } satisfies ProviderInstallState;
903 })
904 : Effect.void,
905 ),
906 Effect.ignoreCause,
907 Effect.ensuring(
908 Effect.sync(() => {
909 if (running?.operationId === operationId) running = undefined;
910 }),
911 ),
912 );
913 const fiber = yield* Effect.forkIn(Effect.interruptible(work), serviceScope);
914 running = { operationId, fiber };
915 return next;
916 }).pipe(Effect.uninterruptible),
917 )
918 .pipe(Effect.mapError(wrapFailure("start", "Could not start the Codex installation.")));
919
920 const cancel = Effect.fn("CodexInstallation.cancel")(function* (operationId: string) {
921 return yield* gate.withPermit(
922 Effect.gen(function* () {
923 const current = yield* SubscriptionRef.get(state);
924 if (current.operationId !== operationId) {
925 return yield* installationError(
926 "cancel",
927 "This installation is no longer current. Refresh its status before cancelling.",
928 );
929 }
930 if (running?.operationId === operationId && isRunning(current)) {
931 yield* Fiber.interrupt(running.fiber);
932 }
933 return yield* SubscriptionRef.get(state);
934 }),
935 );
936 });
937
938 const remove = Effect.fn("CodexInstallation.remove")(
939 function* (protectedBinaryPaths: ReadonlyArray<string> = []) {
940 yield* gate.withPermit(
941 Effect.gen(function* () {
942 if (isRunning(yield* SubscriptionRef.get(state)) || leases.size > 0) {
943 return yield* installationError(
944 "remove",
945 "Stop Codex sessions and sign-in flows before removing its managed runtime.",
946 );
947 }
948 const realManaged = yield* fs.realPath(managedDirectory).pipe(Effect.option);
949 if (Option.isSome(realManaged)) {
950 for (const binary of protectedBinaryPaths) {
951 const resolved = yield* fs.realPath(binary).pipe(Effect.option);
952 const candidate = Option.getOrElse(resolved, () => path.resolve(binary));
953 if (candidate.startsWith(`${realManaged.value}${path.sep}`))
954 return yield* installationError(
955 "remove",
956 "A provider instance uses a custom path inside managed Codex. Clear that path before removing it.",
957 );
958 }
959 }
960 yield* fs.remove(managedDirectory, { recursive: true, force: true });
961 yield* SubscriptionRef.update(
962 state,
963 (current) =>
964 ({
965 ...current,
966 ...offer(null),
967 operationId: null,
968 phase: "idle",
969 downloadedBytes: 0,
970 installedVersion: null,
971 executablePath: null,
972 source: null,
973 canRemove: false,
974 message: null,
975 }) satisfies ProviderInstallState,
976 );
977 yield* reuseLocal();
978 }).pipe(Effect.uninterruptible),
979 );
980 },
981 Effect.mapError(
982 wrapFailure(
983 "remove",
984 "Could not remove the managed Codex runtime. Check for open processes and try again.",
985 ),
986 ),
987 );
988
989 yield* Effect.gen(function* () {
990 // Shared-home installs do not refresh parent mtimes; remove only staging directories far older than the 45-minute download cap.
991 let canRemove = false;
992 if (yield* fs.exists(managedDirectory)) {
993 const entries = yield* fs
994 .readDirectory(managedDirectory)
995 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
996 const now = yield* Clock.currentTimeMillis;
997 for (const entry of entries) {
998 if (!entry.startsWith(".install-") && !entry.startsWith(".active-")) continue;
999 const target = path.join(managedDirectory, entry);
1000 const info = yield* fs.stat(target).pipe(Effect.option);
1001 if (Option.isNone(info)) continue;
1002 const modifiedAt = Option.match(info.value.mtime, {
1003 onNone: () => now,
1004 onSome: (date) => date.getTime(),
1005 });
1006 if (now - modifiedAt < STAGING_STALE_AFTER_MS) continue;
1007 yield* fs.remove(target, { recursive: true, force: true }).pipe(Effect.ignore);
1008 }
1009 // Keep the empty root to avoid racing new staging directories; unreadable roots remain removable.
1010 const remaining = yield* fs.readDirectory(managedDirectory).pipe(Effect.option);
1011 canRemove = Option.isNone(remaining) || remaining.value.length > 0;
1012 }
1013 yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove }));
1014 if (yield* reuseLocal()) return;
1015 if (!(yield* fs.exists(activePath))) return;
1016 const active = yield* readRecord(activePath, ActiveRelease);
1017 const installed = yield* completedRelease(active.version);
1018 const kept = yield* keptInstall(installed.version);
1019 yield* SubscriptionRef.update(
1020 state,
1021 (current) =>
1022 ({
1023 ...current,
1024 ...offer(kept),
1025 installedVersion: installed.version,
1026 executablePath: installed.executablePath,
1027 source: "managed",
1028 }) satisfies ProviderInstallState,
1029 );
1030 // A supported older runtime still resolves, so a raised pin needs its own update.
1031 if (asset && compareSemverVersions(installed.version, asset.version) < 0)
1032 yield* start.pipe(Effect.ignore);
1033 }).pipe(
1034 Effect.catch(() =>
1035 SubscriptionRef.update(
1036 state,
1037 (current) =>
1038 ({
1039 ...current,
1040 phase: "failed",
1041 message: "The managed Codex runtime is incomplete. Remove it and reinstall.",
1042 }) satisfies ProviderInstallState,
1043 ),
1044 ),
1045 );
1046
1047 // A startup install prunes when it activates; pruning now could delete the release it is verifying.
1048 if (!isRunning(yield* SubscriptionRef.get(state))) yield* pruneInactiveReleases;
1049
1050 return CodexInstallation.of({
1051 managedDirectory,
1052 resolve,
1053 acquire,
1054 compatibility,
1055 start,
1056 cancel,
1057 state: SubscriptionRef.get(state),
1058 changes: SubscriptionRef.changes(state),
1059 checkForUpdate,
1060 remove,
1061 });
1062});