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

CodexInstallation.ts

805 lines31.1 KB

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