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