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 `ServerProviderShape` 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/unstable/http";
31import { ChildProcessSpawner } from "effect/unstable/process";
32
33import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
34import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
35import { ServerConfig } from "../../config.ts";
36import { expandHomePath } from "../../pathExpansion.ts";
37import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
38import {
39 createCodexAdapterV2,
40 type CodexAdapterV2DriverEnv,
41} from "../../orchestration-v2/Adapters/CodexAdapterV2.ts";
42import { ServerSettingsService } from "../../serverSettings.ts";
43import { ProviderDriverError } from "../Errors.ts";
44import {
45 CODEX_RESET_CREDIT_TIMEOUT,
46 CodexResetCreditCoordinator,
47} from "../Layers/codexResetCredit.ts";
48import {
49 checkCodexProviderStatus,
50 makePendingCodexProvider,
51 probeCodexSkillsForCwd,
52 withCodexAppServerClient,
53} from "../Layers/CodexProvider.ts";
54import { resolveCodexLaunchArgs } from "../Layers/codexLaunchArgs.ts";
55import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
56import * as ModelManifest from "../ModelManifest.ts";
57import type { ProviderDriver, ProviderInstance } from "../ProviderDriver.ts";
58import { withInstanceIdentity } from "./instanceIdentity.ts";
59import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
60import {
61 enrichProviderSnapshotWithVersionAdvisory,
62 makeCachedProviderMaintenanceResolution,
63 makePackageManagedProviderMaintenanceResolver,
64 normalizeCommandPath,
65 resolveProviderMaintenanceCapabilitiesEffect,
66} from "../providerMaintenance.ts";
67import {
68 haveProviderSnapshotSettingsChanged,
69 makeProviderSnapshotSettingsSource,
70 type ProviderSnapshotSettings,
71} from "../providerUpdateSettings.ts";
72import {
73 codexContinuationIdentity,
74 materializeCodexShadowHome,
75 resolveCodexHomeLayout,
76} from "./CodexHomeLayout.ts";
77const decodeCodexSettings = Schema.decodeSync(CodexSettings);
78
79const DRIVER_KIND = ProviderDriverKind.make("codex");
80// The standalone installer lays out `<CODEX_HOME>/packages/standalone/…`;
81// CODEX_HOME is not always `~/.codex`.
82function isCodexStandaloneCommandPath(commandPath: string): boolean {
83 return normalizeCommandPath(commandPath).includes("/packages/standalone/");
84}
85
86/**
87 * `codex update` replaces the standalone tree under `CODEX_HOME`. That tree
88 * lives in the shared home even when an auth-overlay shadow home is in use
89 * (the overlay only carries auth and a few local entries), so the updater
90 * runs against `sharedHomePath` rather than the instance's effective home.
91 */
92function makeCodexMaintenanceResolver(sharedHomePath: string) {
93 return makePackageManagedProviderMaintenanceResolver({
94 provider: DRIVER_KIND,
95 npmPackageName: "@openai/codex",
96 nativeUpdate: {
97 args: ["update"],
98 isCommandPath: isCodexStandaloneCommandPath,
99 env: { CODEX_HOME: sharedHomePath },
100 },
101 });
102}
103
104/**
105 * Services the driver needs to materialize an instance. Surfaced as the
106 * driver's `R` so the registry layer aggregates these across every
107 * registered driver and the runtime satisfies them once.
108 */
109export type CodexDriverEnv =
110 | CodexAdapterV2DriverEnv
111 | BackgroundPolicy.BackgroundPolicy
112 | ChildProcessSpawner.ChildProcessSpawner
113 | CodexResetCreditCoordinator
114 | Crypto.Crypto
115 | FileSystem.FileSystem
116 | HttpClient.HttpClient
117 | ModelManifest.ModelManifest
118 | Path.Path
119 | ProviderEventLoggers
120 | ServerConfig
121 | ServerSettingsService;
122
123export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
124 driverKind: DRIVER_KIND,
125 metadata: {
126 displayName: "Codex",
127 supportsMultipleInstances: true,
128 },
129 configSchema: CodexSettings,
130 defaultConfig: (): CodexSettings => decodeCodexSettings({}),
131 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
132 Effect.gen(function* () {
133 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
134 const resetCreditCoordinator = yield* CodexResetCreditCoordinator;
135 const fileSystem = yield* FileSystem.FileSystem;
136 const pathService = yield* Path.Path;
137 const httpClient = yield* HttpClient.HttpClient;
138 const serverSettings = yield* ServerSettingsService;
139 const modelManifest = yield* ModelManifest.ModelManifest;
140 const processEnv = 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),
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 // Build a managed snapshot whose settings never change — mutations come
204 // in as instance rebuilds from the registry rather than in-place
205 // updates. Pre-provide `ChildProcessSpawner` so the check fits
206 // `makeManagedServerProvider.checkProvider`'s `R = never`.
207 // Kick the TTL-gated manifest refresh in the background and classify
208 // with the in-memory manifest, so a slow or hung fetch never delays the
209 // provider check. A refresh that lands mid-probe applies on the next one.
210 const checkProvider = modelManifest.refreshInBackground.pipe(
211 Effect.andThen(
212 Effect.zipWith(
213 checkCodexProviderStatus(effectiveConfig, undefined, processEnv),
214 modelManifest.current,
215 (draft, manifest) =>
216 stampIdentity(ModelManifest.applyModelManifest(draft, manifest, DRIVER_KIND)),
217 { concurrent: true },
218 ),
219 ),
220 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
221 );
222 const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
223 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CodexSettings>>({
224 resolveMaintenance,
225 getSettings: snapshotSettings.getSettings,
226 streamSettings: snapshotSettings.streamSettings,
227 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
228 initialSnapshot: (settings) =>
229 Effect.zipWith(
230 makePendingCodexProvider(settings.provider),
231 modelManifest.current,
232 (draft, manifest) =>
233 stampIdentity(ModelManifest.applyModelManifest(draft, manifest, DRIVER_KIND)),
234 ),
235 checkProvider,
236 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
237 resolveMaintenance().pipe(
238 Effect.flatMap((maintenanceCapabilities) =>
239 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
240 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
241 }),
242 ),
243 Effect.provideService(HttpClient.HttpClient, httpClient),
244 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
245 ),
246 }).pipe(
247 Effect.mapError(
248 (cause) =>
249 new ProviderDriverError({
250 driver: DRIVER_KIND,
251 instanceId,
252 detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,
253 cause,
254 }),
255 ),
256 );
257 const textGeneration = yield* makeCodexTextGeneration(
258 effectiveConfig,
259 processEnv,
260 snapshot.getSnapshot.pipe(Effect.map((value) => value.models)),
261 );
262 const snapshotForCwd = (cwd: string) =>
263 !effectiveConfig.enabled
264 ? snapshot.getSnapshot
265 : Effect.all([
266 snapshot.getSnapshot,
267 probeCodexSkillsForCwd({
268 binaryPath: effectiveConfig.binaryPath,
269 homePath: effectiveConfig.homePath,
270 launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),
271 cwd,
272 environment: processEnv,
273 }).pipe(
274 Effect.scoped,
275 Effect.timeout("20 seconds"),
276 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
277 ),
278 ]).pipe(
279 Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })),
280 Effect.mapError(
281 (cause) =>
282 new ProviderDriverError({
283 driver: DRIVER_KIND,
284 instanceId,
285 detail: `Failed to probe Codex skills for '${cwd}'`,
286 cause,
287 }),
288 ),
289 );
290
291 // Redemption spends something on the user's account. It serialises on
292 // the account (instances sharing a Codex home share the credit), keeps
293 // one idempotency key until Codex reports an outcome, and is bounded so
294 // a hung app-server cannot hold the account lock.
295 // Keyed on the directory holding auth.json: an auth-overlay instance has
296 // its own account under `effectiveHomePath`, while plain instances share
297 // the common home. The continuation key would conflate the two.
298 const accountKey = homeLayout.effectiveHomePath ?? homeLayout.sharedHomePath;
299 const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = () =>
300 resetCreditCoordinator
301 .redeem(accountKey, (idempotencyKey) =>
302 Effect.gen(function* () {
303 const { client } = yield* withCodexAppServerClient({
304 binaryPath: effectiveConfig.binaryPath,
305 homePath: effectiveConfig.homePath,
306 launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),
307 // Account-level request; any directory serves, same as the status probe.
308 cwd: process.cwd(),
309 environment: processEnv,
310 });
311 const response = yield* client.request("account/rateLimitResetCredit/consume", {
312 idempotencyKey,
313 });
314 return response.outcome;
315 }).pipe(Effect.scoped, Effect.timeout(CODEX_RESET_CREDIT_TIMEOUT)),
316 )
317 .pipe(
318 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
319 Effect.mapError(
320 (cause) =>
321 new ProviderDriverError({
322 driver: DRIVER_KIND,
323 instanceId,
324 detail: "Codex could not redeem the reset credit.",
325 cause,
326 }),
327 ),
328 // The windows just changed; re-probe so the snapshot says so. A
329 // failed probe republishes the pre-redemption limits rather than
330 // marking them failed, so "confirmed" means `checkedAt` moved
331 // past what was published before the redemption started.
332 Effect.tap(() =>
333 Effect.gen(function* () {
334 const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt;
335 const refreshed = yield* snapshot.refresh;
336 const after = refreshed.usageLimits?.checkedAt;
337 if (
338 after === undefined ||
339 after === before ||
340 refreshed.usageLimits?.unavailable?.reason === "probeFailed"
341 ) {
342 return yield* new ProviderDriverError({
343 driver: DRIVER_KIND,
344 instanceId,
345 detail:
346 "The reset was applied, but Codex could not confirm the new limits. Refresh to check.",
347 });
348 }
349 }),
350 ),
351 );
352
353 return {
354 instanceId,
355 driverKind: DRIVER_KIND,
356 continuationIdentity,
357 displayName,
358 accentColor,
359 enabled,
360 snapshot,
361 snapshotForCwd,
362 consumeResetCredit,
363 orchestrationAdapter,
364 textGeneration,
365 } satisfies ProviderInstance;
366 }),
367};