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 compatibility: installation.compatibility,
252 },
253 ).pipe(
254 Effect.mapError(
255 (cause) =>
256 new ProviderDriverError({
257 driver: DRIVER_KIND,
258 instanceId,
259 detail: "Failed to build Codex orchestration adapter.",
260 cause,
261 }),
262 ),
263 );
264
265 // Kick the TTL-gated manifest refresh in the background and classify with the in-memory
266 // manifest, so a slow or hung fetch never delays the provider check.
267 const checkProvider = modelCatalog.refreshInBackground.pipe(
268 Effect.andThen(
269 Effect.zipWith(
270 checkCodexProviderStatus(effectiveConfig, undefined, processEnv),
271 currentCatalog,
272 (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)),
273 { concurrent: true },
274 ),
275 ),
276 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
277 Effect.provideService(FileSystem.FileSystem, fileSystem),
278 Effect.provideService(Path.Path, pathService),
279 );
280 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
281 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CodexSettings>>({
282 resolveMaintenance,
283 getSettings: snapshotSettings.getSettings,
284 streamSettings: snapshotSettings.streamSettings,
285 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
286 initialSnapshot: (settings) =>
287 Effect.zipWith(
288 makePendingCodexProvider(settings.provider),
289 currentCatalog,
290 (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)),
291 ),
292 checkProvider,
293 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
294 resolveMaintenance().pipe(
295 Effect.flatMap((maintenanceCapabilities) =>
296 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
297 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
298 }),
299 ),
300 Effect.provideService(HttpClient.HttpClient, httpClient),
301 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
302 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
303 ),
304 }).pipe(
305 Effect.mapError(
306 (cause) =>
307 new ProviderDriverError({
308 driver: DRIVER_KIND,
309 instanceId,
310 detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,
311 cause,
312 }),
313 ),
314 );
315 const textGeneration = yield* makeCodexTextGeneration(
316 effectiveConfig,
317 processEnv,
318 snapshot.getSnapshot.pipe(Effect.map((value) => value.models)),
319 );
320 const snapshotForCwd = (cwd: string) =>
321 !effectiveConfig.enabled
322 ? snapshot.getSnapshot
323 : Effect.all([
324 snapshot.getSnapshot,
325 probeCodexSkillsForCwd({
326 binaryPath: effectiveConfig.binaryPath,
327 homePath: effectiveConfig.homePath,
328 launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),
329 cwd,
330 environment: processEnv,
331 }).pipe(
332 Effect.scoped,
333 Effect.timeout("20 seconds"),
334 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
335 ),
336 ]).pipe(
337 Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })),
338 Effect.mapError(
339 (cause) =>
340 new ProviderDriverError({
341 driver: DRIVER_KIND,
342 instanceId,
343 detail: `Failed to probe Codex skills for '${cwd}'`,
344 cause,
345 }),
346 ),
347 );
348
349 // Redemption spends account credit; serialize by the auth.json directory, keep one idempotency key
350 // until the outcome, and bound the wait so a hung app-server cannot hold the account lock.
351 // Auth overlays use effectiveHomePath; the continuation key would conflate them with shared homes.
352 const accountKey = homeLayout.effectiveHomePath ?? homeLayout.sharedHomePath;
353 const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = () =>
354 resetCreditCoordinator
355 .redeem(accountKey, (idempotencyKey) =>
356 Effect.gen(function* () {
357 const { client } = yield* withCodexAppServerClient({
358 binaryPath: effectiveConfig.binaryPath,
359 homePath: effectiveConfig.homePath,
360 launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),
361 cwd: process.cwd(),
362 environment: processEnv,
363 });
364 const response = yield* client.request("account/rateLimitResetCredit/consume", {
365 idempotencyKey,
366 });
367 return response.outcome;
368 }).pipe(Effect.scoped, Effect.timeout("20 seconds")),
369 )
370 .pipe(
371 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
372 Effect.mapError(
373 (cause) =>
374 new ProviderDriverError({
375 driver: DRIVER_KIND,
376 instanceId,
377 detail: "Codex could not redeem the reset credit.",
378 cause,
379 }),
380 ),
381 Effect.tap((outcome) =>
382 ResetCreditCoordinator.refreshAfterRedemption({
383 outcome,
384 getSnapshot: snapshot.getSnapshot,
385 refresh: snapshot.refresh,
386 }).pipe(
387 Effect.filterOrFail(
388 (confirmed) => confirmed,
389 () =>
390 new ProviderDriverError({
391 driver: DRIVER_KIND,
392 instanceId,
393 detail:
394 "The reset was applied, but Codex could not confirm the new limits. Refresh to check.",
395 }),
396 ),
397 ),
398 ),
399 );
400
401 // `codex login` and `codex logout` rewrite auth.json outside T3.
402 if (effectiveConfig.enabled) {
403 yield* fileSystem.watch(accountKey).pipe(
404 Stream.filter((event) => pathService.basename(event.path) === "auth.json"),
405 Stream.debounce(Duration.millis(250)),
406 Stream.runForEach(() => snapshot.refresh.pipe(Effect.ignoreCause({ log: true }))),
407 Effect.catchReason("PlatformError", "NotFound", () => Effect.void),
408 Effect.ignoreCause({ log: true }),
409 Effect.forkScoped,
410 );
411 }
412 return {
413 instanceId,
414 driverKind: DRIVER_KIND,
415 continuationIdentity,
416 displayName,
417 accentColor,
418 enabled,
419 snapshot,
420 snapshotForCwd,
421 consumeResetCredit,
422 orchestrationAdapter,
423 textGeneration,
424 } satisfies ProviderInstance;
425 }),
426};