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