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

CodexDriver.ts

350 lines14.7 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 {
41 CODEX_RESET_CREDIT_TIMEOUT,
42 CodexResetCreditCoordinator,
43} from "../Layers/codexResetCredit.ts";
44import {
45 checkCodexProviderStatus,
46 makePendingCodexProvider,
47 probeCodexSkillsForCwd,
48 withCodexAppServerClient,
49} from "../Layers/CodexProvider.ts";
50import { resolveCodexLaunchArgs } from "../Layers/codexLaunchArgs.ts";
51import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
52import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
53import * as ModelManifest from "../ModelManifest.ts";
54import type { ProviderDriver, ProviderInstance } from "../ProviderDriver.ts";
55import { withInstanceIdentity } from "./instanceIdentity.ts";
56import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
57import {
58 enrichProviderSnapshotWithVersionAdvisory,
59 makeCachedProviderMaintenanceResolution,
60 makePackageManagedProviderMaintenanceResolver,
61 normalizeCommandPath,
62 resolveProviderMaintenanceCapabilitiesEffect,
63} from "../providerMaintenance.ts";
64import {
65 haveProviderSnapshotSettingsChanged,
66 makeProviderSnapshotSettingsSource,
67 type ProviderSnapshotSettings,
68} from "../providerUpdateSettings.ts";
69import {
70 codexContinuationIdentity,
71 materializeCodexShadowHome,
72 resolveCodexHomeLayout,
73} from "./CodexHomeLayout.ts";
74const decodeCodexSettings = Schema.decodeSync(CodexSettings);
75​
76const DRIVER_KIND = ProviderDriverKind.make("codex");
77// The standalone installer lays out `<CODEX_HOME>/packages/standalone/…`;
78// CODEX_HOME is not always `~/.codex`.
79function isCodexStandaloneCommandPath(commandPath: string): boolean {
80 return normalizeCommandPath(commandPath).includes("/packages/standalone/");
82​
83/**
84 * `codex update` replaces the standalone tree under `CODEX_HOME`. That tree
85 * lives in the shared home even when an auth-overlay shadow home is in use
86 * (the overlay only carries auth and a few local entries), so the updater
87 * runs against `sharedHomePath` rather than the instance's effective home.
88 */
89function makeCodexMaintenanceResolver(sharedHomePath: string) {
90 return makePackageManagedProviderMaintenanceResolver({
91 provider: DRIVER_KIND,
92 npmPackageName: "@openai/codex",
93 nativeUpdate: {
94 args: ["update"],
95 isCommandPath: isCodexStandaloneCommandPath,
96 env: { CODEX_HOME: sharedHomePath },
97 },
98 });
100​
101/**
102 * Services the driver needs to materialize an instance. Surfaced as the
103 * driver's `R` so the registry layer aggregates these across every
104 * registered driver and the runtime satisfies them once.
105 */
106export type CodexDriverEnv =
107 | BackgroundPolicy.BackgroundPolicy
108 | ChildProcessSpawner.ChildProcessSpawner
109 | CodexResetCreditCoordinator
110 | Crypto.Crypto
111 | FileSystem.FileSystem
112 | HttpClient.HttpClient
113 | ModelManifest.ModelManifest
114 | Path.Path
115 | ProviderEventLoggers
116 | ServerConfig
117 | ServerSettingsService;
118​
119export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
120 driverKind: DRIVER_KIND,
121 metadata: {
122 displayName: "Codex",
123 supportsMultipleInstances: true,
124 },
125 configSchema: CodexSettings,
126 defaultConfig: (): CodexSettings => decodeCodexSettings({}),
127 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
128 Effect.gen(function* () {
129 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
130 const resetCreditCoordinator = yield* CodexResetCreditCoordinator;
131 const fileSystem = yield* FileSystem.FileSystem;
132 const pathService = yield* Path.Path;
133 const httpClient = yield* HttpClient.HttpClient;
134 const serverSettings = yield* ServerSettingsService;
135 const eventLoggers = yield* ProviderEventLoggers;
136 const modelManifest = yield* ModelManifest.ModelManifest;
137 const processEnv = mergeProviderInstanceEnvironment(environment);
138 const homeLayout = yield* resolveCodexHomeLayout(config);
139 const continuationIdentity = codexContinuationIdentity(homeLayout);
140 const stampIdentity = withInstanceIdentity({
141 instanceId,
142 driverKind: DRIVER_KIND,
143 displayName,
144 accentColor,
145 continuationGroupKey: continuationIdentity.continuationKey,
146 });
147 yield* materializeCodexShadowHome(homeLayout).pipe(
148 Effect.mapError(
149 (cause) =>
150 new ProviderDriverError({
151 driver: DRIVER_KIND,
152 instanceId,
153 detail: cause.message,
154 cause,
155 }),
156 ),
157 );
158 const effectiveConfig = {
159 ...config,
160 enabled,
161 binaryPath: expandHomePath(config.binaryPath),
162 homePath: homeLayout.effectiveHomePath ?? "",
163 } satisfies CodexSettings;
164 const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
165 resolveProviderMaintenanceCapabilitiesEffect(
166 makeCodexMaintenanceResolver(homeLayout.sharedHomePath),
167 {
168 binaryPath: effectiveConfig.binaryPath,
169 env: processEnv,
170 },
171 ).pipe(
172 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
173 Effect.provideService(FileSystem.FileSystem, fileSystem),
174 Effect.provideService(Path.Path, pathService),
175 ),
176 );
177​
178 // `makeCodexAdapter` and `makeCodexTextGeneration` have `never` error
179 // channels at construction time — their failure modes are all on the
180 // per-operation closures they return. No `mapError` wrapper is needed
181 // here; the registry only has to worry about snapshot-build and
182 // spawner-availability failures surfaced from `checkCodexProviderStatus`
183 // below.
184 const adapter = yield* makeCodexAdapter(effectiveConfig, {
185 instanceId,
186 environment: processEnv,
187 ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
188 });
189 const textGeneration = yield* makeCodexTextGeneration(effectiveConfig, processEnv);
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 snapshotForCwd = (cwd: string) =>
246 !effectiveConfig.enabled
247 ? snapshot.getSnapshot
248 : Effect.all([
249 snapshot.getSnapshot,
250 probeCodexSkillsForCwd({
251 binaryPath: effectiveConfig.binaryPath,
252 homePath: effectiveConfig.homePath,
253 launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),
254 cwd,
255 environment: processEnv,
256 }).pipe(
257 Effect.scoped,
258 Effect.timeout("20 seconds"),
259 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
260 ),
261 ]).pipe(
262 Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })),
263 Effect.mapError(
264 (cause) =>
265 new ProviderDriverError({
266 driver: DRIVER_KIND,
267 instanceId,
268 detail: `Failed to probe Codex skills for '${cwd}'`,
269 cause,
270 }),
271 ),
272 );
273​
274 // Redemption spends something on the user's account. It serialises on
275 // the account (instances sharing a Codex home share the credit), keeps
276 // one idempotency key until Codex reports an outcome, and is bounded so
277 // a hung app-server cannot hold the account lock.
278 // Keyed on the directory holding auth.json: an auth-overlay instance has
279 // its own account under `effectiveHomePath`, while plain instances share
280 // the common home. The continuation key would conflate the two.
281 const accountKey = homeLayout.effectiveHomePath ?? homeLayout.sharedHomePath;
282 const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = () =>
283 resetCreditCoordinator
284 .redeem(accountKey, (idempotencyKey) =>
285 Effect.gen(function* () {
286 const { client } = yield* withCodexAppServerClient({
287 binaryPath: effectiveConfig.binaryPath,
288 homePath: effectiveConfig.homePath,
289 launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),
290 // Account-level request; any directory serves, same as the status probe.
291 cwd: process.cwd(),
292 environment: processEnv,
293 });
294 const response = yield* client.request("account/rateLimitResetCredit/consume", {
295 idempotencyKey,
296 });
297 return response.outcome;
298 }).pipe(Effect.scoped, Effect.timeout(CODEX_RESET_CREDIT_TIMEOUT)),
299 )
300 .pipe(
301 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
302 Effect.mapError(
303 (cause) =>
304 new ProviderDriverError({
305 driver: DRIVER_KIND,
306 instanceId,
307 detail: "Codex could not redeem the reset credit.",
308 cause,
309 }),
310 ),
311 // The windows just changed; re-probe so the snapshot says so. A
312 // failed probe republishes the pre-redemption limits rather than
313 // marking them failed, so "confirmed" means `checkedAt` moved
314 // past what was published before the redemption started.
315 Effect.tap(() =>
316 Effect.gen(function* () {
317 const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt;
318 const refreshed = yield* snapshot.refresh;
319 const after = refreshed.usageLimits?.checkedAt;
320 if (
321 after === undefined ||
322 after === before ||
323 refreshed.usageLimits?.unavailable?.reason === "probeFailed"
324 ) {
325 return yield* new ProviderDriverError({
326 driver: DRIVER_KIND,
327 instanceId,
328 detail:
329 "The reset was applied, but Codex could not confirm the new limits. Refresh to check.",
330 });
331 }
332 }),
333 ),
334 );
335​
336 return {
337 instanceId,
338 driverKind: DRIVER_KIND,
339 continuationIdentity,
340 displayName,
341 accentColor,
342 enabled,
343 snapshot,
344 snapshotForCwd,
345 consumeResetCredit,
346 adapter,
347 textGeneration,
348 } satisfies ProviderInstance;
349 }),
350};