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