Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CodexManagedRuntime.ts

141 lines5.6 KB

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;
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 // Catalog models declaring multi_agent_version still get agent tools without this.
32 "agents.enabled=false",
33 ]
34 .map((value) => `-c ${JSON.stringify(value)}`)
35 .join(" ");
36​
37export const makeCodexManagedRuntime = Effect.fn("makeCodexManagedRuntime")(function* (options: {
38 readonly instanceId: ProviderInstanceId;
39 readonly enabled: boolean;
40 readonly environment: NodeJS.ProcessEnv;
41 readonly config: CodexSettings;
42}) {
43 const installation = yield* CodexInstallation.CodexInstallation;
44 const config = yield* ServerConfig.ServerConfig;
45 const fs = yield* FileSystem.FileSystem;
46 const path = yield* Path.Path;
47 const broker = yield* CodexManagedTokenBroker.CodexManagedTokenBroker;
48 const environmentIdentity = yield* ServerEnvironment.ServerEnvironmentIdentity;
49 const environmentId = yield* environmentIdentity.getEnvironmentId;
50 const invocation = yield* resolveSelfInvocation();
51 const auth = yield* makeCodexChatGptAuth({
52 instanceId: options.instanceId,
53 defaultReturnUrl: new URL(
54 "/welcome",
55 config.devUrl ?? resolveLocalOrigin(config.host, config.port),
56 ).toString(),
57 });
58 const homeLayout = yield* resolveManagedCodexHomeLayout(
59 config.stateDir,
60 options.instanceId,
61 options.config,
62 );
63 const homePath = homeLayout.effectiveHomePath ?? homeLayout.sharedHomePath;
64 const resolve = Effect.gen(function* () {
65 // Establish renewal availability before auth.access can consume a refresh token.
66 const endpoint = yield* broker.endpoint.pipe(
67 Effect.mapError(
68 (cause) =>
69 new ProviderSetupError({
70 instanceId: options.instanceId,
71 operation: "runtime",
72 detail:
73 "Could not prepare the private managed Codex token listener. Restart T3 and retry.",
74 cause,
75 }),
76 ),
77 );
78 const executable = yield* installation.acquire().pipe(
79 Effect.mapError(
80 () =>
81 new ProviderSetupError({
82 instanceId: options.instanceId,
83 operation: "install",
84 detail: "Set up managed Codex before starting a session.",
85 }),
86 ),
87 );
88 const credentials = yield* auth.access;
89 const profileKey = yield* auth.profileKey(credentials);
90 const authArgs = selfInvocationArgs(invocation, [
91 "__managed-chatgpt-token",
92 endpoint,
93 options.instanceId,
94 environmentId,
95 profileKey,
96 ]);
97 yield* materializeCodexShadowHome(homeLayout).pipe(
98 Effect.provideService(FileSystem.FileSystem, fs),
99 Effect.provideService(Path.Path, path),
100 Effect.mapError(
101 (cause) =>
102 new ProviderSetupError({
103 instanceId: options.instanceId,
104 operation: "runtime",
105 detail: cause.message,
106 }),
107 ),
108 );
109 yield* fs.makeDirectory(homePath, { recursive: true }).pipe(
110 Effect.mapError(
111 () =>
112 new ProviderSetupError({
113 instanceId: options.instanceId,
114 operation: "runtime",
115 detail: "Could not prepare the managed Codex runtime.",
116 }),
117 ),
118 );
119 // Ambient CLI overrides cannot redirect a T3-owned token to a different provider.
120 const environment: NodeJS.ProcessEnv = {
121 ...options.environment,
122 CODEX_HOME: homePath,
123 };
124 delete environment.ACCESS_TOKEN;
125 delete environment.T3CODE_CODEX_LAUNCH_ARGS;
126 delete environment.OPENAI_API_KEY;
127 delete environment.OPENAI_BASE_URL;
128 return {
129 config: decodeSettings({
130 enabled: options.enabled,
131 setupMode: "managed",
132 binaryPath: executable.executablePath,
133 homePath,
134 launchArgs: managedCodexLaunchArgs(invocation.command, authArgs),
135 }),
136 environment,
137 revision: profileKey,
138 } satisfies CodexEffectiveRuntime;
139 });
140 return { auth, resolve, installation, homePath, homeLayout };
141});