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