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