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 { ServerSettingsService } from "../../serverSettings.ts";
38import { ProviderDriverError } from "../Errors.ts";
39import { makeCodexAdapter } from "../Layers/CodexAdapter.ts";
40import * as ResetCreditCoordinator from "../Layers/resetCreditCoordinator.ts";
41import {
42 checkCodexProviderStatus,
43 makePendingCodexProvider,
44 probeCodexSkillsForCwd,
45 withCodexAppServerClient,
46} from "../Layers/CodexProvider.ts";
47import { resolveCodexLaunchArgs } from "../Layers/codexLaunchArgs.ts";
48import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
49import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
50import * as ModelManifest from "../ModelManifest.ts";
51import type { ProviderDriver, ProviderInstance } from "../ProviderDriver.ts";
52import { withInstanceIdentity } from "./instanceIdentity.ts";
53import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
54import {
55 enrichProviderSnapshotWithVersionAdvisory,
56 makeCachedProviderMaintenanceResolution,
57 makePackageManagedProviderMaintenanceResolver,
58 normalizeCommandPath,
59 resolveProviderMaintenanceCapabilitiesEffect,
60} from "../providerMaintenance.ts";
61import {
62 haveProviderSnapshotSettingsChanged,
63 makeProviderSnapshotSettingsSource,
64 type ProviderSnapshotSettings,
65} from "../providerUpdateSettings.ts";
66import {
67 codexContinuationIdentity,
68 materializeCodexShadowHome,
69 resolveCodexHomeLayout,
70} from "./CodexHomeLayout.ts";
71const decodeCodexSettings = Schema.decodeSync(CodexSettings);
72
73const DRIVER_KIND = ProviderDriverKind.make("codex");
74// The standalone installer lays out `<CODEX_HOME>/packages/standalone/…`;
75// CODEX_HOME is not always `~/.codex`.
76function isCodexStandaloneCommandPath(commandPath: string): boolean {
77 return normalizeCommandPath(commandPath).includes("/packages/standalone/");
78}
79
80/**
81 * `codex update` replaces the standalone tree under `CODEX_HOME`. That tree
82 * lives in the shared home even when an auth-overlay shadow home is in use
83 * (the overlay only carries auth and a few local entries), so the updater
84 * runs against `sharedHomePath` rather than the instance's effective home.
85 */
86function makeCodexMaintenanceResolver(sharedHomePath: string) {
87 return makePackageManagedProviderMaintenanceResolver({
88 provider: DRIVER_KIND,
89 npmPackageName: "@openai/codex",
90 nativeUpdate: {
91 args: ["update"],
92 isCommandPath: isCodexStandaloneCommandPath,
93 env: { CODEX_HOME: sharedHomePath },
94 },
95 });
96}
97
98/**
99 * Services the driver needs to materialize an instance. Surfaced as the
100 * driver's `R` so the registry layer aggregates these across every
101 * registered driver and the runtime satisfies them once.
102 */
103export type CodexDriverEnv =
104 | BackgroundPolicy.BackgroundPolicy
105 | ChildProcessSpawner.ChildProcessSpawner
106 | ResetCreditCoordinator.ResetCreditCoordinator
107 | Crypto.Crypto
108 | FileSystem.FileSystem
109 | HttpClient.HttpClient
110 | ModelManifest.ModelManifest
111 | Path.Path
112 | ProviderEventLoggers
113 | ServerConfig
114 | ServerSettingsService;
115
116export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
117 driverKind: DRIVER_KIND,
118 metadata: {
119 displayName: "Codex",
120 supportsMultipleInstances: true,
121 },
122 configSchema: CodexSettings,
123 defaultConfig: (): CodexSettings => decodeCodexSettings({}),
124 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
125 Effect.gen(function* () {
126 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
127 const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator;
128 const fileSystem = yield* FileSystem.FileSystem;
129 const pathService = yield* Path.Path;
130 const httpClient = yield* HttpClient.HttpClient;
131 const serverSettings = yield* ServerSettingsService;
132 const eventLoggers = yield* ProviderEventLoggers;
133 const modelManifest = yield* ModelManifest.ModelManifest;
134 const processEnv = mergeProviderInstanceEnvironment(environment);
135 const homeLayout = yield* resolveCodexHomeLayout(config);
136 const continuationIdentity = codexContinuationIdentity(homeLayout);
137 const stampIdentity = withInstanceIdentity({
138 instanceId,
139 driverKind: DRIVER_KIND,
140 displayName,
141 accentColor,
142 continuationGroupKey: continuationIdentity.continuationKey,
143 });
144 yield* materializeCodexShadowHome(homeLayout).pipe(
145 Effect.mapError(
146 (cause) =>
147 new ProviderDriverError({
148 driver: DRIVER_KIND,
149 instanceId,
150 detail: cause.message,
151 cause,
152 }),
153 ),
154 );
155 const effectiveConfig = {
156 ...config,
157 enabled,
158 binaryPath: expandHomePath(config.binaryPath),
159 homePath: homeLayout.effectiveHomePath ?? "",
160 } satisfies CodexSettings;
161 const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
162 resolveProviderMaintenanceCapabilitiesEffect(
163 makeCodexMaintenanceResolver(homeLayout.sharedHomePath),
164 {
165 binaryPath: effectiveConfig.binaryPath,
166 env: processEnv,
167 },
168 ).pipe(
169 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
170 Effect.provideService(FileSystem.FileSystem, fileSystem),
171 Effect.provideService(Path.Path, pathService),
172 ),
173 );
174
175 // `makeCodexAdapter` and `makeCodexTextGeneration` have `never` error
176 // channels at construction time — their failure modes are all on the
177 // per-operation closures they return. No `mapError` wrapper is needed
178 // here; the registry only has to worry about snapshot-build and
179 // spawner-availability failures surfaced from `checkCodexProviderStatus`
180 // below.
181 const adapter = yield* makeCodexAdapter(effectiveConfig, {
182 instanceId,
183 environment: processEnv,
184 ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
185 });
186
187 // Build a managed snapshot whose settings never change — mutations come
188 // in as instance rebuilds from the registry rather than in-place
189 // updates. Pre-provide `ChildProcessSpawner` so the check fits
190 // `makeManagedServerProvider.checkProvider`'s `R = never`.
191 // Kick the TTL-gated manifest refresh in the background and classify
192 // with the in-memory manifest, so a slow or hung fetch never delays the
193 // provider check. A refresh that lands mid-probe applies on the next one.
194 const checkProvider = modelManifest.refreshInBackground.pipe(
195 Effect.andThen(
196 Effect.zipWith(
197 checkCodexProviderStatus(effectiveConfig, undefined, processEnv),
198 modelManifest.current,
199 (draft, manifest) =>
200 stampIdentity(ModelManifest.applyModelManifest(draft, manifest, DRIVER_KIND)),
201 { concurrent: true },
202 ),
203 ),
204 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
205 );
206 const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
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 modelManifest.current,
216 (draft, manifest) =>
217 stampIdentity(ModelManifest.applyModelManifest(draft, manifest, DRIVER_KIND)),
218 ),
219 checkProvider,
220 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
221 resolveMaintenance().pipe(
222 Effect.flatMap((maintenanceCapabilities) =>
223 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
224 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
225 }),
226 ),
227 Effect.provideService(HttpClient.HttpClient, httpClient),
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 // Account-level request; any directory serves, same as the status probe.
292 cwd: process.cwd(),
293 environment: processEnv,
294 });
295 const response = yield* client.request("account/rateLimitResetCredit/consume", {
296 idempotencyKey,
297 });
298 return response.outcome;
299 }).pipe(Effect.scoped, Effect.timeout("20 seconds")),
300 )
301 .pipe(
302 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
303 Effect.mapError(
304 (cause) =>
305 new ProviderDriverError({
306 driver: DRIVER_KIND,
307 instanceId,
308 detail: "Codex could not redeem the reset credit.",
309 cause,
310 }),
311 ),
312 // The windows just changed; re-probe so the snapshot says so. A
313 // failed probe republishes the pre-redemption limits rather than
314 // marking them failed, so "confirmed" means `checkedAt` moved
315 // past what was published before the redemption started. Only a
316 // reset claims the limits changed, so only a reset reports an
317 // unconfirmed refresh.
318 Effect.tap((outcome) =>
319 Effect.gen(function* () {
320 const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt;
321 const refreshed = yield* snapshot.refresh;
322 const after = refreshed.usageLimits?.checkedAt;
323 if (
324 outcome === "reset" &&
325 (after === undefined ||
326 after === before ||
327 refreshed.usageLimits?.unavailable?.reason === "probeFailed")
328 ) {
329 return yield* new ProviderDriverError({
330 driver: DRIVER_KIND,
331 instanceId,
332 detail:
333 "The reset was applied, but Codex could not confirm the new limits. Refresh to check.",
334 });
335 }
336 }),
337 ),
338 );
339
340 return {
341 instanceId,
342 driverKind: DRIVER_KIND,
343 continuationIdentity,
344 displayName,
345 accentColor,
346 enabled,
347 snapshot,
348 snapshotForCwd,
349 consumeResetCredit,
350 adapter,
351 textGeneration,
352 } satisfies ProviderInstance;
353 }),
354};