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

CodexInstallation.ts

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