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