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 nativeUpdate: {
85 args: ["update"],
86 isCommandPath: (commandPath) => codexStandaloneHome(commandPath) !== null,
87 requiresCommandPath: true,
88 env: (context) => ({
89 CODEX_HOME:
90 codexStandaloneHome(context.realCommandPath) ??
91 codexStandaloneHome(context.resolvedCommandPath) ??
92 sharedHomePath,
93 }),
94 },
95 });
96}
97
98export type CodexDriverEnv =
99 | CodexAdapterV2DriverEnv
100 | ProviderHost.ProviderHost
101 | ChildProcessSpawner.ChildProcessSpawner
102 | ResetCreditCoordinator.ResetCreditCoordinator
103 | Digest.Digest
104 | SecureRandom.SecureRandom
105 | Signature.Signature
106 | FileSystem.FileSystem
107 | HttpClient.HttpClient
108 | ProviderLatestVersions.ProviderLatestVersions
109 | ModelCatalog.ModelCatalog
110 | Path.Path
111 | ProviderEventLoggers.ProviderEventLoggers
112 | ServerConfig.ServerConfig
113 | ServerSecretStore.ServerSecretStore
114 | ServerEnvironment.ServerEnvironmentIdentity
115 | CodexInstallation.CodexInstallation
116 | CodexManagedTokenBroker.CodexManagedTokenBroker;
117
118export const CodexDriver: ProviderDriver<
119 CodexSettings,
120 CodexDriverEnv,
121 Path.Path | CodexUsageHistory.CodexUsageHistory
122> = {
123 driverKind: DRIVER_KIND,
124 metadata: {
125 displayName: "Codex",
126 supportsMultipleInstances: true,
127 },
128 configSchema: CodexSettings,
129 defaultConfig: (): CodexSettings => decodeCodexSettings({}),
130 usage: codexUsageReader,
131 create: Effect.fn("CodexDriver.create")(function* ({
132 instanceId,
133 displayName,
134 accentColor,
135 environment,
136 enabled,
137 config,
138 }) {
139 if (config.setupMode === "managed")
140 return yield* makeManagedCodexProvider({
141 instanceId,
142 displayName,
143 accentColor,
144 environment,
145 enabled,
146 config,
147 });
148 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
149 const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator;
150 const fileSystem = yield* FileSystem.FileSystem;
151 const pathService = yield* Path.Path;
152 const httpClient = yield* HttpClient.HttpClient;
153 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
154 const installation = yield* CodexInstallation.CodexInstallation;
155 const modelCatalog = yield* ModelCatalog.ModelCatalog;
156 const currentCatalog = modelCatalog.current(DRIVER_KIND);
157 const processEnv = yield* mergeProviderInstanceEnvironment(
158 environment,
159 yield* HostProcess.Environment,
160 );
161 const environmentHome = processEnv.CODEX_HOME;
162 const homeLayout = yield* resolveCodexHomeLayout(
163 !config.homePath.trim() && !config.shadowHomePath.trim() && environmentHome?.trim()
164 ? { ...config, homePath: environmentHome }
165 : config,
166 );
167 const continuationIdentity = codexContinuationIdentity(homeLayout);
168 const stampIdentity = withInstanceIdentity({
169 instanceId,
170 driverKind: DRIVER_KIND,
171 displayName,
172 accentColor,
173 continuationGroupKey: continuationIdentity.continuationKey,
174 });
175 yield* materializeCodexShadowHome(homeLayout).pipe(
176 Effect.mapError(
177 (cause) =>
178 new ProviderDriverError({
179 driver: DRIVER_KIND,
180 instanceId,
181 detail: cause.message,
182 cause,
183 }),
184 ),
185 );
186 const effectiveConfig = {
187 ...config,
188 enabled,
189 binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),
190 homePath: homeLayout.effectiveHomePath ?? "",
191 } satisfies CodexSettings;
192 const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
193 resolveProviderMaintenanceCapabilitiesEffect(
194 makeCodexMaintenanceResolver(homeLayout.sharedHomePath),
195 {
196 binaryPath: effectiveConfig.binaryPath,
197 env: processEnv,
198 },
199 ).pipe(
200 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
201 Effect.provideService(FileSystem.FileSystem, fileSystem),
202 Effect.provideService(Path.Path, pathService),
203 ),
204 );
205
206 const orchestrationAdapter = yield* createCodexAdapterV2(
207 {
208 instanceId,
209 displayName,
210 accentColor,
211 environment,
212 enabled,
213 config,
214 },
215 {
216 onUsageLimits: (update) => snapshot.applyUsageLimits(update),
217 compatibility: installation.compatibility,
218 },
219 ).pipe(
220 Effect.mapError(
221 (cause) =>
222 new ProviderDriverError({
223 driver: DRIVER_KIND,
224 instanceId,
225 detail: "Failed to build Codex orchestration adapter.",
226 cause,
227 }),
228 ),
229 );
230
231 // Kick the TTL-gated manifest refresh in the background and classify with the in-memory
232 // manifest, so a slow or hung fetch never delays the provider check.
233 const checkProvider = modelCatalog.refreshInBackground.pipe(
234 Effect.andThen(
235 Effect.zipWith(
236 checkCodexProviderStatus(effectiveConfig, undefined, processEnv),
237 currentCatalog,
238 (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)),
239 { concurrent: true },
240 ),
241 ),
242 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
243 Effect.provideService(FileSystem.FileSystem, fileSystem),
244 Effect.provideService(Path.Path, pathService),
245 );
246 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
247 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CodexSettings>>({
248 resolveMaintenance,
249 getSettings: snapshotSettings.getSettings,
250 streamSettings: snapshotSettings.streamSettings,
251 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
252 initialSnapshot: (settings) =>
253 Effect.zipWith(
254 makePendingCodexProvider(settings.provider),
255 currentCatalog,
256 (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)),
257 ),
258 checkProvider,
259 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
260 resolveMaintenance().pipe(
261 Effect.flatMap((maintenanceCapabilities) =>
262 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
263 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
264 }),
265 ),
266 Effect.provideService(HttpClient.HttpClient, httpClient),
267 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
268 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
269 ),
270 }).pipe(
271 Effect.mapError(
272 (cause) =>
273 new ProviderDriverError({
274 driver: DRIVER_KIND,
275 instanceId,
276 detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,
277 cause,
278 }),
279 ),
280 );
281 const textGeneration = yield* makeCodexTextGeneration(
282 effectiveConfig,
283 processEnv,
284 snapshot.getSnapshot.pipe(Effect.map((value) => value.models)),
285 );
286 const snapshotForCwd = (cwd: string) =>
287 !effectiveConfig.enabled
288 ? snapshot.getSnapshot
289 : Effect.all([
290 snapshot.getSnapshot,
291 probeCodexSkillsForCwd({
292 binaryPath: effectiveConfig.binaryPath,
293 homePath: effectiveConfig.homePath,
294 launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),
295 cwd,
296 environment: processEnv,
297 }).pipe(
298 Effect.scoped,
299 Effect.timeout("20 seconds"),
300 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
301 ),
302 ]).pipe(
303 Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })),
304 Effect.mapError(
305 (cause) =>
306 new ProviderDriverError({
307 driver: DRIVER_KIND,
308 instanceId,
309 detail: `Failed to probe Codex skills for '${cwd}'`,
310 cause,
311 }),
312 ),
313 );
314
315 // Redemption spends account credit; serialize by the auth.json directory, keep one idempotency key
316 // until the outcome, and bound the wait so a hung app-server cannot hold the account lock.
317 // Auth overlays use effectiveHomePath; the continuation key would conflate them with shared homes.
318 const accountKey = homeLayout.effectiveHomePath ?? homeLayout.sharedHomePath;
319 const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = () =>
320 resetCreditCoordinator
321 .redeem(accountKey, (idempotencyKey) =>
322 Effect.gen(function* () {
323 const { client } = yield* withCodexAppServerClient({
324 binaryPath: effectiveConfig.binaryPath,
325 homePath: effectiveConfig.homePath,
326 launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),
327 cwd: process.cwd(),
328 environment: processEnv,
329 });
330 const response = yield* client.request("account/rateLimitResetCredit/consume", {
331 idempotencyKey,
332 });
333 return response.outcome;
334 }).pipe(Effect.scoped, Effect.timeout("20 seconds")),
335 )
336 .pipe(
337 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
338 Effect.mapError(
339 (cause) =>
340 new ProviderDriverError({
341 driver: DRIVER_KIND,
342 instanceId,
343 detail: "Codex could not redeem the reset credit.",
344 cause,
345 }),
346 ),
347 // The windows just changed; re-probe so the snapshot says so. A
348 // failed probe republishes the pre-redemption limits rather than
349 // marking them failed, so "confirmed" means `checkedAt` moved past
350 // what was published before the redemption started.
351 Effect.tap((outcome) =>
352 Effect.gen(function* () {
353 const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt;
354 const refreshed = yield* snapshot.refresh;
355 const after = refreshed.usageLimits?.checkedAt;
356 if (
357 outcome === "reset" &&
358 (after === undefined ||
359 after === before ||
360 refreshed.usageLimits?.unavailable?.reason === "probeFailed")
361 ) {
362 return yield* new ProviderDriverError({
363 driver: DRIVER_KIND,
364 instanceId,
365 detail:
366 "The reset was applied, but Codex could not confirm the new limits. Refresh to check.",
367 });
368 }
369 }),
370 ),
371 );
372
373 return {
374 instanceId,
375 driverKind: DRIVER_KIND,
376 continuationIdentity,
377 displayName,
378 accentColor,
379 enabled,
380 snapshot,
381 snapshotForCwd,
382 consumeResetCredit,
383 orchestrationAdapter,
384 textGeneration,
385 } satisfies ProviderInstance;
386 }),
387};