Open History to see the last commit
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;
54}
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};
99export const 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 }
112}
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;
123}
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>;
137}
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 );
149}
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>;
157}
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.decodeUnknownEffect(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 const localCache = new Map<string, { fingerprint: string; executable: CodexExecutable | null }>();
333 const resolveLocal = Effect.fn("CodexInstallation.resolveLocal")(
334 function* () {
335 const executablePath = yield* resolveCommandPath("codex", { env: environment }).pipe(
336 Effect.provideService(HostProcess.Platform, platform),
337 Effect.provideService(FileSystem.FileSystem, fs),
338 Effect.provideService(Path.Path, path),
339 );
340 if (executablePath === null) return null;
341 // Keep launcher symlinks intact: version-manager shims dispatch by their invoked name.
342 const realExecutablePath = yield* fs.realPath(executablePath);
343 const realManaged = yield* fs.realPath(managedDirectory).pipe(Effect.option);
344 if (
345 realExecutablePath.startsWith(
346 `${Option.getOrElse(realManaged, () => managedDirectory)}${path.sep}`,
347 )
348 )
349 return null;
350 const info = yield* fs.stat(executablePath);
351 const fingerprint = `${realExecutablePath}:${info.size}:${Option.getOrUndefined(info.mtime)?.getTime()}:${Option.getOrUndefined(info.ino)}`;
352 const cached = localCache.get(executablePath);
353 const executable =
354 cached?.fingerprint === fingerprint
355 ? cached.executable
356 : yield* Effect.gen(function* () {
357 const output = yield* runCommand(executablePath, ["--version"]);
358 const version = /^codex-cli (\d+\.\d+\.\d+)$/u.exec(output.trim())?.[1];
359 if (!version) return null;
360 yield* runCommand(executablePath, ["app-server", "--help"]);
361 return {
362 executablePath,
363 source: "local",
364 version,
365 managedVersionDirectory: null,
366 } satisfies CodexExecutable;
367 }).pipe(
368 Effect.timeout("5 seconds"),
369 Effect.orElseSucceed(() => null),
370 );
371 localCache.set(executablePath, { fingerprint, executable });
372 if (!executable) return null;
373 const advisory = yield* compatibility(executable.version);
374 return advisory?.status === "supported" ? executable : null;
375 },
376 Effect.orElseSucceed(() => null),
377 );
378 const resolve = Effect.fn("CodexInstallation.resolve")(function* () {
379 const local = yield* resolveLocal();
380 return local ?? (yield* resolveManaged());
381 });
382 const reuseLocal = Effect.fn("CodexInstallation.reuseLocal")(function* () {
383 const local = yield* resolveLocal();
384 if (!local) return false;
385 yield* SubscriptionRef.update(
386 state,
387 (current) =>
388 ({
389 ...current,
390 phase: "succeeded",
391 source: "local",
392 operationId: null,
393 installedVersion: local.version,
394 executablePath: local.executablePath,
395 downloadedBytes: 0,
396 totalBytes: null,
397 message: null,
398 }) satisfies ProviderInstallState,
399 );
400 return true;
401 });
402 const validate =
403 options.validate ??
404 Effect.fn("CodexInstallation.validate")(
405 function* (executable: CodexExecutable, version: string) {
406 const output = yield* runCommand(executable.executablePath, ["--version"]);
407 if (output.trim() !== `codex-cli ${version}`)
408 return yield* installationError(
409 "verify",
410 "The downloaded Codex executable has the wrong version.",
411 );
412 },
413 Effect.mapError(wrapFailure("verify", "The downloaded Codex runtime could not start.")),
414 );
415 const install = Effect.fn("CodexInstallation.install")(
416 function* (release: CodexReleaseAsset) {
417 yield* decodeVersion(release.version);
418 yield* fs.makeDirectory(managedDirectory, { recursive: true });
419 yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove: true }));
420 const destination = path.join(managedDirectory, release.version);
421 const activate = Effect.fn("CodexInstallation.activate")(
422 function* () {
423 const executable = yield* completedRelease(release.version);
424 const temporary = yield* fs.makeTempDirectoryScoped({
425 directory: managedDirectory,
426 prefix: ".active-",
427 });
428 const pointer = path.join(temporary, "active.json");
429 yield* fs.writeFileString(pointer, yield* encodeActive({ version: release.version }), {
430 mode: 0o600,
431 flag: "wx",
432 });
433 yield* fs.rename(pointer, activePath);
434 yield* SubscriptionRef.update(
435 state,
436 (current) =>
437 ({
438 ...current,
439 phase: "succeeded",
440 source: "managed",
441 installedVersion: release.version,
442 executablePath: executable.executablePath,
443 message: null,
444 }) satisfies ProviderInstallState,
445 );
446 },
447 Effect.scoped,
448 Effect.uninterruptible,
449 );
450 if (yield* fs.exists(destination)) {
451 const existing = yield* completedRelease(release.version);
452 const record = yield* readRecord(
453 path.join(destination, ".install-complete.json"),
454 InstalledRelease,
455 );
456 if (record.sha256 !== release.sha256 || record.target !== release.target)
457 return yield* installationError(
458 "verify",
459 "The existing managed Codex release differs from the official package. Remove it and reinstall.",
460 );
461 yield* validate(existing, release.version).pipe(
462 Effect.scoped,
463 Effect.timeout("90 seconds"),
464 );
465 yield* activate();
466 return;
467 }
468 const staging = yield* fs.makeTempDirectoryScoped({
469 directory: managedDirectory,
470 prefix: ".install-",
471 });
472 const archivePath = path.join(staging, "download.tar.gz");
473 const runtime = path.join(staging, "runtime");
474 yield* fs.makeDirectory(runtime);
475 const hash = NodeCrypto.createHash("sha256");
476 let downloadedBytes = 0;
477 let lastProgressAt = yield* Clock.currentTimeMillis;
478 const response = yield* http
479 .execute(HttpClientRequest.get(release.url))
480 .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk));
481 yield* response.stream.pipe(
482 Stream.tap((chunk) =>
483 Effect.gen(function* () {
484 downloadedBytes += chunk.byteLength;
485 if (downloadedBytes > release.archiveBytes)
486 return yield* installationError(
487 "download",
488 "The Codex download exceeded the expected release size.",
489 );
490 hash.update(chunk);
491 const now = yield* Clock.currentTimeMillis;
492 if (now - lastProgressAt >= 250 || downloadedBytes === release.archiveBytes) {
493 lastProgressAt = now;
494 yield* SubscriptionRef.update(state, (current) => ({ ...current, downloadedBytes }));
495 }
496 }),
497 ),
498 Stream.run(fs.sink(archivePath, { flag: "wx", mode: 0o600 })),
499 Effect.timeout("45 minutes"),
500 );
501 if (downloadedBytes !== release.archiveBytes || hash.digest("hex") !== release.sha256)
502 return yield* installationError(
503 "download",
504 "The Codex download failed its size or SHA-256 check. Nothing was installed.",
505 );
506 yield* SubscriptionRef.update(
507 state,
508 (current) =>
509 ({
510 ...current,
511 phase: "extracting",
512 message: "Extracting Codex.",
513 }) satisfies ProviderInstallState,
514 );
515 // Bare `tar` on Windows can resolve to Git's MSYS tar, which reads `C:\...` as a remote host.
516 const tarCommand = cliArchiveTarCommand(platform, environment);
517 const entries = (yield* runCommand(tarCommand, ["-tzf", archivePath])).trim().split(/\r?\n/u);
518 const types = (yield* runCommand(tarCommand, ["-tvzf", archivePath])).trim().split(/\r?\n/u);
519 if (
520 entries.length > 10000 ||
521 entries.length !== types.length ||
522 types.some((line) => !["-", "d"].includes(line[0] ?? "")) ||
523 entries.some((entry) => {
524 const parts = entry.replace(/\/$/u, "").split("/");
525 return (
526 !entry ||
527 entry.includes("\\") ||
528 entry.startsWith("/") ||
529 parts.some((part) => part === ".." || part === "." || part === "" || part.includes(":"))
530 );
531 })
532 )
533 return yield* installationError("extract", "The Codex archive contains unsafe entries.");
534 yield* runCommand(tarCommand, ["-xzf", archivePath, "-C", runtime]);
535 yield* SubscriptionRef.update(
536 state,
537 (current) =>
538 ({
539 ...current,
540 phase: "verifying",
541 message: "Checking Codex.",
542 }) satisfies ProviderInstallState,
543 );
544 const executable = yield* fromDirectory(runtime, release.version, release.target);
545 yield* validate(executable, release.version).pipe(
546 Effect.scoped,
547 Effect.timeout("90 seconds"),
548 );
549 yield* fs.writeFileString(
550 path.join(runtime, ".install-complete.json"),
551 yield* encodeRecord({
552 version: release.version,
553 target: release.target,
554 sha256: release.sha256,
555 }),
556 { flag: "wx", mode: 0o600 },
557 );
558 // On Windows, Defender and kernel process rundown can briefly hold the
559 // verified codex.exe handle open right after `--version` exits.
560 const renameRuntime = fs.rename(runtime, destination);
561 yield* platform === "win32"
562 ? renameRuntime.pipe(Effect.retry({ times: 10, schedule: Schedule.spaced("100 millis") }))
563 : renameRuntime;
564 yield* activate();
565 },
566 Effect.scoped,
567 Effect.mapError(
568 wrapFailure(
569 "install",
570 "Could not install Codex. Check disk space and directory access, then try again.",
571 ),
572 ),
573 );
574 const start = gate
575 .withPermit(
576 Effect.gen(function* () {
577 const current = yield* SubscriptionRef.get(state);
578 if (isRunning(current)) return current;
579 if (yield* reuseLocal()) return yield* SubscriptionRef.get(state);
580 if (!asset) {
581 return yield* installationError(
582 "start",
583 `OpenAI does not publish a Codex runtime for ${platform}-${arch}. Use a supported remote environment or a custom executable.`,
584 );
585 }
586 const operationId = yield* crypto.randomUUIDv4();
587 const next: ProviderInstallState = {
588 driver: DRIVER,
589 operationId,
590 phase: "downloading",
591 downloadedBytes: 0,
592 totalBytes: asset.archiveBytes,
593 version: asset.version,
594 installedVersion: current.installedVersion,
595 canRemove: current.canRemove,
596 message: "Downloading Codex.",
597 };
598 yield* SubscriptionRef.set(state, next);
599 const work = install(asset).pipe(
600 Effect.onExit((exit) =>
601 Exit.isFailure(exit)
602 ? SubscriptionRef.update(state, (value) => {
603 if (value.operationId !== operationId || value.phase === "succeeded")
604 return value;
605 const error = Cause.findErrorOption(exit.cause);
606 const cancelled = Cause.hasInterruptsOnly(exit.cause);
607 return {
608 ...value,
609 phase: cancelled ? "cancelled" : "failed",
610 message: cancelled
611 ? "Installation cancelled. The previous runtime is unchanged."
612 : Option.isSome(error)
613 ? error.value.detail
614 : "Could not finish the Codex installation. Check disk space and directory access.",
615 } satisfies ProviderInstallState;
616 })
617 : Effect.void,
618 ),
619 Effect.ignoreCause,
620 Effect.ensuring(
621 Effect.sync(() => {
622 if (running?.operationId === operationId) running = undefined;
623 }),
624 ),
625 );
626 const fiber = yield* Effect.forkIn(Effect.interruptible(work), serviceScope);
627 running = { operationId, fiber };
628 return next;
629 }).pipe(Effect.uninterruptible),
630 )
631 .pipe(Effect.mapError(wrapFailure("start", "Could not start the Codex installation.")));
632
633 const cancel = Effect.fn("CodexInstallation.cancel")(function* (operationId: string) {
634 return yield* gate.withPermit(
635 Effect.gen(function* () {
636 const current = yield* SubscriptionRef.get(state);
637 if (current.operationId !== operationId) {
638 return yield* installationError(
639 "cancel",
640 "This installation is no longer current. Refresh its status before cancelling.",
641 );
642 }
643 if (running?.operationId === operationId && isRunning(current)) {
644 yield* Fiber.interrupt(running.fiber);
645 }
646 return yield* SubscriptionRef.get(state);
647 }),
648 );
649 });
650
651 const remove = Effect.fn("CodexInstallation.remove")(
652 function* (protectedBinaryPaths: ReadonlyArray<string> = []) {
653 yield* gate.withPermit(
654 Effect.gen(function* () {
655 if (isRunning(yield* SubscriptionRef.get(state)) || leases > 0) {
656 return yield* installationError(
657 "remove",
658 "Stop Codex sessions and sign-in flows before removing its managed runtime.",
659 );
660 }
661 const realManaged = yield* fs.realPath(managedDirectory).pipe(Effect.option);
662 if (Option.isSome(realManaged)) {
663 for (const binary of protectedBinaryPaths) {
664 const resolved = yield* fs.realPath(binary).pipe(Effect.option);
665 const candidate = Option.getOrElse(resolved, () => path.resolve(binary));
666 if (candidate.startsWith(`${realManaged.value}${path.sep}`))
667 return yield* installationError(
668 "remove",
669 "A provider instance uses a custom path inside managed Codex. Clear that path before removing it.",
670 );
671 }
672 }
673 yield* fs.remove(managedDirectory, { recursive: true, force: true });
674 yield* SubscriptionRef.update(
675 state,
676 (current) =>
677 ({
678 ...current,
679 operationId: null,
680 phase: "idle",
681 downloadedBytes: 0,
682 installedVersion: null,
683 executablePath: null,
684 source: null,
685 canRemove: false,
686 message: null,
687 }) satisfies ProviderInstallState,
688 );
689 yield* reuseLocal();
690 }).pipe(Effect.uninterruptible),
691 );
692 },
693 Effect.mapError(
694 wrapFailure(
695 "remove",
696 "Could not remove the managed Codex runtime. Check for open processes and try again.",
697 ),
698 ),
699 );
700
701 yield* Effect.gen(function* () {
702 // Two servers can share a home, and writes below a staging directory do not
703 // refresh its mtime, so only directories far older than any real install
704 // (download is capped at 45 minutes) are treated as abandoned.
705 let canRemove = false;
706 if (yield* fs.exists(managedDirectory)) {
707 const entries = yield* fs
708 .readDirectory(managedDirectory)
709 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
710 const now = yield* Clock.currentTimeMillis;
711 for (const entry of entries) {
712 if (!entry.startsWith(".install-") && !entry.startsWith(".active-")) continue;
713 const target = path.join(managedDirectory, entry);
714 const info = yield* fs.stat(target).pipe(Effect.option);
715 if (Option.isNone(info)) continue;
716 const modifiedAt = Option.match(info.value.mtime, {
717 onNone: () => now,
718 onSome: (date) => date.getTime(),
719 });
720 if (now - modifiedAt < STAGING_STALE_AFTER_MS) continue;
721 yield* fs.remove(target, { recursive: true, force: true }).pipe(Effect.ignore);
722 }
723 // The empty root itself stays: deleting it could race another server
724 // creating a staging directory inside. An unreadable root stays removable.
725 const remaining = yield* fs.readDirectory(managedDirectory).pipe(Effect.option);
726 canRemove = Option.isNone(remaining) || remaining.value.length > 0;
727 }
728 yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove }));
729 if (yield* reuseLocal()) return;
730 if (!(yield* fs.exists(activePath))) return;
731 const active = yield* readRecord(activePath, ActiveRelease);
732 const installed = yield* completedRelease(active.version);
733 yield* SubscriptionRef.update(
734 state,
735 (current) =>
736 ({
737 ...current,
738 installedVersion: installed.version,
739 executablePath: installed.executablePath,
740 source: "managed",
741 }) satisfies ProviderInstallState,
742 );
743 }).pipe(
744 Effect.catch(() =>
745 SubscriptionRef.update(
746 state,
747 (current) =>
748 ({
749 ...current,
750 phase: "failed",
751 message: "The managed Codex runtime is incomplete. Remove it and reinstall.",
752 }) satisfies ProviderInstallState,
753 ),
754 ),
755 );
756
757 return CodexInstallation.of({
758 managedDirectory,
759 resolve,
760 acquire,
761 start,
762 cancel,
763 state: SubscriptionRef.get(state),
764 changes: SubscriptionRef.changes(state),
765 remove,
766 });
767});