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

CodexDriver.ts

389 lines16.3 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 Effect.provideService(FileSystem.FileSystem, fileSystem),
239 Effect.provideService(Path.Path, pathService),
240 );
241 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
242 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CodexSettings>>({
243 resolveMaintenance,
244 getSettings: snapshotSettings.getSettings,
245 streamSettings: snapshotSettings.streamSettings,
246 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
247 initialSnapshot: (settings) =>
248 Effect.zipWith(
249 makePendingCodexProvider(settings.provider),
250 currentCatalog,
251 (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)),
252 ),
253 checkProvider,
254 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
255 resolveMaintenance().pipe(
256 Effect.flatMap((maintenanceCapabilities) =>
257 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
258 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
259 }),
260 ),
261 Effect.provideService(HttpClient.HttpClient, httpClient),
262 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
263 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
264 ),
265 }).pipe(
266 Effect.mapError(
267 (cause) =>
268 new ProviderDriverError({
269 driver: DRIVER_KIND,
270 instanceId,
271 detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,
272 cause,
273 }),
274 ),
275 );
276 const textGeneration = yield* makeCodexTextGeneration(
277 effectiveConfig,
278 processEnv,
279 snapshot.getSnapshot.pipe(Effect.map((value) => value.models)),
280 );
281 const snapshotForCwd = (cwd: string) =>
282 !effectiveConfig.enabled
283 ? snapshot.getSnapshot
284 : Effect.all([
285 snapshot.getSnapshot,
286 probeCodexSkillsForCwd({
287 binaryPath: effectiveConfig.binaryPath,
288 homePath: effectiveConfig.homePath,
289 launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),
290 cwd,
291 environment: processEnv,
292 }).pipe(
293 Effect.scoped,
294 Effect.timeout("20 seconds"),
295 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
296 ),
297 ]).pipe(
298 Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })),
299 Effect.mapError(
300 (cause) =>
301 new ProviderDriverError({
302 driver: DRIVER_KIND,
303 instanceId,
304 detail: `Failed to probe Codex skills for '${cwd}'`,
305 cause,
306 }),
307 ),
308 );
309​
310 // Redemption spends something on the user's account. It serialises on
311 // the account (instances sharing a Codex home share the credit), keeps
312 // one idempotency key until Codex reports an outcome, and is bounded so
313 // a hung app-server cannot hold the account lock.
314 // Keyed on the directory holding auth.json: an auth-overlay instance has
315 // its own account under `effectiveHomePath`, while plain instances share
316 // the common home. The continuation key would conflate the two.
317 const accountKey = homeLayout.effectiveHomePath ?? homeLayout.sharedHomePath;
318 const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = () =>
319 resetCreditCoordinator
320 .redeem(accountKey, (idempotencyKey) =>
321 Effect.gen(function* () {
322 const { client } = yield* withCodexAppServerClient({
323 binaryPath: effectiveConfig.binaryPath,
324 homePath: effectiveConfig.homePath,
325 launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),
326 // Account-level request; any directory serves, same as the status probe.
327 cwd: process.cwd(),
328 environment: processEnv,
329 });
330 const response = yield* client.request("account/rateLimitResetCredit/consume", {
331 idempotencyKey,
332 });
333 return response.outcome;
334 }).pipe(Effect.scoped, Effect.timeout("20 seconds")),
335 )
336 .pipe(
337 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
338 Effect.mapError(
339 (cause) =>
340 new ProviderDriverError({
341 driver: DRIVER_KIND,
342 instanceId,
343 detail: "Codex could not redeem the reset credit.",
344 cause,
345 }),
346 ),
347 // The windows just changed; re-probe so the snapshot says so. A
348 // failed probe republishes the pre-redemption limits rather than
349 // marking them failed, so "confirmed" means `checkedAt` moved
350 // past what was published before the redemption started. Only a
351 // reset claims the limits changed, so only a reset reports an
352 // unconfirmed refresh.
353 Effect.tap((outcome) =>
354 Effect.gen(function* () {
355 const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt;
356 const refreshed = yield* snapshot.refresh;
357 const after = refreshed.usageLimits?.checkedAt;
358 if (
359 outcome === "reset" &&
360 (after === undefined ||
361 after === before ||
362 refreshed.usageLimits?.unavailable?.reason === "probeFailed")
363 ) {
364 return yield* new ProviderDriverError({
365 driver: DRIVER_KIND,
366 instanceId,
367 detail:
368 "The reset was applied, but Codex could not confirm the new limits. Refresh to check.",
369 });
370 }
371 }),
372 ),
373 );
374​
375 return {
376 instanceId,
377 driverKind: DRIVER_KIND,
378 continuationIdentity,
379 displayName,
380 accentColor,
381 enabled,
382 snapshot,
383 snapshotForCwd,
384 consumeResetCredit,
385 orchestrationAdapter,
386 textGeneration,
387 } satisfies ProviderInstance;
388 }),
389};