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 {
4 HostProcessArchitecture,
5 HostProcessEnvironment,
6 HostProcessPlatform,
7} from "@t3tools/shared/hostProcess";
8import { resolveCommandPath, resolveSpawnCommand } from "@t3tools/shared/shell";
9import * as Clock from "effect/Clock";
10import * as Cause from "effect/Cause";
11import * as Context from "effect/Context";
12import * as Crypto from "effect/Crypto";
13import * as Effect from "effect/Effect";
14import * as Exit from "effect/Exit";
15import * as Fiber from "effect/Fiber";
16import * as FileSystem from "effect/FileSystem";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Path from "effect/Path";
20import * as Schema from "effect/Schema";
21import * as Scope from "effect/Scope";
22import * as Semaphore from "effect/Semaphore";
23import * as Stream from "effect/Stream";
24import * as SubscriptionRef from "effect/SubscriptionRef";
25import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
26import { ChildProcess, ChildProcessSpawner } from "effect/process";
27import * as NodeCrypto from "node:crypto";
28import * as ServerConfig from "../config.ts";
29import * as ModelManifest from "./ModelManifest.ts";
30import { resolveProviderCompatibility } from "./providerCompatibility.ts";
31
32const DRIVER = ProviderDriverKind.make("codex");
33const Version = Schema.String.check(Schema.isPattern(/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/u));
34const ActiveRelease = Schema.Struct({ version: Version });
35const InstalledRelease = Schema.Struct({
36 version: Version,
37 target: Schema.String,
38 sha256: Schema.String,
39});
40const PackageManifest = Schema.Struct({
41 layoutVersion: Schema.Literal(1),
42 version: Version,
43 target: Schema.String,
44 entrypoint: Schema.String,
45});
46const decodeVersion = Schema.decodeUnknownEffect(Version);
47const encodeRecord = Schema.encodeEffect(Schema.fromJsonString(InstalledRelease));
48const encodeActive = Schema.encodeEffect(Schema.fromJsonString(ActiveRelease));
49export interface CodexReleaseAsset {
50 readonly version: string;
51 readonly target: string;
52 readonly url: string;
53 readonly sha256: string;
54 readonly archiveBytes: number;
55}
56// Official complete packages retain the code-mode, search, and resource companions.
57const RELEASES: Readonly<Record<string, CodexReleaseAsset>> = {
58 "darwin-arm64": {
59 version: "0.156.1",
60 target: "aarch64-apple-darwin",
61 url: "https://github.com/openai/codex/releases/download/rust-v0.156.1/codex-package-aarch64-apple-darwin.tar.gz",
62 sha256: "fea42f9625091f011e38f059da974d52e57ba31831648bb1c7f0b1a385fde547",
63 archiveBytes: 127394863,
64 },
65 "darwin-x64": {
66 version: "0.156.1",
67 target: "x86_64-apple-darwin",
68 url: "https://github.com/openai/codex/releases/download/rust-v0.156.1/codex-package-x86_64-apple-darwin.tar.gz",
69 sha256: "618dbcd55419fa041871f777a14b107ceb3fe2d339ef81e21e6ab5374420dc71",
70 archiveBytes: 138670455,
71 },
72 "linux-arm64": {
73 version: "0.156.1",
74 target: "aarch64-unknown-linux-musl",
75 url: "https://github.com/openai/codex/releases/download/rust-v0.156.1/codex-package-aarch64-unknown-linux-musl.tar.gz",
76 sha256: "fdd47ed6aade0360796fd3f6f95a45096f327c15e19e8c7339f9dc5633041786",
77 archiveBytes: 136933361,
78 },
79 "linux-x64": {
80 version: "0.156.1",
81 target: "x86_64-unknown-linux-musl",
82 url: "https://github.com/openai/codex/releases/download/rust-v0.156.1/codex-package-x86_64-unknown-linux-musl.tar.gz",
83 sha256: "8b711520beddf385467b8da4d2c93736637c6ba1e46811cf0d8606b7c490b6f6",
84 archiveBytes: 145976992,
85 },
86 "win32-arm64": {
87 version: "0.156.1",
88 target: "aarch64-pc-windows-msvc",
89 url: "https://github.com/openai/codex/releases/download/rust-v0.156.1/codex-package-aarch64-pc-windows-msvc.tar.gz",
90 sha256: "85994caecdc7609c49fd585c1cdb5677fa9d0acbf789650cff23a13afc9505db",
91 archiveBytes: 142037952,
92 },
93 "win32-x64": {
94 version: "0.156.1",
95 target: "x86_64-pc-windows-msvc",
96 url: "https://github.com/openai/codex/releases/download/rust-v0.156.1/codex-package-x86_64-pc-windows-msvc.tar.gz",
97 sha256: "a2e017db9807e6a2269a26fea0e1d9546469cef4d472a33016bc9f3ad7d3b733",
98 archiveBytes: 153839991,
99 },
100};
101export const resolveCodexReleaseAsset = (platform: NodeJS.Platform, arch: string) =>
102 RELEASES[`${platform}-${arch}`] ?? null;
103export class CodexInstallationError extends Schema.TaggedError<CodexInstallationError>()(
104 "CodexInstallationError",
105 {
106 operation: Schema.String,
107 detail: Schema.String,
108 cause: Schema.optional(Schema.Defect()),
109 },
110) {
111 override get message() {
112 return this.detail;
113 }
114}
115const isInstallationError = Schema.is(CodexInstallationError);
116const installationError = (operation: string, detail: string, cause?: unknown) =>
117 new CodexInstallationError({ operation, detail, ...(cause === undefined ? {} : { cause }) });
118const wrapFailure = (operation: string, detail: string) => (cause: unknown) =>
119 isInstallationError(cause) ? cause : installationError(operation, detail, cause);
120export interface CodexExecutable {
121 readonly executablePath: string;
122 readonly source: "managed" | "local";
123 readonly version: string;
124 readonly managedVersionDirectory: string | null;
125}
126interface CodexInstallationService {
127 readonly managedDirectory: string;
128 readonly resolve: () => Effect.Effect<CodexExecutable, CodexInstallationError>;
129 readonly acquire: () => Effect.Effect<CodexExecutable, CodexInstallationError, Scope.Scope>;
130 readonly start: Effect.Effect<ProviderInstallState, CodexInstallationError>;
131 readonly cancel: (
132 operationId: string,
133 ) => Effect.Effect<ProviderInstallState, CodexInstallationError>;
134 readonly state: Effect.Effect<ProviderInstallState>;
135 readonly changes: Stream.Stream<ProviderInstallState>;
136 readonly remove: (
137 protectedBinaryPaths?: ReadonlyArray<string>,
138 ) => Effect.Effect<void, CodexInstallationError>;
139}
140export class CodexInstallation extends Context.Service<
141 CodexInstallation,
142 CodexInstallationService
143>()("t3/provider/CodexInstallation") {
144 static readonly layer = Layer.effect(
145 CodexInstallation,
146 Effect.gen(function* () {
147 const config = yield* ServerConfig.ServerConfig;
148 return yield* makeCodexInstallation({ baseDir: config.baseDir });
149 }),
150 );
151}
152export interface CodexInstallationOptions {
153 readonly baseDir: string;
154 readonly releaseAsset?: CodexReleaseAsset | null;
155 readonly validate?: (
156 executable: CodexExecutable,
157 expectedVersion: string,
158 ) => Effect.Effect<void, CodexInstallationError, Scope.Scope>;
159}
160const isRunning = (state: ProviderInstallState) =>
161 ["downloading", "extracting", "verifying"].includes(state.phase);
162export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function* (
163 options: CodexInstallationOptions,
164) {
165 const manifestService = yield* ModelManifest.ModelManifest;
166 const fs = yield* FileSystem.FileSystem;
167 const path = yield* Path.Path;
168 const crypto = yield* Crypto.Crypto;
169 const http = yield* HttpClient.HttpClient;
170 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
171 const serviceScope = yield* Effect.scope;
172 const platform = yield* HostProcessPlatform;
173 const environment = yield* HostProcessEnvironment;
174 const arch = yield* HostProcessArchitecture;
175 const asset =
176 options.releaseAsset === undefined
177 ? resolveCodexReleaseAsset(platform, arch)
178 : options.releaseAsset;
179 const managedDirectory = path.join(options.baseDir, "tools", "codex");
180 const activePath = path.join(managedDirectory, "active.json");
181 const executableName = platform === "win32" ? "codex.exe" : "codex";
182 const gate = yield* Semaphore.make(1);
183 let leases = 0;
184 let running: { readonly operationId: string; readonly fiber: Fiber.Fiber<void> } | undefined;
185 const state = yield* SubscriptionRef.make<ProviderInstallState>({
186 driver: DRIVER,
187 operationId: null,
188 phase: "idle",
189 downloadedBytes: 0,
190 totalBytes: asset?.archiveBytes ?? null,
191 version: asset?.version ?? null,
192 installedVersion: null,
193 executablePath: null,
194 canRemove: false,
195 message: null,
196 });
197 const readRecord = Effect.fn("CodexInstallation.readRecord")(function* <A>(
198 file: string,
199 schema: Schema.Codec<A>,
200 ) {
201 const info = yield* fs.stat(file);
202 if (info.type !== "File" || Number(info.size) > 8192)
203 return yield* installationError(
204 "resolve",
205 "The managed Codex installation record is invalid. Reinstall Codex.",
206 );
207 return yield* Schema.decodeUnknownEffect(Schema.fromJsonString(schema))(
208 yield* fs.readFileString(file),
209 );
210 });
211 const fromDirectory = Effect.fn("CodexInstallation.fromDirectory")(function* (
212 directory: string,
213 version: string,
214 target: string,
215 ) {
216 const manifest = yield* readRecord(path.join(directory, "codex-package.json"), PackageManifest);
217 if (
218 manifest.version !== version ||
219 manifest.target !== target ||
220 manifest.entrypoint !== `bin/${executableName}`
221 )
222 return yield* installationError(
223 "verify",
224 "The downloaded Codex package does not match the expected release.",
225 );
226 for (const name of [
227 `bin/${executableName}`,
228 `bin/codex-code-mode-host${platform === "win32" ? ".exe" : ""}`,
229 `codex-path/rg${platform === "win32" ? ".exe" : ""}`,
230 ]) {
231 const info = yield* fs.stat(path.join(directory, name));
232 if (
233 info.type !== "File" ||
234 Number(info.size) === 0 ||
235 (platform !== "win32" && (info.mode & 0o111) === 0)
236 )
237 return yield* installationError(
238 "verify",
239 "The managed Codex package is incomplete. Reinstall Codex.",
240 );
241 }
242 return {
243 executablePath: path.join(directory, "bin", executableName),
244 source: "managed",
245 version,
246 managedVersionDirectory: directory,
247 } satisfies CodexExecutable;
248 });
249 const completedRelease = Effect.fn("CodexInstallation.completedRelease")(function* (
250 version: string,
251 ) {
252 yield* decodeVersion(version);
253 const directory = path.join(managedDirectory, version);
254 const record = yield* readRecord(
255 path.join(directory, ".install-complete.json"),
256 InstalledRelease,
257 );
258 if (record.version !== version)
259 return yield* installationError(
260 "resolve",
261 "The managed Codex installation record has the wrong version.",
262 );
263 return yield* fromDirectory(directory, version, record.target);
264 });
265 const compatibility = Effect.fn("CodexInstallation.compatibility")(function* (version: string) {
266 const manifest = yield* manifestService.current;
267 return (
268 resolveProviderCompatibility(manifest.compatibility, DRIVER, version) ??
269 resolveProviderCompatibility(
270 ModelManifest.BUNDLED_MODEL_MANIFEST.compatibility,
271 DRIVER,
272 version,
273 )
274 );
275 });
276 const resolveManaged = Effect.fn("CodexInstallation.resolveManaged")(
277 function* () {
278 const active = yield* readRecord(activePath, ActiveRelease);
279 const executable = yield* completedRelease(active.version);
280 const advisory = yield* compatibility(executable.version);
281 if (advisory?.status !== "supported")
282 return yield* installationError(
283 "resolve",
284 advisory?.message ?? "Update the managed Codex installation to continue.",
285 );
286 return executable;
287 },
288 Effect.mapError(
289 wrapFailure("resolve", "Codex is not installed in T3 Code. Install it to continue."),
290 ),
291 );
292 const acquire = Effect.fn("CodexInstallation.acquire")(function* () {
293 return yield* Effect.acquireRelease(
294 gate.withPermit(
295 resolve().pipe(
296 Effect.tap(() =>
297 Effect.sync(() => {
298 leases += 1;
299 }),
300 ),
301 ),
302 ),
303 () =>
304 Effect.sync(() => {
305 leases -= 1;
306 }),
307 );
308 });
309 const runCommand = Effect.fn("CodexInstallation.runCommand")(function* (
310 command: string,
311 args: ReadonlyArray<string>,
312 ) {
313 const resolved = yield* resolveSpawnCommand(command, args).pipe(
314 Effect.provideService(HostProcessPlatform, platform),
315 );
316 const child = yield* spawner.spawn(
317 ChildProcess.make(resolved.command, resolved.args, { shell: resolved.shell }),
318 );
319 const [output, , exitCode] = yield* Effect.all(
320 [
321 child.stdout.pipe(Stream.decodeText(), Stream.mkString),
322 child.stderr.pipe(Stream.runDrain),
323 child.exitCode,
324 ],
325 { concurrency: "unbounded" },
326 );
327 if (exitCode !== 0)
328 return yield* installationError(
329 "verify",
330 "Could not unpack or start the downloaded Codex package.",
331 );
332 return output;
333 }, Effect.scoped);
334 const localCache = new Map<string, { fingerprint: string; executable: CodexExecutable | null }>();
335 const resolveLocal = Effect.fn("CodexInstallation.resolveLocal")(
336 function* () {
337 const executablePath = yield* resolveCommandPath("codex", { env: environment }).pipe(
338 Effect.provideService(HostProcessPlatform, platform),
339 Effect.provideService(FileSystem.FileSystem, fs),
340 Effect.provideService(Path.Path, path),
341 );
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 const entries = (yield* runCommand("tar", ["-tzf", archivePath])).trim().split("\n");
519 const types = (yield* runCommand("tar", ["-tvzf", archivePath])).trim().split("\n");
520 if (
521 entries.length > 10000 ||
522 entries.length !== types.length ||
523 types.some((line) => !["-", "d"].includes(line[0] ?? "")) ||
524 entries.some((entry) => {
525 const parts = entry.replace(/\/$/u, "").split("/");
526 return (
527 !entry ||
528 entry.includes("\\") ||
529 entry.startsWith("/") ||
530 parts.some((part) => part === ".." || part === "." || part === "" || part.includes(":"))
531 );
532 })
533 )
534 return yield* installationError("extract", "The Codex archive contains unsafe entries.");
535 yield* runCommand("tar", ["-xzf", archivePath, "-C", runtime]);
536 yield* SubscriptionRef.update(
537 state,
538 (current) =>
539 ({
540 ...current,
541 phase: "verifying",
542 message: "Checking Codex.",
543 }) satisfies ProviderInstallState,
544 );
545 const executable = yield* fromDirectory(runtime, release.version, release.target);
546 yield* validate(executable, release.version).pipe(
547 Effect.scoped,
548 Effect.timeout("90 seconds"),
549 );
550 yield* fs.writeFileString(
551 path.join(runtime, ".install-complete.json"),
552 yield* encodeRecord({
553 version: release.version,
554 target: release.target,
555 sha256: release.sha256,
556 }),
557 { flag: "wx", mode: 0o600 },
558 );
559 yield* fs.rename(runtime, destination);
560 yield* activate();
561 },
562 Effect.scoped,
563 Effect.mapError(
564 wrapFailure(
565 "install",
566 "Could not install Codex. Check disk space and directory access, then try again.",
567 ),
568 ),
569 );
570 const start = gate
571 .withPermit(
572 Effect.gen(function* () {
573 const current = yield* SubscriptionRef.get(state);
574 if (isRunning(current)) return current;
575 if (yield* reuseLocal()) return yield* SubscriptionRef.get(state);
576 if (!asset) {
577 return yield* installationError(
578 "start",
579 `OpenAI does not publish a Codex runtime for ${platform}-${arch}. Use a supported remote environment or a custom executable.`,
580 );
581 }
582 const operationId = yield* crypto.randomUUIDv4;
583 const next: ProviderInstallState = {
584 driver: DRIVER,
585 operationId,
586 phase: "downloading",
587 downloadedBytes: 0,
588 totalBytes: asset.archiveBytes,
589 version: asset.version,
590 installedVersion: current.installedVersion,
591 canRemove: current.canRemove,
592 message: "Downloading Codex.",
593 };
594 yield* SubscriptionRef.set(state, next);
595 const work = install(asset).pipe(
596 Effect.onExit((exit) =>
597 Exit.isFailure(exit)
598 ? SubscriptionRef.update(state, (value) => {
599 if (value.operationId !== operationId || value.phase === "succeeded")
600 return value;
601 const error = Cause.findErrorOption(exit.cause);
602 const cancelled = Cause.hasInterruptsOnly(exit.cause);
603 return {
604 ...value,
605 phase: cancelled ? "cancelled" : "failed",
606 message: cancelled
607 ? "Installation cancelled. The previous runtime is unchanged."
608 : Option.isSome(error)
609 ? error.value.detail
610 : "Could not finish the Codex installation. Check disk space and directory access.",
611 } satisfies ProviderInstallState;
612 })
613 : Effect.void,
614 ),
615 Effect.ignoreCause,
616 Effect.ensuring(
617 Effect.sync(() => {
618 if (running?.operationId === operationId) running = undefined;
619 }),
620 ),
621 );
622 const fiber = yield* Effect.forkIn(Effect.interruptible(work), serviceScope);
623 running = { operationId, fiber };
624 return next;
625 }).pipe(Effect.uninterruptible),
626 )
627 .pipe(Effect.mapError(wrapFailure("start", "Could not start the Codex installation.")));
628
629 const cancel = Effect.fn("CodexInstallation.cancel")(function* (operationId: string) {
630 return yield* gate.withPermit(
631 Effect.gen(function* () {
632 const current = yield* SubscriptionRef.get(state);
633 if (current.operationId !== operationId) {
634 return yield* installationError(
635 "cancel",
636 "This installation is no longer current. Refresh its status before cancelling.",
637 );
638 }
639 if (running?.operationId === operationId && isRunning(current)) {
640 yield* Fiber.interrupt(running.fiber);
641 }
642 return yield* SubscriptionRef.get(state);
643 }),
644 );
645 });
646
647 const remove = Effect.fn("CodexInstallation.remove")(
648 function* (protectedBinaryPaths: ReadonlyArray<string> = []) {
649 yield* gate.withPermit(
650 Effect.gen(function* () {
651 if (isRunning(yield* SubscriptionRef.get(state)) || leases > 0) {
652 return yield* installationError(
653 "remove",
654 "Stop Codex sessions and sign-in flows before removing its managed runtime.",
655 );
656 }
657 const realManaged = yield* fs.realPath(managedDirectory).pipe(Effect.option);
658 if (Option.isSome(realManaged)) {
659 for (const binary of protectedBinaryPaths) {
660 const resolved = yield* fs.realPath(binary).pipe(Effect.option);
661 const candidate = Option.getOrElse(resolved, () => path.resolve(binary));
662 if (candidate.startsWith(`${realManaged.value}${path.sep}`))
663 return yield* installationError(
664 "remove",
665 "A provider instance uses a custom path inside managed Codex. Clear that path before removing it.",
666 );
667 }
668 }
669 yield* fs.remove(managedDirectory, { recursive: true, force: true });
670 yield* SubscriptionRef.update(
671 state,
672 (current) =>
673 ({
674 ...current,
675 operationId: null,
676 phase: "idle",
677 downloadedBytes: 0,
678 installedVersion: null,
679 executablePath: null,
680 source: null,
681 canRemove: false,
682 message: null,
683 }) satisfies ProviderInstallState,
684 );
685 yield* reuseLocal();
686 }).pipe(Effect.uninterruptible),
687 );
688 },
689 Effect.mapError(
690 wrapFailure(
691 "remove",
692 "Could not remove the managed Codex runtime. Check for open processes and try again.",
693 ),
694 ),
695 );
696
697 yield* Effect.gen(function* () {
698 const canRemove = yield* fs.exists(managedDirectory);
699 yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove }));
700 if (yield* reuseLocal()) return;
701 if (!(yield* fs.exists(activePath))) return;
702 const active = yield* readRecord(activePath, ActiveRelease);
703 const installed = yield* completedRelease(active.version);
704 yield* SubscriptionRef.update(
705 state,
706 (current) =>
707 ({
708 ...current,
709 installedVersion: installed.version,
710 executablePath: installed.executablePath,
711 source: "managed",
712 }) satisfies ProviderInstallState,
713 );
714 }).pipe(
715 Effect.catch(() =>
716 SubscriptionRef.update(
717 state,
718 (current) =>
719 ({
720 ...current,
721 phase: "failed",
722 message: "The managed Codex runtime is incomplete. Remove it and reinstall.",
723 }) satisfies ProviderInstallState,
724 ),
725 ),
726 );
727
728 return CodexInstallation.of({
729 managedDirectory,
730 resolve,
731 acquire,
732 start,
733 cancel,
734 state: SubscriptionRef.get(state),
735 changes: SubscriptionRef.changes(state),
736 remove,
737 });
738});