The best way to control Claude Code, Codex and more from any computer or phone

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