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