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

CodexDriver.ts

351 lines15.0 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";
71const decodeCodexSettings = Schema.decodeSync(CodexSettings);
72​
73const DRIVER_KIND = ProviderDriverKind.make("codex");
74// The standalone installer lays out `<CODEX_HOME>/packages/standalone/…`;
75// CODEX_HOME is not always `~/.codex`.
76function isCodexStandaloneCommandPath(commandPath: string): boolean {
77 return normalizeCommandPath(commandPath).includes("/packages/standalone/");
79​
80/**
81 * `codex update` replaces the standalone tree under `CODEX_HOME`. That tree
82 * lives in the shared home even when an auth-overlay shadow home is in use
83 * (the overlay only carries auth and a few local entries), so the updater
84 * runs against `sharedHomePath` rather than the instance's effective home.
85 */
86function makeCodexMaintenanceResolver(sharedHomePath: string) {
87 return makePackageManagedProviderMaintenanceResolver({
88 provider: DRIVER_KIND,
89 npmPackageName: "@openai/codex",
90 nativeUpdate: {
91 args: ["update"],
92 isCommandPath: isCodexStandaloneCommandPath,
93 env: { CODEX_HOME: sharedHomePath },
94 },
95 });
97​
98/**
99 * Services the driver needs to materialize an instance. Surfaced as the
100 * driver's `R` so the registry layer aggregates these across every
101 * registered driver and the runtime satisfies them once.
102 */
103export type CodexDriverEnv =
104 | BackgroundPolicy.BackgroundPolicy
105 | ChildProcessSpawner.ChildProcessSpawner
106 | ResetCreditCoordinator.ResetCreditCoordinator
107 | Crypto.Crypto
108 | FileSystem.FileSystem
109 | HttpClient.HttpClient
110 | ModelManifest.ModelManifest
111 | Path.Path
112 | ProviderEventLoggers
113 | ServerConfig
114 | ServerSettingsService;
115​
116export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
117 driverKind: DRIVER_KIND,
118 metadata: {
119 displayName: "Codex",
120 supportsMultipleInstances: true,
121 },
122 configSchema: CodexSettings,
123 defaultConfig: (): CodexSettings => decodeCodexSettings({}),
124 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
125 Effect.gen(function* () {
126 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
127 const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator;
128 const fileSystem = yield* FileSystem.FileSystem;
129 const pathService = yield* Path.Path;
130 const httpClient = yield* HttpClient.HttpClient;
131 const serverSettings = yield* ServerSettingsService;
132 const eventLoggers = yield* ProviderEventLoggers;
133 const modelManifest = yield* ModelManifest.ModelManifest;
134 const processEnv = mergeProviderInstanceEnvironment(environment);
135 const homeLayout = yield* resolveCodexHomeLayout(config);
136 const continuationIdentity = codexContinuationIdentity(homeLayout);
137 const stampIdentity = withInstanceIdentity({
138 instanceId,
139 driverKind: DRIVER_KIND,
140 displayName,
141 accentColor,
142 continuationGroupKey: continuationIdentity.continuationKey,
143 });
144 yield* materializeCodexShadowHome(homeLayout).pipe(
145 Effect.mapError(
146 (cause) =>
147 new ProviderDriverError({
148 driver: DRIVER_KIND,
149 instanceId,
150 detail: cause.message,
151 cause,
152 }),
153 ),
154 );
155 const effectiveConfig = {
156 ...config,
157 enabled,
158 binaryPath: expandHomePath(config.binaryPath),
159 homePath: homeLayout.effectiveHomePath ?? "",
160 } satisfies CodexSettings;
161 const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
162 resolveProviderMaintenanceCapabilitiesEffect(
163 makeCodexMaintenanceResolver(homeLayout.sharedHomePath),
164 {
165 binaryPath: effectiveConfig.binaryPath,
166 env: processEnv,
167 },
168 ).pipe(
169 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
170 Effect.provideService(FileSystem.FileSystem, fileSystem),
171 Effect.provideService(Path.Path, pathService),
172 ),
173 );
174​
175 // Build a managed snapshot whose settings never change — mutations come
176 // in as instance rebuilds from the registry rather than in-place
177 // updates. Pre-provide `ChildProcessSpawner` so the check fits
178 // `makeManagedServerProvider.checkProvider`'s `R = never`.
179 // Kick the TTL-gated manifest refresh in the background and classify
180 // with the in-memory manifest, so a slow or hung fetch never delays the
181 // provider check. A refresh that lands mid-probe applies on the next one.
182 const checkProvider = modelManifest.refreshInBackground.pipe(
183 Effect.andThen(
184 Effect.zipWith(
185 checkCodexProviderStatus(effectiveConfig, undefined, processEnv),
186 modelManifest.current,
187 (draft, manifest) =>
188 stampIdentity(ModelManifest.applyModelManifest(draft, manifest, DRIVER_KIND)),
189 { concurrent: true },
190 ),
191 ),
192 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
193 );
194 const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
195 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CodexSettings>>({
196 resolveMaintenance,
197 getSettings: snapshotSettings.getSettings,
198 streamSettings: snapshotSettings.streamSettings,
199 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
200 initialSnapshot: (settings) =>
201 Effect.zipWith(
202 makePendingCodexProvider(settings.provider),
203 modelManifest.current,
204 (draft, manifest) =>
205 stampIdentity(ModelManifest.applyModelManifest(draft, manifest, DRIVER_KIND)),
206 ),
207 checkProvider,
208 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
209 resolveMaintenance().pipe(
210 Effect.flatMap((maintenanceCapabilities) =>
211 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
212 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
213 }),
214 ),
215 Effect.provideService(HttpClient.HttpClient, httpClient),
216 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
217 ),
218 }).pipe(
219 Effect.mapError(
220 (cause) =>
221 new ProviderDriverError({
222 driver: DRIVER_KIND,
223 instanceId,
224 detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,
225 cause,
226 }),
227 ),
228 );
229 const models = snapshot.getSnapshot.pipe(Effect.map((value) => value.models));
230 // `makeCodexAdapter` and `makeCodexTextGeneration` have `never` error
231 // channels at construction time — their failure modes are all on the
232 // per-operation closures they return. No `mapError` wrapper is needed
233 // here; the registry only has to worry about snapshot-build and
234 // spawner-availability failures surfaced from `checkCodexProviderStatus`
235 // above.
236 const adapter = yield* makeCodexAdapter(effectiveConfig, {
237 instanceId,
238 environment: processEnv,
239 models,
240 ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
241 });
242 const textGeneration = yield* makeCodexTextGeneration(effectiveConfig, processEnv, models);
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("20 seconds")),
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. Only a
313 // reset claims the limits changed, so only a reset reports an
314 // unconfirmed refresh.
315 Effect.tap((outcome) =>
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 outcome === "reset" &&
322 (after === undefined ||
323 after === before ||
324 refreshed.usageLimits?.unavailable?.reason === "probeFailed")
325 ) {
326 return yield* new ProviderDriverError({
327 driver: DRIVER_KIND,
328 instanceId,
329 detail:
330 "The reset was applied, but Codex could not confirm the new limits. Refresh to check.",
331 });
332 }
333 }),
334 ),
335 );
336​
337 return {
338 instanceId,
339 driverKind: DRIVER_KIND,
340 continuationIdentity,
341 displayName,
342 accentColor,
343 enabled,
344 snapshot,
345 snapshotForCwd,
346 consumeResetCredit,
347 adapter,
348 textGeneration,
349 } satisfies ProviderInstance;
350 }),
351};