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