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