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

CodexDriver.ts

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