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

CodexDriver.ts

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