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