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

CodexDriver.ts

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