Open History to see the last commit
1import { CodexSettings, ProviderDriverKind } from "@t3tools/contracts";
2import * as Digest from "effect/crypto/Digest";
3import * as SecureRandom from "effect/crypto/SecureRandom";
4import type * as Signature from "effect/crypto/Signature";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Option from "effect/Option";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11import * as Stream from "effect/Stream";
12import { HttpClient, HttpClientResponse } from "effect/http";
13import { ChildProcessSpawner } from "effect/process";
14
15import type * as CodexUsageHistory from "../../usage/CodexUsageHistory.ts";
16import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
17import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
18import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
19import * as ServerConfig from "../../config.ts";
20import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
21import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
22import {
23 createCodexAdapterV2,
24 type CodexAdapterV2DriverEnv,
25} from "../../orchestration-v2/Adapters/CodexAdapterV2.ts";
26import { ProviderDriverError } from "../Errors.ts";
27import * as ResetCreditCoordinator from "../resetCreditCoordinator.ts";
28import {
29 checkCodexProviderStatus,
30 makePendingCodexProvider,
31 probeCodexSkillsForCwd,
32 withCodexAppServerClient,
33} from "../CodexProvider.ts";
34import { resolveCodexLaunchArgs } from "../codexLaunchArgs.ts";
35import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
36import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog";
37import { applyCodexModelCatalog } from "../codexModelCatalog.ts";
38import type { ProviderDriver, ProviderInstance } from "@t3tools/provider-core/server/driver";
39import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity";
40import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
41import {
42 enrichProviderSnapshotWithVersionAdvisory,
43 makeCachedProviderMaintenanceResolution,
44 makePackageManagedProviderMaintenanceResolver,
45 resolveProviderMaintenanceCapabilitiesEffect,
46 type ProviderMaintenanceCapabilities,
47} from "@t3tools/provider-core/server/maintenanceResolver";
48import {
49 haveProviderSnapshotSettingsChanged,
50 makeProviderSnapshotSettingsSource,
51 type ProviderSnapshotSettings,
52} from "@t3tools/provider-core/server/snapshotSettings";
53import {
54 codexContinuationIdentity,
55 materializeCodexShadowHome,
56 resolveCodexHomeLayout,
57} from "./CodexHomeLayout.ts";
58import { makeManagedCodexProvider } from "./CodexManagedProvider.ts";
59import { codexUsageReader } from "./codexUsage.ts";
60import * as CodexInstallation from "../CodexInstallation.ts";
61import * as CodexManagedTokenBroker from "../CodexManagedTokenBroker.ts";
62import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
63import * as ServerEnvironment from "../../environment/ServerEnvironment.ts";
64import * as HostProcess from "@t3tools/shared/HostProcess";
65const decodeCodexSettings = Schema.decodeSync(CodexSettings);
66
67const DRIVER_KIND = ProviderDriverKind.make("codex");
68const CODEX_STANDALONE_HOME_PATTERN = /^(.*)\/packages\/standalone\//is;
69
70function codexStandaloneHome(commandPath: string): string | null {
71 // Slash replacement preserves indices; Unicode lowercasing can change the path length.
72 const match = CODEX_STANDALONE_HOME_PATTERN.exec(commandPath.replaceAll("\\", "/"));
73 if (!match) {
74 return null;
75 }
76 const home = match[1]!;
77 // Keep root separators: `C:` is drive-relative, and an empty home is not `/`.
78 const isRoot = home === "" || /^[a-z]:$/i.test(home);
79 return commandPath.slice(0, home.length + (isRoot ? 1 : 0));
80}
81
82// Standalone updates locate their install through CODEX_HOME. Account and auth-overlay
83// homes can share an executable, so only the updater uses the executable's owning home.
84function makeCodexMaintenanceResolver(sharedHomePath: string) {
85 return makePackageManagedProviderMaintenanceResolver({
86 provider: DRIVER_KIND,
87 npmPackageName: "@openai/codex",
88 mise: { tool: "codex" },
89 nativeUpdate: {
90 args: ["update"],
91 isCommandPath: (commandPath) => codexStandaloneHome(commandPath) !== null,
92 requiresCommandPath: true,
93 env: (context) => ({
94 CODEX_HOME:
95 codexStandaloneHome(context.realCommandPath) ??
96 codexStandaloneHome(context.resolvedCommandPath) ??
97 sharedHomePath,
98 }),
99 },
100 });
101}
102
103// `codex update` installs this channel's release, which can lag npm's latest tag.
104const CODEX_NATIVE_CHANNEL = "https://releases.openai.com/codex/channels/latest";
105const CodexNativeRelease = Schema.Struct({ tag_name: Schema.String });
106
107function withCodexNativeLatestVersion(
108 capabilities: ProviderMaintenanceCapabilities,
109 http: HttpClient.HttpClient,
110): ProviderMaintenanceCapabilities {
111 if (capabilities.update?.lockKey !== `${DRIVER_KIND}-native`) return capabilities;
112 return {
113 ...capabilities,
114 latestVersion: null,
115 latestVersionCacheKey: CODEX_NATIVE_CHANNEL,
116 lookupLatestVersion: http.get(CODEX_NATIVE_CHANNEL).pipe(
117 Effect.flatMap(HttpClientResponse.filterStatusOk),
118 Effect.flatMap((response) => response.json),
119 Effect.flatMap(Schema.decodeUnknownEffect(CodexNativeRelease)),
120 Effect.map((release) => /^rust-v(\d+\.\d+\.\d+)$/.exec(release.tag_name)?.[1] ?? null),
121 Effect.timeoutOption("4 seconds"),
122 Effect.map(Option.getOrNull),
123 Effect.orElseSucceed(() => null),
124 ),
125 };
126}
127
128export type CodexDriverEnv =
129 | CodexAdapterV2DriverEnv
130 | ProviderHost.ProviderHost
131 | ChildProcessSpawner.ChildProcessSpawner
132 | ResetCreditCoordinator.ResetCreditCoordinator
133 | Digest.Digest
134 | SecureRandom.SecureRandom
135 | Signature.Signature
136 | FileSystem.FileSystem
137 | HttpClient.HttpClient
138 | ProviderLatestVersions.ProviderLatestVersions
139 | ModelCatalog.ModelCatalog
140 | Path.Path
141 | ProviderEventLoggers.ProviderEventLoggers
142 | ServerConfig.ServerConfig
143 | ServerSecretStore.ServerSecretStore
144 | ServerEnvironment.ServerEnvironmentIdentity
145 | CodexInstallation.CodexInstallation
146 | CodexManagedTokenBroker.CodexManagedTokenBroker;
147
148export const CodexDriver: ProviderDriver<
149 CodexSettings,
150 CodexDriverEnv,
151 Path.Path | CodexUsageHistory.CodexUsageHistory
152> = {
153 driverKind: DRIVER_KIND,
154 metadata: {
155 displayName: "Codex",
156 supportsMultipleInstances: true,
157 },
158 configSchema: CodexSettings,
159 defaultConfig: (): CodexSettings => decodeCodexSettings({}),
160 usage: codexUsageReader,
161 create: Effect.fn("CodexDriver.create")(function* ({
162 instanceId,
163 displayName,
164 accentColor,
165 environment,
166 enabled,
167 config,
168 }) {
169 if (config.setupMode === "managed")
170 return yield* makeManagedCodexProvider({
171 instanceId,
172 displayName,
173 accentColor,
174 environment,
175 enabled,
176 config,
177 });
178 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
179 const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator;
180 const fileSystem = yield* FileSystem.FileSystem;
181 const pathService = yield* Path.Path;
182 const httpClient = yield* HttpClient.HttpClient;
183 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
184 const installation = yield* CodexInstallation.CodexInstallation;
185 const modelCatalog = yield* ModelCatalog.ModelCatalog;
186 const currentCatalog = modelCatalog.current(DRIVER_KIND);
187 const processEnv = yield* mergeProviderInstanceEnvironment(
188 environment,
189 yield* HostProcess.Environment,
190 );
191 const environmentHome = processEnv.CODEX_HOME;
192 const homeLayout = yield* resolveCodexHomeLayout(
193 !config.homePath.trim() && !config.shadowHomePath.trim() && environmentHome?.trim()
194 ? { ...config, homePath: environmentHome }
195 : config,
196 );
197 const continuationIdentity = codexContinuationIdentity(homeLayout);
198 const stampIdentity = withInstanceIdentity({
199 instanceId,
200 driverKind: DRIVER_KIND,
201 displayName,
202 accentColor,
203 continuationGroupKey: continuationIdentity.continuationKey,
204 });
205 yield* materializeCodexShadowHome(homeLayout).pipe(
206 Effect.mapError(
207 (cause) =>
208 new ProviderDriverError({
209 driver: DRIVER_KIND,
210 instanceId,
211 detail: cause.message,
212 cause,
213 }),
214 ),
215 );
216 const effectiveConfig = {
217 ...config,
218 enabled,
219 binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),
220 homePath: homeLayout.effectiveHomePath ?? "",
221 } satisfies CodexSettings;
222 const resolveInstallation = yield* makeCachedProviderMaintenanceResolution(
223 resolveProviderMaintenanceCapabilitiesEffect(
224 makeCodexMaintenanceResolver(homeLayout.sharedHomePath),
225 {
226 binaryPath: effectiveConfig.binaryPath,
227 env: processEnv,
228 },
229 ).pipe(
230 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
231 Effect.provideService(FileSystem.FileSystem, fileSystem),
232 Effect.provideService(Path.Path, pathService),
233 ),
234 );
235 const resolveMaintenance: typeof resolveInstallation = (options) =>
236 resolveInstallation(options).pipe(
237 Effect.map((capabilities) => withCodexNativeLatestVersion(capabilities, httpClient)),
238 );
239
240 const orchestrationAdapter = yield* createCodexAdapterV2(
241 {
242 instanceId,
243 displayName,
244 accentColor,
245 environment,
246 enabled,
247 config,
248 },
249 {
250 onUsageLimits: (update) => snapshot.applyUsageLimits(update),
251 models: Effect.suspend(() => snapshot.getSnapshot).pipe(
252 Effect.map((value) => value.models),
253 ),
254 compatibility: installation.compatibility,
255 },
256 ).pipe(
257 Effect.mapError(
258 (cause) =>
259 new ProviderDriverError({
260 driver: DRIVER_KIND,
261 instanceId,
262 detail: "Failed to build Codex orchestration adapter.",
263 cause,
264 }),
265 ),
266 );
267
268 // Kick the TTL-gated manifest refresh in the background and classify with the in-memory
269 // manifest, so a slow or hung fetch never delays the provider check.
270 const checkProvider = modelCatalog.refreshInBackground.pipe(
271 Effect.andThen(
272 Effect.zipWith(
273 checkCodexProviderStatus(effectiveConfig, undefined, processEnv),
274 currentCatalog,
275 (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)),
276 { concurrent: true },
277 ),
278 ),
279 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
280 Effect.provideService(FileSystem.FileSystem, fileSystem),
281 Effect.provideService(Path.Path, pathService),
282 );
283 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
284 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CodexSettings>>({
285 resolveMaintenance,
286 getSettings: snapshotSettings.getSettings,
287 streamSettings: snapshotSettings.streamSettings,
288 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
289 initialSnapshot: (settings) =>
290 Effect.zipWith(
291 makePendingCodexProvider(settings.provider),
292 currentCatalog,
293 (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)),
294 ),
295 checkProvider,
296 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
297 resolveMaintenance().pipe(
298 Effect.flatMap((maintenanceCapabilities) =>
299 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
300 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
301 }),
302 ),
303 Effect.provideService(HttpClient.HttpClient, httpClient),
304 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
305 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
306 ),
307 }).pipe(
308 Effect.mapError(
309 (cause) =>
310 new ProviderDriverError({
311 driver: DRIVER_KIND,
312 instanceId,
313 detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,
314 cause,
315 }),
316 ),
317 );
318 const textGeneration = yield* makeCodexTextGeneration(
319 effectiveConfig,
320 processEnv,
321 snapshot.getSnapshot.pipe(Effect.map((value) => value.models)),
322 );
323 const snapshotForCwd = (cwd: string) =>
324 !effectiveConfig.enabled
325 ? snapshot.getSnapshot
326 : Effect.all([
327 snapshot.getSnapshot,
328 probeCodexSkillsForCwd({
329 binaryPath: effectiveConfig.binaryPath,
330 homePath: effectiveConfig.homePath,
331 launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),
332 cwd,
333 environment: processEnv,
334 }).pipe(
335 Effect.scoped,
336 Effect.timeout("20 seconds"),
337 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
338 ),
339 ]).pipe(
340 Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })),
341 Effect.mapError(
342 (cause) =>
343 new ProviderDriverError({
344 driver: DRIVER_KIND,
345 instanceId,
346 detail: `Failed to probe Codex skills for '${cwd}'`,
347 cause,
348 }),
349 ),
350 );
351
352 // Redemption spends account credit; serialize by the auth.json directory, keep one idempotency key
353 // until the outcome, and bound the wait so a hung app-server cannot hold the account lock.
354 // Auth overlays use effectiveHomePath; the continuation key would conflate them with shared homes.
355 const accountKey = homeLayout.effectiveHomePath ?? homeLayout.sharedHomePath;
356 const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = () =>
357 resetCreditCoordinator
358 .redeem(accountKey, (idempotencyKey) =>
359 Effect.gen(function* () {
360 const { client } = yield* withCodexAppServerClient({
361 binaryPath: effectiveConfig.binaryPath,
362 homePath: effectiveConfig.homePath,
363 launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),
364 cwd: process.cwd(),
365 environment: processEnv,
366 });
367 const response = yield* client.request("account/rateLimitResetCredit/consume", {
368 idempotencyKey,
369 });
370 return response.outcome;
371 }).pipe(Effect.scoped, Effect.timeout("20 seconds")),
372 )
373 .pipe(
374 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
375 Effect.mapError(
376 (cause) =>
377 new ProviderDriverError({
378 driver: DRIVER_KIND,
379 instanceId,
380 detail: "Codex could not redeem the reset credit.",
381 cause,
382 }),
383 ),
384 Effect.tap((outcome) =>
385 ResetCreditCoordinator.refreshAfterRedemption({
386 outcome,
387 getSnapshot: snapshot.getSnapshot,
388 refresh: snapshot.refresh,
389 }).pipe(
390 Effect.filterOrFail(
391 (confirmed) => confirmed,
392 () =>
393 new ProviderDriverError({
394 driver: DRIVER_KIND,
395 instanceId,
396 detail:
397 "The reset was applied, but Codex could not confirm the new limits. Refresh to check.",
398 }),
399 ),
400 ),
401 ),
402 );
403
404 // `codex login` and `codex logout` rewrite auth.json outside T3.
405 if (effectiveConfig.enabled) {
406 yield* fileSystem.watch(accountKey).pipe(
407 Stream.filter((event) => pathService.basename(event.path) === "auth.json"),
408 Stream.debounce(Duration.millis(250)),
409 Stream.runForEach(() => snapshot.refresh.pipe(Effect.ignoreCause({ log: true }))),
410 Effect.catchReason("PlatformError", "NotFound", () => Effect.void),
411 Effect.ignoreCause({ log: true }),
412 Effect.forkScoped,
413 );
414 }
415 return {
416 instanceId,
417 driverKind: DRIVER_KIND,
418 continuationIdentity,
419 displayName,
420 accentColor,
421 enabled,
422 snapshot,
423 snapshotForCwd,
424 consumeResetCredit,
425 orchestrationAdapter,
426 textGeneration,
427 } satisfies ProviderInstance;
428 }),
429};