Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CodexDriver.ts

367 lines15.0 KB

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