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

CodexDriver.ts

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