The best way to control Claude Code, Codex and more from any computer or phone
fix(server): renew active managed Codex turns through native auth (#21787)
Julius Marminge committed
Oct 22, 2026 at 16:41 UTC
f5cf9a02de10fa61ef180020a607279351c8b4cb
10 files changed
+287
-51
apps/server/src/bin.ts
+6
-3
@@ -1,8 +1,8 @@
1
/**
2
* Every ACP agent spawns `t3 acp-mcp-bridge` while opening its session, and terminal-fallback
3
* agents run `t3 acp-mcp-call` per tool call, so their startup sits on first-message latency.
4
- * Both dispatch here before the full CLI module graph (seconds of evaluation) loads; everything
5
- * else defers to the real CLI in ./binCli.ts.
4
+ * They and Codex's managed-token helper dispatch before the full CLI module graph (seconds
5
+ * of evaluation) loads; everything else defers to the real CLI in ./binCli.ts.
6
*/
7
import { isEntrypoint } from "./entrypoint.ts";
8
@@ -17,7 +17,10 @@ if (
17
// Guard sockets before either dispatch path can load outbound-capable modules.
18
const { ignoreMacosTypeOfServiceEinval } = await import("./outboundHttp.ts");
19
ignoreMacosTypeOfServiceEinval();
20
- if (command === "acp-mcp-bridge" || command === "acp-mcp-call") {
20
+ if (command === "__managed-chatgpt-token") {
21
+ const { runManagedChatGptTokenCli } = await import("./cli/managedChatGptToken.ts");
22
+ await runManagedChatGptTokenCli(process.argv.slice(3));
23
+ } else if (command === "acp-mcp-bridge" || command === "acp-mcp-call") {
24
const { runAcpMcpCliFastPath } = await import("./mcp/AcpMcpStdioBridge.ts");
25
await runAcpMcpCliFastPath(command, process.argv.slice(3));
26
} else {
apps/server/src/cli/managedChatGptToken.ts
new
+48
@@ -0,0 +1,48 @@
1
+// @effect-diagnostics nodeBuiltinImport:off - Lean self-invoked local IPC client; no auth/store graph.
2
+import * as NodeNet from "node:net";
3
+import * as Effect from "effect/Effect";
4
+import * as Exit from "effect/Exit";
5
+import * as Schema from "effect/Schema";
6
+import * as Protocol from "../provider/CodexManagedTokenProtocol.ts";
7
+
8
+const decodeArguments = Schema.decodeUnknownEffect(
9
+ Schema.Tuple([
10
+ Schema.NonEmptyString,
11
+ Protocol.Request.fields.instanceId,
12
+ Protocol.Request.fields.environmentId,
13
+ Protocol.Request.fields.profileKey,
14
+ ]),
15
+);
16
+const encodeRequest = Schema.encodeSync(Schema.fromJsonString(Protocol.Request));
17
+const decodeResponse = Schema.decodeUnknownEffect(Schema.fromJsonString(Protocol.Response), {
18
+ onExcessProperty: "error",
19
+});
20
+
21
+/** Codex's auth.command protocol is a bare token on stdout, never a CLI diagnostic. */
22
+export async function runManagedChatGptTokenCli(args: ReadonlyArray<string>): Promise<void> {
23
+ const program = Effect.gen(function* () {
24
+ const [endpoint, instanceId, environmentId, profileKey] = yield* decodeArguments(args);
25
+ const socket = yield* Effect.acquireRelease(
26
+ Effect.sync(() => NodeNet.createConnection(endpoint)),
27
+ (socket) => Effect.sync(() => socket.destroy()),
28
+ );
29
+ socket.on("error", () => {});
30
+ socket.once("connect", () =>
31
+ socket.write(encodeRequest({ version: 1, instanceId, environmentId, profileKey }) + "\n"),
32
+ );
33
+ return yield* Protocol.readFrame(
34
+ socket,
35
+ Protocol.RESPONSE_BYTES,
36
+ Protocol.COMMAND_TIMEOUT_MS,
37
+ ).pipe(Effect.flatMap(decodeResponse));
38
+ }).pipe(Effect.scoped);
39
+ const result = await Effect.runPromiseExit(program);
40
+ if (Exit.isFailure(result)) {
41
+ process.stderr.write(
42
+ "Could not access the managed ChatGPT connection. Reconnect in T3 Code.\n",
43
+ );
44
+ process.exitCode = 1;
45
+ return;
46
+ }
47
+ process.stdout.write(result.value.token);
48
+}
apps/server/src/provider/CodexManagedRuntime.test.ts
+96
-14
@@ -1,4 +1,9 @@
1
// @effect-diagnostics nodeBuiltinImport:off - checks the host's default Codex directory without writing to it.
2
+import * as NodeURL from "node:url";
3
+import * as HostProcess from "@t3tools/shared/HostProcess";
4
+import * as Stream from "effect/Stream";
5
+import { ChildProcess, ChildProcessSpawner } from "effect/process";
6
+import * as CodexManagedTokenBroker from "./CodexManagedTokenBroker.ts";
7
import * as NodeServices from "@effect/platform-node/NodeServices";
8
import { assert, it } from "@effect/vitest";
9
import { CodexSettings, EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
@@ -20,7 +25,10 @@ import { codexAppServerArgs } from "./codexLaunchArgs.ts";
25
26
const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
27
const decodeSettings = Schema.decodeSync(CodexSettings);
23
-it.effect.each(
28
+const decodeCommand = Schema.decodeUnknownSync(
29
+ Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.Array(Schema.String)])),
30
+);
31
+it.live.each(
32
(["managed", "local"] as const).flatMap((source) =>
33
(["primary", "additional"] as const).map((account) => ({ source, account })),
34
),
@@ -37,6 +45,7 @@ it.effect.each(
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) =>
@@ -87,10 +96,13 @@ it.effect.each(
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",
93
- PATH: "/usr/bin",
104
+ PATH: process.env.PATH,
105
+ SystemRoot: process.env.SystemRoot,
106
};
107
const runtime = yield* makeCodexManagedRuntime({
108
instanceId,
@@ -121,27 +133,78 @@ it.effect.each(
133
);
134
assert.isFalse(yield* fs.exists(path.join(effective.config.homePath, "auth.json")));
135
}
124
- assert.strictEqual(effective.environment.ACCESS_TOKEN, "dummy-owned-access");
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);
129
- assert.include(
130
- args,
131
- 'model_providers.openai_token_sharing.base_url="https://api.openai.com/v1"',
132
- );
133
- assert.include(
134
- args,
135
- 'model_providers.openai_token_sharing.model_catalog_url="https://api.openai.com/v1/models"',
136
- );
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");
142
- assert.include(args, "model_providers.openai_token_sharing.supports_websockets=false");
143
- assert.include(args, "model_providers.openai_token_sharing.requires_openai_auth=false");
144
- assert.notInclude(effective.config.launchArgs, "dummy-owned-access");
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);
@@ -151,6 +214,11 @@ it.effect.each(
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(
@@ -166,8 +234,22 @@ it.effect.each(
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")
apps/server/src/provider/CodexManagedRuntime.ts
+43
-18
@@ -5,8 +5,12 @@ import * as FileSystem from "effect/FileSystem";
5
import * as Path from "effect/Path";
6
import * as Schema from "effect/Schema";
7
import * as ServerConfig from "../config.ts";
8
+import * as CodexManagedTokenBroker from "./CodexManagedTokenBroker.ts";
9
+import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
10
+import { resolveSelfInvocation, selfInvocationArgs } from "@t3tools/shared/nodeRuntime";
11
import * as CodexInstallation from "./CodexInstallation.ts";
12
import { makeCodexChatGptAuth } from "./CodexChatGptAuth.ts";
13
+import { COMMAND_TIMEOUT_MS } from "./CodexManagedTokenProtocol.ts";
14
import { materializeCodexShadowHome } from "./Drivers/CodexHomeLayout.ts";
15
16
export interface CodexEffectiveRuntime {
@@ -15,21 +19,17 @@ export interface CodexEffectiveRuntime {
19
readonly revision: string;
20
}
21
const decodeSettings = Schema.decodeSync(CodexSettings);
18
-const managedCodexLaunchArgs = [
19
- 'model_provider="openai_token_sharing"',
20
- 'model_providers.openai_token_sharing.name="OpenAI Token Sharing"',
21
- 'model_providers.openai_token_sharing.base_url="https://api.openai.com/v1"',
22
- 'model_providers.openai_token_sharing.model_catalog_url="https://api.openai.com/v1/models"',
23
- "features.api_key_model_discovery=true",
24
- "features.multi_agent=false",
25
- "features.multi_agent_v2=false",
26
- 'model_providers.openai_token_sharing.env_key="ACCESS_TOKEN"',
27
- 'model_providers.openai_token_sharing.wire_api="responses"',
28
- "model_providers.openai_token_sharing.requires_openai_auth=false",
29
- "model_providers.openai_token_sharing.supports_websockets=false",
30
-]
31
- .map((value) => `-c '${value}'`)
32
- .join(" ");
22
+const managedCodexLaunchArgs = (command: string, args: ReadonlyArray<string>) =>
23
+ [
24
+ 'model_provider="openai_token_sharing"',
25
+ // Codex persists this provider ID in rollouts and needs it unchanged to resume.
26
+ `model_providers.openai_token_sharing={name="OpenAI Token Sharing",base_url="https://api.openai.com/v1",model_catalog_url="https://api.openai.com/v1/models",wire_api="responses",requires_openai_auth=false,supports_websockets=false,auth={command=${JSON.stringify(command)},args=${JSON.stringify(args)},timeout_ms=${COMMAND_TIMEOUT_MS},refresh_interval_ms=0}}`,
27
+ "features.api_key_model_discovery=true",
28
+ "features.multi_agent=false",
29
+ "features.multi_agent_v2=false",
30
+ ]
31
+ .map((value) => `-c ${JSON.stringify(value)}`)
32
+ .join(" ");
33
34
export const makeCodexManagedRuntime = Effect.fn("makeCodexManagedRuntime")(function* (options: {
35
readonly instanceId: ProviderInstanceId;
@@ -41,6 +41,10 @@ export const makeCodexManagedRuntime = Effect.fn("makeCodexManagedRuntime")(func
41
const config = yield* ServerConfig.ServerConfig;
42
const fs = yield* FileSystem.FileSystem;
43
const path = yield* Path.Path;
44
+ const broker = yield* CodexManagedTokenBroker.CodexManagedTokenBroker;
45
+ const environmentIdentity = yield* ServerEnvironment.ServerEnvironmentIdentity;
46
+ const environmentId = yield* environmentIdentity.getEnvironmentId;
47
+ const invocation = yield* resolveSelfInvocation();
48
const auth = yield* makeCodexChatGptAuth({
49
instanceId: options.instanceId,
50
defaultReturnUrl: new URL(
@@ -55,6 +59,19 @@ export const makeCodexManagedRuntime = Effect.fn("makeCodexManagedRuntime")(func
59
);
60
const homePath = homeLayout.effectiveHomePath ?? homeLayout.sharedHomePath;
61
const resolve = Effect.gen(function* () {
62
+ // Establish renewal availability before auth.access can consume a refresh token.
63
+ const endpoint = yield* broker.endpoint.pipe(
64
+ Effect.mapError(
65
+ (cause) =>
66
+ new ProviderSetupError({
67
+ instanceId: options.instanceId,
68
+ operation: "runtime",
69
+ detail:
70
+ "Could not prepare the private managed Codex token listener. Restart T3 and retry.",
71
+ cause,
72
+ }),
73
+ ),
74
+ );
75
const executable = yield* installation.acquire().pipe(
76
Effect.mapError(
77
() =>
@@ -66,6 +83,14 @@ export const makeCodexManagedRuntime = Effect.fn("makeCodexManagedRuntime")(func
83
),
84
);
85
const credentials = yield* auth.access;
86
+ const profileKey = yield* auth.profileKey(credentials);
87
+ const authArgs = selfInvocationArgs(invocation, [
88
+ "__managed-chatgpt-token",
89
+ endpoint,
90
+ options.instanceId,
91
+ environmentId,
92
+ profileKey,
93
+ ]);
94
yield* materializeCodexShadowHome(homeLayout).pipe(
95
Effect.provideService(FileSystem.FileSystem, fs),
96
Effect.provideService(Path.Path, path),
@@ -91,9 +116,9 @@ export const makeCodexManagedRuntime = Effect.fn("makeCodexManagedRuntime")(func
116
// Ambient CLI overrides cannot redirect a T3-owned token to a different provider.
117
const environment: NodeJS.ProcessEnv = {
118
...options.environment,
94
- ACCESS_TOKEN: credentials.accessToken,
119
CODEX_HOME: homePath,
120
};
121
+ delete environment.ACCESS_TOKEN;
122
delete environment.T3CODE_CODEX_LAUNCH_ARGS;
123
delete environment.OPENAI_API_KEY;
124
delete environment.OPENAI_BASE_URL;
@@ -103,10 +128,10 @@ export const makeCodexManagedRuntime = Effect.fn("makeCodexManagedRuntime")(func
128
setupMode: "managed",
129
binaryPath: executable.executablePath,
130
homePath,
106
- launchArgs: managedCodexLaunchArgs,
131
+ launchArgs: managedCodexLaunchArgs(invocation.command, authArgs),
132
}),
133
environment,
109
- revision: credentials.accessToken,
134
+ revision: profileKey,
135
} satisfies CodexEffectiveRuntime;
136
});
137
return { auth, resolve, installation, homePath, homeLayout };
apps/server/src/provider/Drivers/CodexDriver.test.ts
+57
-9
@@ -1,4 +1,5 @@
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
@@ -58,6 +59,12 @@ const layerDeps = ServerConfig.layerTest(process.cwd(), {
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")),
@@ -96,10 +103,13 @@ const noSpawn = ChildProcessSpawner.make(() =>
103
const encodeCredentials = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
104
105
it.layer(layerTest)("CodexDriver", (it) => {
99
- it.effect("disconnect refreshes a restored managed account while its auth flow is idle", () =>
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) =>
@@ -126,6 +136,17 @@ it.layer(layerTest)("CodexDriver", (it) => {
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,
@@ -187,13 +208,17 @@ it.layer(layerTest)("CodexDriver", (it) => {
208
Effect.provideService(
209
ChildProcessSpawner.ChildProcessSpawner,
210
ChildProcessSpawner.make(() =>
190
- Effect.fail(
191
- PlatformError.badArgument({
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",
195
- }),
196
- ),
220
+ });
221
+ }),
222
),
223
),
224
);
@@ -209,7 +234,21 @@ it.layer(layerTest)("CodexDriver", (it) => {
234
Effect.forkScoped,
235
);
236
yield* Deferred.await(startupChecksInterrupted);
212
- const restored = yield* instance.snapshot.refresh;
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(
@@ -246,7 +285,9 @@ it.layer(layerTest)("CodexDriver", (it) => {
285
const launch = launches[0]!;
286
expect(launch.settings.binaryPath).toBe(executable.executablePath);
287
expect(launch.settings.launchArgs).toContain("openai_token_sharing");
249
- expect(launch.environment.ACCESS_TOKEN).toBe("dummy-owned-access");
288
+ expect(launch.environment.ACCESS_TOKEN).toBeUndefined();
289
+ expect(launch.settings.launchArgs).toContain("__managed-chatgpt-token");
290
+ expect(launch.settings.launchArgs).not.toContain("dummy-owned-access");
291
expect(launch.environment.OPENAI_API_KEY).toBeUndefined();
292
expect(launch.environment.CODEX_HOME).toBe(launch.settings.homePath);
293
const before = yield* instance.auth!.subscribe("test-owner").pipe(Stream.runHead);
@@ -273,8 +314,10 @@ it.layer(layerTest)("CodexDriver", (it) => {
314
"https://auth.openai.com/revoke",
315
"https://api.openai.com/v1/models",
316
]).toContain(request.url);
276
- if (request.url.endsWith("/models"))
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")
@@ -291,7 +334,12 @@ it.layer(layerTest)("CodexDriver", (it) => {
334
),
335
),
336
);
294
- }).pipe(Effect.scoped),
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)(
apps/server/src/provider/Drivers/CodexDriver.ts
+3
-1
@@ -53,6 +53,7 @@ import {
53
import { makeManagedCodexProvider } from "./CodexManagedProvider.ts";
54
import { codexUsageReader } from "./codexUsage.ts";
55
import * as CodexInstallation from "../CodexInstallation.ts";
56
+import * as CodexManagedTokenBroker from "../CodexManagedTokenBroker.ts";
57
import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
58
import * as ServerEnvironment from "../../environment/ServerEnvironment.ts";
59
import * as HostProcess from "@t3tools/shared/HostProcess";
@@ -97,7 +98,8 @@ export type CodexDriverEnv =
98
| ServerConfig.ServerConfig
99
| ServerSecretStore.ServerSecretStore
100
| ServerEnvironment.ServerEnvironmentIdentity
100
- | CodexInstallation.CodexInstallation;
101
+ | CodexInstallation.CodexInstallation
102
+ | CodexManagedTokenBroker.CodexManagedTokenBroker;
103
104
export const CodexDriver: ProviderDriver<
105
CodexSettings,
apps/server/src/provider/Drivers/CodexManagedProvider.ts
+22
-6
@@ -1,4 +1,9 @@
1
-import { ProviderDriverKind, TextGenerationError, type CodexSettings } from "@t3tools/contracts";
1
+import {
2
+ ProviderDriverKind,
3
+ ProviderSetupError,
4
+ TextGenerationError,
5
+ type CodexSettings,
6
+} from "@t3tools/contracts";
7
import * as Effect from "effect/Effect";
8
import * as FileSystem from "effect/FileSystem";
9
import * as Path from "effect/Path";
@@ -128,10 +133,21 @@ export const makeManagedCodexProvider = Effect.fn("makeManagedCodexProvider")(fu
133
effective.environment,
134
managedAuth,
135
);
131
- const models = yield* chatGptModels(
132
- effective.environment.ACCESS_TOKEN!,
133
- draft.models,
134
- ).pipe(Effect.provideService(HttpClient.HttpClient, http));
136
+ const credentials = yield* runtime.auth.access;
137
+ // Another server can replace the saved profile while the native probe runs.
138
+ // Never send that account's token with the launch profile's catalog labels.
139
+ if (
140
+ (yield* runtime.auth.profileKey(credentials)) !== effective.revision ||
141
+ (yield* runtime.auth.profileKey(saved.value)) !== effective.revision
142
+ )
143
+ return yield* new ProviderSetupError({
144
+ instanceId,
145
+ operation: "models",
146
+ detail: "The ChatGPT connection changed while checking Codex. Retry.",
147
+ });
148
+ const models = yield* chatGptModels(credentials.accessToken, draft.models).pipe(
149
+ Effect.provideService(HttpClient.HttpClient, http),
150
+ );
151
return { ...draft, models };
152
}),
153
),
@@ -225,7 +241,7 @@ export const makeManagedCodexProvider = Effect.fn("makeManagedCodexProvider")(fu
241
Effect.forkScoped,
242
);
243
const resolveRuntime = runtime.auth.controller.withAccess!(runtime.resolve);
228
- // Launch settings resolve per session from the signed-in token. The registry
244
+ // Launch settings bind the refresh command to the signed-in profile. The registry
245
// already wraps openSession in withAccess, so resolve without re-entering it.
246
const orchestrationAdapter = yield* createCodexAdapterV2(input, {
247
onUsageLimits: (update) => snapshot.applyUsageLimits(update),
apps/server/src/provider/ProviderInstanceRegistry.test.ts
+6
@@ -1,5 +1,6 @@
1
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
2
import * as CodexInstallation from "./CodexInstallation.ts";
3
+import * as CodexManagedTokenBroker from "./CodexManagedTokenBroker.ts";
4
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
5
import * as ClaudeSdk from "@anthropic-ai/claude-agent-sdk";
6
import { describe, expect, it } from "@effect/vitest";
@@ -154,6 +155,11 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => {
155
const layerBaseDeps = ServerConfig.layerTest(process.cwd(), {
156
prefix: "provider-instance-registry-test",
157
}).pipe(
158
+ Layer.provideMerge(
159
+ Layer.mock(CodexManagedTokenBroker.CodexManagedTokenBroker)({
160
+ endpoint: Effect.succeed("unused-private-pipe"),
161
+ }),
162
+ ),
163
Layer.provideMerge(NodeServices.layer),
164
Layer.provideMerge(
165
Layer.mock(CodexInstallation.CodexInstallation)({
apps/server/src/provider/ProviderRegistry.test.ts
+4
@@ -1,6 +1,7 @@
1
import { vi } from "vite-plus/test";
2
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
3
import * as CodexInstallation from "./CodexInstallation.ts";
4
+import * as CodexManagedTokenBroker from "./CodexManagedTokenBroker.ts";
5
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
6
import * as NodeServices from "@effect/platform-node/NodeServices";
7
import { describe, it, assert, expect } from "@effect/vitest";
@@ -307,6 +308,9 @@ const awaitPersistedProvider = (
308
const layerTestNodeServices = Layer.mergeAll(
309
ProviderLatestVersions.layer,
310
NodeServices.layer,
311
+ Layer.mock(CodexManagedTokenBroker.CodexManagedTokenBroker)({
312
+ endpoint: Effect.succeed("unused-private-pipe"),
313
+ }),
314
Layer.mock(CodexInstallation.CodexInstallation)({
315
managedDirectory: "unused-managed-installation",
316
}),
apps/server/src/server.ts
+2
@@ -123,6 +123,7 @@ import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
123
import * as AuthHttp from "./auth/http.ts";
124
import * as ReplayMarkers from "./auth/replayMarkers.ts";
125
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
126
+import * as CodexManagedTokenBroker from "./provider/CodexManagedTokenBroker.ts";
127
import * as WebhookRoute from "./scheduledTasks/webhookRoute.ts";
128
import * as RelayDeliveryProof from "./scheduledTasks/RelayDeliveryProof.ts";
129
import * as HeldHooksWaker from "./relay/HeldHooksWaker.ts";
@@ -653,6 +654,7 @@ const layerRuntimeCoreDependencies = layerRuntimeCoreDependenciesBase.pipe(
654
Layer.provideMerge(ProjectEnrichmentService.layer),
655
Layer.provideMerge(Layer.mergeAll(NativeAppIconResolver.layer, layerProjectFaviconResolver)),
656
Layer.provideMerge(layerRepositoryIdentityResolver),
657
+ Layer.provideMerge(CodexManagedTokenBroker.layer),
658
Layer.provideMerge(layerServerEnvironment),
659
Layer.provideMerge(layerAuth),
660
Layer.provideMerge(ServerSecretStore.layer),