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