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