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