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