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