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

CodexDriver.ts

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