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