Open History to see the last commit
1import { resolveManagedCodexHomeLayout } from "./CodexManagedHome.ts";
2import { CodexSettings, ProviderSetupError, type ProviderInstanceId } from "@t3tools/contracts";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Path from "effect/Path";
6import * as Schema from "effect/Schema";
7import * as ServerConfig from "../config.ts";
8import { resolveLocalOrigin } from "../startupAccess.ts";
9import * as CodexManagedTokenBroker from "./CodexManagedTokenBroker.ts";
10import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
11import { resolveSelfInvocation, selfInvocationArgs } from "@t3tools/shared/nodeRuntime";
12import * as CodexInstallation from "./CodexInstallation.ts";
13import { makeCodexChatGptAuth } from "./CodexChatGptAuth.ts";
14import { COMMAND_TIMEOUT_MS } from "./CodexManagedTokenProtocol.ts";
15import { materializeCodexShadowHome } from "./Drivers/CodexHomeLayout.ts";
16
17export interface CodexEffectiveRuntime {
18 readonly config: CodexSettings;
19 readonly environment: NodeJS.ProcessEnv;
20 readonly revision: string;
21}
22const decodeSettings = Schema.decodeSync(CodexSettings);
23const managedCodexLaunchArgs = (command: string, args: ReadonlyArray<string>) =>
24 [
25 'model_provider="openai_token_sharing"',
26 // Codex persists this provider ID in rollouts and needs it unchanged to resume.
27 `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}}`,
28 "features.api_key_model_discovery=true",
29 "features.multi_agent=false",
30 "features.multi_agent_v2=false",
31 ]
32 .map((value) => `-c ${JSON.stringify(value)}`)
33 .join(" ");
34
35export const makeCodexManagedRuntime = Effect.fn("makeCodexManagedRuntime")(function* (options: {
36 readonly instanceId: ProviderInstanceId;
37 readonly enabled: boolean;
38 readonly environment: NodeJS.ProcessEnv;
39 readonly config: CodexSettings;
40}) {
41 const installation = yield* CodexInstallation.CodexInstallation;
42 const config = yield* ServerConfig.ServerConfig;
43 const fs = yield* FileSystem.FileSystem;
44 const path = yield* Path.Path;
45 const broker = yield* CodexManagedTokenBroker.CodexManagedTokenBroker;
46 const environmentIdentity = yield* ServerEnvironment.ServerEnvironmentIdentity;
47 const environmentId = yield* environmentIdentity.getEnvironmentId;
48 const invocation = yield* resolveSelfInvocation();
49 const auth = yield* makeCodexChatGptAuth({
50 instanceId: options.instanceId,
51 defaultReturnUrl: new URL(
52 "/welcome",
53 config.devUrl ?? resolveLocalOrigin(config.host, config.port),
54 ).toString(),
55 });
56 const homeLayout = yield* resolveManagedCodexHomeLayout(
57 config.stateDir,
58 options.instanceId,
59 options.config,
60 );
61 const homePath = homeLayout.effectiveHomePath ?? homeLayout.sharedHomePath;
62 const resolve = Effect.gen(function* () {
63 // Establish renewal availability before auth.access can consume a refresh token.
64 const endpoint = yield* broker.endpoint.pipe(
65 Effect.mapError(
66 (cause) =>
67 new ProviderSetupError({
68 instanceId: options.instanceId,
69 operation: "runtime",
70 detail:
71 "Could not prepare the private managed Codex token listener. Restart T3 and retry.",
72 cause,
73 }),
74 ),
75 );
76 const executable = yield* installation.acquire().pipe(
77 Effect.mapError(
78 () =>
79 new ProviderSetupError({
80 instanceId: options.instanceId,
81 operation: "install",
82 detail: "Set up managed Codex before starting a session.",
83 }),
84 ),
85 );
86 const credentials = yield* auth.access;
87 const profileKey = yield* auth.profileKey(credentials);
88 const authArgs = selfInvocationArgs(invocation, [
89 "__managed-chatgpt-token",
90 endpoint,
91 options.instanceId,
92 environmentId,
93 profileKey,
94 ]);
95 yield* materializeCodexShadowHome(homeLayout).pipe(
96 Effect.provideService(FileSystem.FileSystem, fs),
97 Effect.provideService(Path.Path, path),
98 Effect.mapError(
99 (cause) =>
100 new ProviderSetupError({
101 instanceId: options.instanceId,
102 operation: "runtime",
103 detail: cause.message,
104 }),
105 ),
106 );
107 yield* fs.makeDirectory(homePath, { recursive: true }).pipe(
108 Effect.mapError(
109 () =>
110 new ProviderSetupError({
111 instanceId: options.instanceId,
112 operation: "runtime",
113 detail: "Could not prepare the managed Codex runtime.",
114 }),
115 ),
116 );
117 // Ambient CLI overrides cannot redirect a T3-owned token to a different provider.
118 const environment: NodeJS.ProcessEnv = {
119 ...options.environment,
120 CODEX_HOME: homePath,
121 };
122 delete environment.ACCESS_TOKEN;
123 delete environment.T3CODE_CODEX_LAUNCH_ARGS;
124 delete environment.OPENAI_API_KEY;
125 delete environment.OPENAI_BASE_URL;
126 return {
127 config: decodeSettings({
128 enabled: options.enabled,
129 setupMode: "managed",
130 binaryPath: executable.executablePath,
131 homePath,
132 launchArgs: managedCodexLaunchArgs(invocation.command, authArgs),
133 }),
134 environment,
135 revision: profileKey,
136 } satisfies CodexEffectiveRuntime;
137 });
138 return { auth, resolve, installation, homePath, homeLayout };
139});