Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - checks the host's default Codex directory without writing to it.
2import * as NodeURL from "node:url";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as Stream from "effect/Stream";
5import { ChildProcess, ChildProcessSpawner } from "effect/process";
6import * as CodexManagedTokenBroker from "./CodexManagedTokenBroker.ts";
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import { assert, it } from "@effect/vitest";
9import { CodexSettings, EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
10import * as Clock from "effect/Clock";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Path from "effect/Path";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Schema from "effect/Schema";
17import { HttpClient, HttpClientResponse } from "effect/http";
18import * as ServerConfig from "../config.ts";
19import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
20import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
21import * as CodexInstallation from "./CodexInstallation.ts";
22import { makeCodexManagedRuntime } from "./CodexManagedRuntime.ts";
23import * as ProviderCredentialStore from "./ProviderCredentialStore.ts";
24import { codexAppServerArgs } from "./codexLaunchArgs.ts";
25
26const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
27const decodeSettings = Schema.decodeSync(CodexSettings);
28const decodeCommand = Schema.decodeUnknownSync(
29 Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.Array(Schema.String)])),
30);
31it.live.each(
32 (["managed", "local"] as const).flatMap((source) =>
33 (["primary", "additional"] as const).map((account) => ({ source, account })),
34 ),
35)(
36 "$source Codex $account account shares home state without routing owned tokens through ambient CLI overrides",
37 ({ source, account }) =>
38 Effect.gen(function* () {
39 const instanceId = ProviderInstanceId.make(
40 account === "primary" ? "codex" : "codex-personal",
41 );
42 const fs = yield* FileSystem.FileSystem;
43 const path = yield* Path.Path;
44 const sharedHome = yield* fs.makeTempDirectoryScoped({ prefix: "codex-shared-home-" });
45 yield* fs.writeFileString(path.join(sharedHome, "auth.json"), "native-auth-unchanged");
46 yield* fs.writeFileString(path.join(sharedHome, "config.toml"), "# shared config\n");
47 const data = new Map<string, Uint8Array>();
48 let renewals = 0;
49 const secrets = ServerSecretStore.ServerSecretStore.of({
50 get: (key) => Effect.sync(() => Option.fromUndefinedOr(data.get(key))),
51 set: (key, value) =>
52 Effect.sync(() => {
53 data.set(key, value);
54 }),
55 remove: (key) =>
56 Effect.sync(() => {
57 data.delete(key);
58 }),
59 create: () => Effect.die("unused"),
60 getOrCreateRandom: () => Effect.die("unused"),
61 });
62 let leases = 0;
63 const executable = {
64 executablePath:
65 source === "managed" ? "/isolated/tools/codex/0.156.1/bin/codex" : "/user/bin/codex",
66 managedVersionDirectory: source === "managed" ? "/isolated/tools/codex/0.156.1" : null,
67 source,
68 version: "0.156.1",
69 };
70 const layerInstaller = Layer.mock(CodexInstallation.CodexInstallation)({
71 managedDirectory: "/isolated/tools/codex",
72 resolve: () => Effect.succeed(executable),
73 acquire: () =>
74 Effect.gen(function* () {
75 leases++;
76 yield* Effect.addFinalizer(() =>
77 Effect.sync(() => {
78 leases--;
79 }),
80 );
81 return executable;
82 }),
83 });
84 yield* Effect.gen(function* () {
85 const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId);
86 const json = yield* encodeJson({
87 clientId: "oaiapp_test",
88 accessToken: "dummy-owned-access",
89 refreshToken: "dummy-refresh",
90 expiresAt: (yield* Clock.currentTimeMillis) + 3_600_000,
91 earliestRefreshAt: null,
92 scopes: ["chatgpt.tokens.use.direct"],
93 subject: "test-user",
94 email: null,
95 });
96 yield* store.set(new TextEncoder().encode(json));
97 const ambient = {
98 CODEX_HOME: "/user/.codex",
99 ACCESS_TOKEN: "ambient-bearer",
100 T3CODE_HOME: path.join(sharedHome, "wrong-server-home"),
101 OPENAI_API_KEY: "dummy-global-key",
102 OPENAI_BASE_URL: "https://user-proxy.test",
103 T3CODE_CODEX_LAUNCH_ARGS: "--config model_provider=global-proxy",
104 PATH: process.env.PATH,
105 SystemRoot: process.env.SystemRoot,
106 };
107 const runtime = yield* makeCodexManagedRuntime({
108 instanceId,
109 enabled: true,
110 config: decodeSettings({ setupMode: "managed", homePath: sharedHome }),
111 environment: ambient,
112 });
113 yield* Effect.gen(function* () {
114 const effective = yield* runtime.resolve;
115 assert.strictEqual(leases, 1);
116 assert.strictEqual(effective.config.binaryPath, executable.executablePath);
117 assert.notStrictEqual(effective.config.homePath, ambient.CODEX_HOME);
118 assert.equal(runtime.homeLayout.sharedHomePath, sharedHome);
119 if (account === "primary") {
120 assert.equal(effective.config.homePath, sharedHome);
121 assert.equal(runtime.homeLayout.mode, "direct");
122 } else {
123 assert.include(effective.config.homePath, instanceId);
124 assert.include(effective.config.homePath, "userdata/providers/codex");
125 assert.equal(runtime.homeLayout.mode, "authOverlay");
126 assert.equal(
127 yield* fs.readLink(path.join(effective.config.homePath, "sessions")),
128 path.join(sharedHome, "sessions"),
129 );
130 assert.equal(
131 yield* fs.readLink(path.join(effective.config.homePath, "config.toml")),
132 path.join(sharedHome, "config.toml"),
133 );
134 assert.isFalse(yield* fs.exists(path.join(effective.config.homePath, "auth.json")));
135 }
136 assert.isUndefined(effective.environment.ACCESS_TOKEN);
137 assert.isUndefined(effective.environment.OPENAI_API_KEY);
138 assert.isUndefined(effective.environment.OPENAI_BASE_URL);
139 assert.isUndefined(effective.environment.T3CODE_CODEX_LAUNCH_ARGS);
140 const args = codexAppServerArgs(effective.config.launchArgs);
141 assert.include(args, 'model_provider="openai_token_sharing"');
142 const provider = args.find((arg) =>
143 arg.startsWith("model_providers.openai_token_sharing="),
144 )!;
145 assert.include(provider, 'base_url="https://api.openai.com/v1"');
146 assert.include(provider, 'model_catalog_url="https://api.openai.com/v1/models"');
147 assert.notInclude(provider, "env_key");
148 assert.include(provider, "refresh_interval_ms=0");
149 // regression: #16132 Codex fetches each token through this helper, so a running
150 // session picks up renewals instead of keeping the token it launched with.
151 if (source === "managed" && account === "primary") {
152 const commandMatch = /auth=\{command=(.*),args=(\[.*\]),timeout_ms=/u.exec(provider);
153 assert.isNotNull(commandMatch);
154 const [command, helperArgs] = decodeCommand(
155 `[${commandMatch![1]},${commandMatch![2]}]`,
156 );
157 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
158 const runHelper = Effect.gen(function* () {
159 const child = yield* spawner.spawn(
160 ChildProcess.make(command, helperArgs, {
161 extendEnv: false,
162 env: effective.environment,
163 }),
164 );
165 const [stdout, stderr, code] = yield* Effect.all(
166 [
167 child.stdout.pipe(Stream.decodeText(), Stream.mkString),
168 child.stderr.pipe(Stream.decodeText(), Stream.mkString),
169 child.exitCode,
170 ],
171 { concurrency: "unbounded" },
172 );
173 return { stdout, stderr, code: Number(code) };
174 }).pipe(Effect.scoped);
175 assert.deepEqual(yield* runHelper, {
176 stdout: "dummy-owned-access",
177 stderr: "",
178 code: 0,
179 });
180 const saved = Option.getOrThrow(yield* runtime.auth.read);
181 const expired = yield* encodeJson({ ...saved, expiresAt: 0 });
182 yield* store.set(new TextEncoder().encode(expired));
183 assert.deepEqual(yield* runHelper, { stdout: "renewed-access", stderr: "", code: 0 });
184 assert.equal(renewals, 1);
185 assert.equal(
186 Option.getOrThrow(yield* runtime.auth.read).refreshToken,
187 "renewed-refresh",
188 );
189 assert.equal((yield* runtime.resolve).revision, effective.revision);
190 const replaced = yield* encodeJson({ ...saved, subject: "replacement-user" });
191 yield* store.set(new TextEncoder().encode(replaced));
192 const refused = yield* runHelper;
193 assert.equal(refused.code, 1);
194 assert.equal(refused.stdout, "");
195 assert.isFalse(yield* fs.exists(ambient.T3CODE_HOME));
196 }
197 assert.include(args, "features.api_key_model_discovery=true");
198 assert.include(args, "features.multi_agent=false");
199 assert.include(args, "features.multi_agent_v2=false");
200 assert.notInclude(effective.config.launchArgs, "model_catalog_json");
201 assert.notInclude(effective.config.launchArgs, "x-openai-chatpass-test");
202 assert.include(provider, "supports_websockets=false");
203 assert.include(provider, "requires_openai_auth=false");
204 for (const secret of ["dummy-owned-access", "dummy-refresh", "ambient-bearer"]) {
205 assert.notInclude(effective.config.launchArgs, secret);
206 assert.notInclude(JSON.stringify(effective.environment), secret);
207 }
208 assert.strictEqual(ambient.CODEX_HOME, "/user/.codex");
209 }).pipe(Effect.scoped);
210 assert.strictEqual(leases, 0);
211 yield* runtime.auth.controller.logout(Effect.void);
212 assert.equal(
213 yield* fs.readFileString(path.join(sharedHome, "auth.json")),
214 "native-auth-unchanged",
215 );
216 }).pipe(
217 Effect.provide(CodexManagedTokenBroker.layer),
218 Effect.provideService(HostProcess.Arguments, [
219 process.execPath,
220 NodeURL.fileURLToPath(new URL("../bin.ts", import.meta.url)),
221 ]),
222 Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
223 Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, {
224 getEnvironmentId: Effect.succeed(
225 EnvironmentId.make("00000000-0000-4000-8000-000000000001"),
226 ),
227 }),
228 Effect.provide(layerInstaller),
229 Effect.provideService(
230 HttpClient.HttpClient,
231 HttpClient.make((request) =>
232 Effect.sync(() => {
233 assert.isTrue(
234 [
235 "https://auth.openai.com/.well-known/openid-configuration",
236 "https://auth.openai.com/revoke",
237 "https://auth.openai.com/api/accounts/oauth/token",
238 ].includes(request.url),
239 );
240 if (request.url.endsWith("/token")) {
241 renewals++;
242 return HttpClientResponse.fromWeb(
243 request,
244 Response.json({
245 access_token: "renewed-access",
246 refresh_token: "renewed-refresh",
247 token_type: "Bearer",
248 expires_in: 3600,
249 scope: "chatgpt.tokens.use.direct",
250 }),
251 );
252 }
253 return HttpClientResponse.fromWeb(
254 request,
255 request.url.endsWith("/revoke")
256 ? new Response(null, { status: 200 })
257 : Response.json({
258 issuer: "https://auth.openai.com",
259 authorization_endpoint: "https://auth.openai.com/api/accounts/authorize",
260 token_endpoint: "https://auth.openai.com/api/accounts/oauth/token",
261 jwks_uri: "https://auth.openai.com/jwks",
262 revocation_endpoint: "https://auth.openai.com/revoke",
263 }),
264 );
265 }),
266 ),
267 ),
268 );
269 }).pipe(
270 Effect.scoped,
271 Effect.provide(
272 ServerConfig.layerTest(process.cwd(), {
273 prefix: "t3-managed-runtime-",
274 }).pipe(Layer.provideMerge(NodeServices.layer)),
275 ),
276 ),
277);