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

CodexDriver.ts

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