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

CodexDriver.ts

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