Open History to see the last commit
1import * as CodexInstallation from "../CodexInstallation.ts";
2import * as CodexManagedTokenBroker from "../CodexManagedTokenBroker.ts";
3import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
4import * as ServerEnvironment from "../../environment/ServerEnvironment.ts";
5// @effect-diagnostics nodeBuiltinImport:off
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import * as NodePath from "node:path";
8import { expect, it } from "@effect/vitest";
9import { EnvironmentId, ProviderInstanceId, ProviderSessionId, ThreadId } from "@t3tools/contracts";
10import * as HostProcess from "@t3tools/shared/HostProcess";
11import * as Effect from "effect/Effect";
12import * as Exit from "effect/Exit";
13import * as Deferred from "effect/Deferred";
14import * as Fiber from "effect/Fiber";
15import * as FileSystem from "effect/FileSystem";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as PlatformError from "effect/PlatformError";
19import * as Schema from "effect/Schema";
20import * as Sink from "effect/Sink";
21import * as Stream from "effect/Stream";
22import { HttpClient, HttpClientResponse } from "effect/http";
23import * as ChildProcess from "effect/process/ChildProcess";
24import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
25
26import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
27import * as ServerConfig from "../../config.ts";
28import * as ServerSettings from "../../serverSettings.ts";
29import * as ResetCreditCoordinator from "../resetCreditCoordinator.ts";
30import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
31import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
32import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
33import * as ModelManifest from "../ModelManifest.ts";
34import {
35 createProviderVersionAdvisory,
36 resolveLatestProviderVersion,
37} from "@t3tools/provider-core/server/maintenanceResolver";
38import { CodexDriver } from "./CodexDriver.ts";
39import * as CodexAdapterV2 from "../../orchestration-v2/Adapters/CodexAdapterV2.ts";
40import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
41import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
42import * as ProviderCredentialStore from "../ProviderCredentialStore.ts";
43import * as ProviderHostLive from "../ProviderHostLive.ts";
44
45const layerDeps = ServerConfig.layerTest(process.cwd(), {
46 prefix: "t3-codex-driver-maintenance-",
47}).pipe(
48 Layer.provideMerge(NodeServices.layer),
49 Layer.provideMerge(IdAllocator.layer),
50 Layer.provideMerge(McpProviderSessions.layer),
51 Layer.provideMerge(
52 Layer.mock(CodexAdapterV2.CodexAppServerClientFactory)({
53 open: () => Effect.die("Maintenance resolution must not open a Codex session"),
54 }),
55 ),
56 Layer.provideMerge(
57 Layer.mock(CodexInstallation.CodexInstallation)({
58 managedDirectory: "unused-managed-installation",
59 }),
60 ),
61 Layer.provideMerge(Layer.mock(ServerSecretStore.ServerSecretStore)({})),
62 Layer.provideMerge(
63 Layer.mock(CodexManagedTokenBroker.CodexManagedTokenBroker)({
64 endpoint: Effect.succeed("unused-private-pipe"),
65 awaitIdle: Effect.void,
66 }),
67 ),
68 Layer.provideMerge(
69 Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, {
70 getEnvironmentId: Effect.succeed(EnvironmentId.make("00000000-0000-4000-8000-000000000001")),
71 }),
72 ),
73 Layer.provideMerge(ServerSettings.layerTest()),
74 Layer.provideMerge(ModelManifest.layerTest),
75 Layer.provideMerge(ResetCreditCoordinator.layerTest),
76 Layer.provideMerge(
77 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
78 shouldRunScopeWork: () => Effect.succeed(false),
79 }),
80 ),
81 Layer.provideMerge(
82 Layer.succeed(
83 ProviderEventLoggers.ProviderEventLoggers,
84 ProviderEventLoggers.NoOpProviderEventLoggers,
85 ),
86 ),
87 Layer.provideMerge(ProviderLatestVersions.layer),
88 Layer.provideMerge(
89 Layer.succeed(
90 HttpClient.HttpClient,
91 HttpClient.make(() => Effect.die("Disabled Codex must not make an HTTP request")),
92 ),
93 ),
94);
95const layerTest = ProviderHostLive.layer.pipe(Layer.provideMerge(layerDeps));
96
97// The `#!/bin/sh` stub below cannot be resolved as an executable on Windows.
98const windowsHost = HostProcess.Platform.defaultValue() === "win32";
99
100const noSpawn = ChildProcessSpawner.make(() =>
101 Effect.die("Disabled Codex must not spawn a process"),
102);
103const encodeCredentials = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
104
105it.layer(layerTest)("CodexDriver", (it) => {
106 const checkManagedAccount = (replacementTiming: "unchanged" | "during-probe") =>
107 Effect.gen(function* () {
108 const instanceId = ProviderInstanceId.make("restored-managed-account");
109 const credentials = new Map<string, Uint8Array>();
110 const catalogTokens: Array<string | undefined> = [];
111 const probeEntered = yield* Deferred.make<void>();
112 const resumeProbe = yield* Deferred.make<void>();
113 const secrets = ServerSecretStore.ServerSecretStore.of({
114 get: (key) => Effect.sync(() => Option.fromUndefinedOr(credentials.get(key))),
115 set: (key, value) =>
116 Effect.sync(() => {
117 credentials.set(key, value);
118 }),
119 remove: (key) =>
120 Effect.sync(() => {
121 credentials.delete(key);
122 }),
123 create: () => Effect.die("unused"),
124 getOrCreateRandom: () => Effect.die("unused"),
125 });
126 yield* Effect.gen(function* () {
127 const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId);
128 const json = yield* encodeCredentials({
129 clientId: "oaiapp_test",
130 accessToken: "dummy-owned-access",
131 refreshToken: "dummy-refresh",
132 expiresAt: Number.MAX_SAFE_INTEGER,
133 earliestRefreshAt: null,
134 scopes: ["chatgpt.tokens.use.direct"],
135 subject: "test-user",
136 email: "account@example.test",
137 });
138 yield* store.set(new TextEncoder().encode(json));
139 const replacement = yield* encodeCredentials({
140 clientId: "oaiapp_replacement",
141 subject: "replacement-user",
142 email: "replacement@example.test",
143 accessToken: "replacement-access",
144 refreshToken: "replacement-refresh",
145 expiresAt: Number.MAX_SAFE_INTEGER,
146 earliestRefreshAt: null,
147 scopes: ["chatgpt.tokens.use.direct"],
148 });
149 const replaceAccount = store.set(new TextEncoder().encode(replacement)).pipe(Effect.orDie);
150 const executable = {
151 executablePath: "/user/bin/codex",
152 managedVersionDirectory: null,
153 source: "local" as const,
154 version: "0.156.1",
155 };
156 const installation = yield* CodexInstallation.CodexInstallation;
157 const serverConfig = yield* ServerConfig.ServerConfig;
158 const sharedHome = NodePath.join(serverConfig.stateDir, "shared-codex-home");
159 const launches: Array<
160 Parameters<CodexAdapterV2.CodexAppServerClientFactoryShape["open"]>[0]
161 > = [];
162
163 let interruptedChecks = 0;
164 let failAcquire = false;
165 const startupChecksInterrupted = yield* Deferred.make<void>();
166 const acquire = () =>
167 Effect.suspend(() => {
168 if (failAcquire)
169 return Effect.fail(
170 new CodexInstallation.CodexInstallationError({
171 operation: "acquire",
172 detail: "The fixture runtime is unavailable",
173 }),
174 );
175 if (interruptedChecks === 2) return Effect.succeed(executable);
176 interruptedChecks += 1;
177 return (
178 interruptedChecks === 2
179 ? Deferred.succeed(startupChecksInterrupted, undefined)
180 : Effect.void
181 ).pipe(Effect.andThen(Effect.interrupt));
182 });
183 const instance = yield* CodexDriver.create({
184 instanceId,
185 displayName: "Restored account",
186 enabled: true,
187 environment: [{ name: "OPENAI_API_KEY", value: "ambient-key", sensitive: true }],
188 config: { ...CodexDriver.defaultConfig(), setupMode: "managed", homePath: sharedHome },
189 }).pipe(
190 Effect.provideService(
191 CodexAdapterV2.CodexAppServerClientFactory,
192 CodexAdapterV2.CodexAppServerClientFactory.of({
193 open: (launch) =>
194 Effect.sync(() => launches.push(launch)).pipe(
195 Effect.andThen(Effect.die("The fixture stops after recording the launch")),
196 ),
197 }),
198 ),
199 Effect.provideService(
200 CodexInstallation.CodexInstallation,
201 CodexInstallation.CodexInstallation.of({
202 ...installation,
203 managedDirectory: "unused-managed-installation",
204 resolve: () => Effect.succeed(executable),
205 acquire,
206 }),
207 ),
208 Effect.provideService(
209 ChildProcessSpawner.ChildProcessSpawner,
210 ChildProcessSpawner.make(() =>
211 Effect.gen(function* () {
212 if (replacementTiming === "during-probe") {
213 yield* Deferred.succeed(probeEntered, undefined);
214 yield* Deferred.await(resumeProbe);
215 }
216 return yield* PlatformError.badArgument({
217 module: "ChildProcessSpawner",
218 method: "spawn",
219 description: "The fixture app-server is unavailable",
220 });
221 }),
222 ),
223 ),
224 );
225 const observedAccount = yield* Deferred.make<void>();
226 const disconnected = yield* instance.snapshot.streamChanges.pipe(
227 Stream.tap((provider) =>
228 provider.auth.status === "authenticated"
229 ? Deferred.succeed(observedAccount, undefined).pipe(Effect.asVoid)
230 : Effect.void,
231 ),
232 Stream.filter((provider) => provider.auth.status === "unauthenticated"),
233 Stream.runHead,
234 Effect.forkScoped,
235 );
236 yield* Deferred.await(startupChecksInterrupted);
237 const refresh = yield* instance.snapshot.refresh.pipe(Effect.forkChild);
238 if (replacementTiming === "during-probe") {
239 yield* Deferred.await(probeEntered);
240 yield* replaceAccount;
241 yield* Deferred.succeed(resumeProbe, undefined);
242 }
243 const restored = yield* Fiber.join(refresh);
244 if (replacementTiming === "during-probe") {
245 expect(catalogTokens).toEqual([]);
246 expect(restored.models).toEqual([]);
247 expect(restored.auth.email).toBe("replacement@example.test");
248 expect(restored.auth.profileId).toBe("oaiapp_replacement");
249 return;
250 }
251 expect(catalogTokens).toEqual(["Bearer dummy-owned-access"]);
252 expect(restored.auth.email).toBe("account@example.test");
253 expect(restored.runtimePaths?.homePath).toBe(sharedHome);
254 expect(restored.runtimePaths?.shadowHomePath).toContain(
255 `providers/codex/${instanceId}/shadow`,
256 );
257 const scan = yield* instance.snapshotForCwd!(serverConfig.stateDir).pipe(Effect.exit);
258 expect(Exit.isFailure(scan)).toBe(true);
259 failAcquire = true;
260 const runtimeScan = yield* instance.snapshotForCwd!(serverConfig.stateDir).pipe(
261 Effect.exit,
262 );
263 failAcquire = false;
264 expect(Exit.isFailure(runtimeScan)).toBe(true);
265 yield* Deferred.await(observedAccount);
266
267 const threadId = ThreadId.make("managed-account-thread");
268 yield* instance.orchestrationAdapter
269 .openSession({
270 threadId,
271 providerSessionId: ProviderSessionId.make("managed-account-session"),
272 modelSelection: { instanceId, model: "gpt-5.4" },
273 runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
274 runtimeMode: "full-access",
275 interactionMode: "default",
276 cwd: serverConfig.stateDir,
277 }),
278 })
279 .pipe(Effect.scoped, Effect.exit);
280 expect(launches).toHaveLength(1);
281 const launch = launches[0]!;
282 expect(launch.settings.binaryPath).toBe(executable.executablePath);
283 expect(launch.settings.launchArgs).toContain("openai_token_sharing");
284 expect(launch.environment.ACCESS_TOKEN).toBeUndefined();
285 expect(launch.settings.launchArgs).toContain("__managed-chatgpt-token");
286 expect(launch.settings.launchArgs).not.toContain("dummy-owned-access");
287 expect(launch.environment.OPENAI_API_KEY).toBeUndefined();
288 expect(launch.environment.CODEX_HOME).toBe(launch.settings.homePath);
289 const before = yield* instance.auth!.subscribe("test-owner").pipe(Stream.runHead);
290 expect(Option.getOrThrow(before).phase).toBe("idle");
291 yield* instance.auth!.logout(Effect.void);
292 const after = Option.getOrThrow(yield* Fiber.join(disconnected));
293 expect(after.auth.status).toBe("unauthenticated");
294 expect(after.auth.email).toBeUndefined();
295 expect(after.installed).toBe(true);
296 expect(after.models).toEqual([]);
297 expect(Option.isNone(yield* store.get)).toBe(true);
298 const signedOutScan = yield* instance.snapshotForCwd!(serverConfig.stateDir);
299 expect(signedOutScan.skills).toEqual([]);
300 }).pipe(
301 Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
302 Effect.provideService(
303 HttpClient.HttpClient,
304 HttpClient.make((request) =>
305 Effect.sync(() => {
306 expect([
307 "https://auth.openai.com/.well-known/openid-configuration",
308 "https://auth.openai.com/revoke",
309 "https://api.openai.com/v1/models",
310 ]).toContain(request.url);
311 if (request.url.endsWith("/models")) {
312 catalogTokens.push(request.headers.authorization);
313 return HttpClientResponse.fromWeb(request, Response.json({ models: [] }));
314 }
315 return HttpClientResponse.fromWeb(
316 request,
317 request.url.endsWith("/revoke")
318 ? new Response(null, { status: 200 })
319 : Response.json({
320 issuer: "https://auth.openai.com",
321 authorization_endpoint: "https://auth.openai.com/api/accounts/authorize",
322 token_endpoint: "https://auth.openai.com/api/accounts/oauth/token",
323 jwks_uri: "https://auth.openai.com/jwks",
324 revocation_endpoint: "https://auth.openai.com/revoke",
325 }),
326 );
327 }),
328 ),
329 ),
330 );
331 }).pipe(Effect.scoped);
332 // regression: a sign-in that replaces the account mid-probe must not label the old
333 // account's catalog with the new identity.
334 it.effect.each(["unchanged", "during-probe"] as const)(
335 "managed catalog keeps its account label and token together: %s",
336 checkManagedAccount,
337 );
338
339 it.effect.skipIf(windowsHost)(
340 "runs the standalone updater against the shared home, not the shadow home",
341 () =>
342 Effect.gen(function* () {
343 const fs = yield* FileSystem.FileSystem;
344 const tempDir = yield* fs
345 .makeTempDirectoryScoped({ prefix: "t3-codex-driver-" })
346 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
347 const sharedHome = NodePath.join(tempDir, "codex-home");
348 const shadowHome = NodePath.join(tempDir, "codex-shadow");
349 const binaryPath = NodePath.join(sharedHome, "packages", "standalone", "bin", "codex");
350 yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
351 yield* fs.writeFileString(binaryPath, "#!/bin/sh\n");
352 yield* fs.chmod(binaryPath, 0o755);
353
354 const instance = yield* CodexDriver.create({
355 instanceId: ProviderInstanceId.make("codex-shadow"),
356 displayName: "Codex test",
357 enabled: false,
358 environment: [],
359 config: {
360 ...CodexDriver.defaultConfig(),
361 binaryPath,
362 homePath: sharedHome,
363 shadowHomePath: shadowHome,
364 },
365 });
366
367 const capabilities = yield* instance.snapshot.resolveMaintenance();
368 expect(capabilities.update).toMatchObject({
369 executable: binaryPath,
370 args: ["update"],
371 lockKey: "codex-native",
372 env: { CODEX_HOME: sharedHome },
373 });
374 }).pipe(
375 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
376 Effect.scoped,
377 ),
378 );
379
380 it.effect.skipIf(windowsHost)(
381 "runs the standalone updater against the home that holds a shared install",
382 () =>
383 Effect.gen(function* () {
384 const fs = yield* FileSystem.FileSystem;
385 const tempDir = yield* fs
386 .makeTempDirectoryScoped({ prefix: "t3-codex-driver-" })
387 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
388 // One standalone install, linked onto PATH and used by two account homes.
389 // `İ` gets longer when lowercased, so the home must not be sliced from a
390 // lowercased copy of the path.
391 const installHome = NodePath.join(tempDir, "codex-İnstall");
392 const realBinaryPath = NodePath.join(
393 installHome,
394 "packages",
395 "standalone",
396 "releases",
397 "0.162.1-x86_64-unknown-linux-musl",
398 "bin",
399 "codex",
400 );
401 const binaryPath = NodePath.join(tempDir, "bin", "codex");
402 yield* fs.makeDirectory(NodePath.dirname(realBinaryPath), { recursive: true });
403 yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
404 yield* fs.writeFileString(realBinaryPath, "#!/bin/sh\n");
405 yield* fs.chmod(realBinaryPath, 0o755);
406 yield* fs.symlink(realBinaryPath, binaryPath);
407
408 const updates = yield* Effect.forEach(["codex-p", "codex-vm"], (account) =>
409 Effect.gen(function* () {
410 const homePath = NodePath.join(tempDir, `home-${account}`);
411 yield* fs.makeDirectory(homePath, { recursive: true });
412 const instance = yield* CodexDriver.create({
413 instanceId: ProviderInstanceId.make(account),
414 displayName: account,
415 enabled: false,
416 environment: [],
417 config: { ...CodexDriver.defaultConfig(), binaryPath, homePath },
418 });
419 return (yield* instance.snapshot.resolveMaintenance()).update;
420 }),
421 );
422
423 for (const update of updates) {
424 expect(update).toMatchObject({
425 command: `${binaryPath} update`,
426 args: ["update"],
427 lockKey: "codex-native",
428 env: { CODEX_HOME: installHome },
429 });
430 }
431 }).pipe(
432 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
433 Effect.scoped,
434 ),
435 );
436
437 it.effect.skipIf(windowsHost)("derives the standalone update home from either command path", () =>
438 Effect.gen(function* () {
439 const fs = yield* FileSystem.FileSystem;
440 const tempDir = yield* fs
441 .makeTempDirectoryScoped({ prefix: "t3-codex-update-home-" })
442 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
443 const linkedInstallHome = NodePath.join(tempDir, "install");
444 const fixtures = [
445 { binary: "codex", realPath: "/packages/standalone/bin/codex", home: "/" },
446 { binary: "codex", realPath: "C:\\Packages\\Standalone\\bin\\codex.exe", home: "C:\\" },
447 // The standalone tree itself is a symlink, so only the resolved path names its home.
448 {
449 binary: NodePath.join("install", "packages", "standalone", "bin", "codex"),
450 realPath: "/disk/codex/releases/0.163.0/bin/codex",
451 home: linkedInstallHome,
452 },
453 ];
454
455 for (const fixture of fixtures) {
456 const binaryPath = NodePath.join(tempDir, fixture.binary);
457 yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
458 yield* fs.writeFileString(binaryPath, "#!/bin/sh\n");
459 yield* fs.chmod(binaryPath, 0o755);
460 const instance = yield* CodexDriver.create({
461 instanceId: ProviderInstanceId.make("codex-update-home"),
462 displayName: "Codex update home",
463 enabled: false,
464 environment: [],
465 config: { ...CodexDriver.defaultConfig(), binaryPath, homePath: tempDir },
466 }).pipe(
467 // Virtualize only the executable target: these trees do not belong to this test.
468 Effect.provideService(FileSystem.FileSystem, {
469 ...fs,
470 realPath: (path) =>
471 path === binaryPath ? Effect.succeed(fixture.realPath) : fs.realPath(path),
472 }),
473 );
474 expect((yield* instance.snapshot.resolveMaintenance()).update?.env).toEqual({
475 CODEX_HOME: fixture.home,
476 });
477 }
478 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), Effect.scoped),
479 );
480
481 for (const fixture of [
482 {
483 name: "leaves mise npm-backend installations manual-only",
484 installSegments: ["mise", "installs", "npm-openai-codex", "0.110.0"],
485 npmOwned: false,
486 },
487 {
488 name: "leaves mise tool aliases backed by npm manual-only",
489 installSegments: ["mise", "installs", "codex", "0.110.0"],
490 npmOwned: false,
491 },
492 {
493 name: "keeps npm updates for globals in a mise Node installation",
494 installSegments: ["mise", "installs", "node", "24.0.0"],
495 npmOwned: true,
496 },
497 {
498 name: "keeps npm updates for ordinary global installations",
499 installSegments: ["npm-global"],
500 npmOwned: true,
501 },
502 ] as const) {
503 it.effect.skipIf(windowsHost)(fixture.name, () =>
504 Effect.gen(function* () {
505 const fs = yield* FileSystem.FileSystem;
506 const tempDir = yield* fs
507 .makeTempDirectoryScoped({ prefix: "t3-codex-installer-" })
508 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
509 const installPath = NodePath.join(tempDir, ...fixture.installSegments);
510 const realBinaryPath = NodePath.join(
511 installPath,
512 "lib",
513 "node_modules",
514 "@openai",
515 "codex",
516 "bin",
517 "codex.js",
518 );
519 const binaryPath = NodePath.join(tempDir, "bin", "codex");
520 yield* fs.makeDirectory(NodePath.dirname(realBinaryPath), { recursive: true });
521 yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
522 yield* fs.writeFileString(realBinaryPath, "#!/bin/sh\n");
523 yield* fs.chmod(realBinaryPath, 0o755);
524 yield* fs.symlink(realBinaryPath, binaryPath);
525
526 const instance = yield* CodexDriver.create({
527 instanceId: ProviderInstanceId.make("codex-installer"),
528 displayName: "Codex installer test",
529 enabled: false,
530 environment: [],
531 config: {
532 ...CodexDriver.defaultConfig(),
533 binaryPath,
534 homePath: NodePath.join(tempDir, "codex-home"),
535 },
536 });
537
538 const update = (yield* instance.snapshot.resolveMaintenance()).update;
539 if (fixture.npmOwned) {
540 expect(update).toMatchObject({
541 executable: "npm",
542 args: [
543 "install",
544 "-g",
545 "--prefix",
546 installPath,
547 "--allow-scripts=@openai/codex",
548 "@openai/codex@latest",
549 ],
550 });
551 } else {
552 expect(update).toBeNull();
553 }
554 }).pipe(
555 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
556 Effect.scoped,
557 ),
558 );
559 }
560
561 for (const {} of ["direct", "wrapper"] as const) {
562 }
563
564 it.effect.each([
565 {
566 name: "conventional shim",
567 dataRoot: "mise",
568 commandName: "codex",
569 version: "0.153.4",
570 nodeFirst: false,
571 },
572 {
573 name: "custom data directory",
574 dataRoot: "custom-tool-data",
575 commandName: "codex",
576 version: "0.153.4",
577 nodeFirst: false,
578 },
579 {
580 name: "renamed configured command",
581 dataRoot: "mise",
582 commandName: "custom-codex",
583 version: "0.153.4",
584 nodeFirst: false,
585 },
586 {
587 name: "outdated provider",
588 dataRoot: "mise",
589 commandName: "codex",
590 version: "0.153.3",
591 nodeFirst: false,
592 },
593 {
594 name: "npm before shim",
595 dataRoot: "mise",
596 commandName: "codex",
597 version: "0.153.4",
598 nodeFirst: true,
599 },
600 ])(
601 "does not mistake Homebrew mise for Codex's installer: $name",
602 (fixture) =>
603 Effect.gen(function* () {
604 const fs = yield* FileSystem.FileSystem;
605 const tempDir = yield* fs
606 .makeTempDirectoryScoped({ prefix: "t3-codex-mise-shim-" })
607 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
608 const brewPrefix = NodePath.join(tempDir, "homebrew");
609 const brewPath = NodePath.join(brewPrefix, "bin", "brew");
610 const misePath = NodePath.join(brewPrefix, "Cellar", "mise", "2026.9.1", "bin", "mise");
611 const shimDir = NodePath.join(tempDir, fixture.dataRoot, "shims");
612 const npmPrefix = NodePath.join(tempDir, "mise", "installs", "node", "24.13.0");
613 const npmBin = NodePath.join(npmPrefix, "bin");
614 const npmEntry = NodePath.join(
615 npmPrefix,
616 "lib",
617 "node_modules",
618 "@openai",
619 "codex",
620 "bin",
621 "codex.js",
622 );
623 for (const file of [brewPath, misePath, npmEntry]) {
624 yield* fs.makeDirectory(NodePath.dirname(file), { recursive: true });
625 yield* fs.writeFileString(file, "#!/bin/sh\n");
626 yield* fs.chmod(file, 0o755);
627 }
628 yield* fs.makeDirectory(shimDir, { recursive: true });
629 yield* fs.makeDirectory(npmBin, { recursive: true });
630 yield* fs.symlink(misePath, NodePath.join(shimDir, fixture.commandName));
631 yield* fs.symlink(npmEntry, NodePath.join(npmBin, fixture.commandName));
632 const lookupPath = [
633 ...(fixture.nodeFirst ? [npmBin, shimDir] : [shimDir, npmBin]),
634 NodePath.dirname(brewPath),
635 ].join(NodePath.delimiter);
636 const probes: Array<ReadonlyArray<string>> = [];
637 const metadataSpawner = ChildProcessSpawner.make((command) => {
638 if (!ChildProcess.isStandardCommand(command) || command.command !== brewPath) {
639 return Effect.die("Provider resolution must not execute a provider or updater");
640 }
641 probes.push(command.args);
642 const stdout =
643 command.args[0] === "--prefix"
644 ? brewPrefix
645 : JSON.stringify({ formulae: [{ versions: { stable: "2026.9.1" } }] });
646 return Effect.succeed(
647 ChildProcessSpawner.makeHandle({
648 pid: ChildProcessSpawner.ProcessId(1),
649 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
650 isRunning: Effect.succeed(false),
651 kill: () => Effect.void,
652 unref: Effect.succeed(Effect.void),
653 stdin: Sink.drain,
654 stdout: Stream.encodeText(Stream.make(stdout)),
655 stderr: Stream.empty,
656 all: Stream.empty,
657 getInputFd: () => Sink.drain,
658 getOutputFd: () => Stream.empty,
659 }),
660 );
661 });
662 const instance = yield* CodexDriver.create({
663 instanceId: ProviderInstanceId.make("codex-mise-shim"),
664 displayName: "Codex shim test",
665 enabled: false,
666 environment: [{ name: "PATH", value: lookupPath, sensitive: false }],
667 config: {
668 ...CodexDriver.defaultConfig(),
669 binaryPath: fixture.commandName,
670 homePath: NodePath.join(tempDir, "codex-home"),
671 },
672 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, metadataSpawner));
673 const capabilities = yield* instance.snapshot.resolveMaintenance();
674 const latestVersion = yield* resolveLatestProviderVersion(capabilities).pipe(
675 Effect.provideServiceEffect(
676 ProviderLatestVersions.ProviderLatestVersions,
677 ProviderLatestVersions.make([["@openai/codex", "0.153.4"]]),
678 ),
679 );
680 expect(probes).toEqual([]);
681 expect(latestVersion).toBe("0.153.4");
682 expect(
683 createProviderVersionAdvisory({
684 driver: CodexDriver.driverKind,
685 currentVersion: fixture.version,
686 latestVersion,
687 maintenanceCapabilities: capabilities,
688 }),
689 ).toMatchObject({
690 status: fixture.version === "0.153.4" ? "current" : "behind_latest",
691 currentVersion: fixture.version,
692 latestVersion: "0.153.4",
693 canUpdate: fixture.nodeFirst,
694 });
695 if (fixture.nodeFirst) {
696 expect(capabilities.update).toMatchObject({
697 executable: "npm",
698 args: expect.arrayContaining([
699 "--prefix",
700 yield* fs.realPath(npmPrefix),
701 "@openai/codex@latest",
702 ]),
703 });
704 } else {
705 expect(capabilities.update).toBeNull();
706 }
707 }).pipe(Effect.scoped),
708 { skip: windowsHost },
709 );
710});