Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CodexInstallation.ts

1,020 lines40.5 KB

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