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