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

CodexDriver.ts

245 lines10.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 { ServerSettingsService } from "../../serverSettings.ts";
37import { ProviderDriverError } from "../Errors.ts";
38import { makeCodexAdapter } from "../Layers/CodexAdapter.ts";
39import {
40 checkCodexProviderStatus,
41 makePendingCodexProvider,
42 probeCodexSkillsForCwd,
43} from "../Layers/CodexProvider.ts";
44import { resolveCodexLaunchArgs } from "../Layers/codexLaunchArgs.ts";
45import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
46import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
47import * as ModelManifest from "../ModelManifest.ts";
48import type { ProviderDriver, ProviderInstance } from "../ProviderDriver.ts";
49import { withInstanceIdentity } from "./instanceIdentity.ts";
50import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
51import {
52 enrichProviderSnapshotWithVersionAdvisory,
53 makePackageManagedProviderMaintenanceResolver,
54 resolveProviderMaintenanceCapabilitiesEffect,
55} from "../providerMaintenance.ts";
56import {
57 haveProviderSnapshotSettingsChanged,
58 makeProviderSnapshotSettingsSource,
59 type ProviderSnapshotSettings,
60} from "../providerUpdateSettings.ts";
61import {
62 codexContinuationIdentity,
63 materializeCodexShadowHome,
64 resolveCodexHomeLayout,
65} from "./CodexHomeLayout.ts";
66const decodeCodexSettings = Schema.decodeSync(CodexSettings);
67​
68const DRIVER_KIND = ProviderDriverKind.make("codex");
69const UPDATE = makePackageManagedProviderMaintenanceResolver({
70 provider: DRIVER_KIND,
71 npmPackageName: "@openai/codex",
72 homebrewFormula: "codex",
73 nativeUpdate: null,
74});
75​
76/**
77 * Services the driver needs to materialize an instance. Surfaced as the
78 * driver's `R` so the registry layer aggregates these across every
79 * registered driver and the runtime satisfies them once.
80 */
81export type CodexDriverEnv =
82 | BackgroundPolicy.BackgroundPolicy
83 | ChildProcessSpawner.ChildProcessSpawner
84 | Crypto.Crypto
85 | FileSystem.FileSystem
86 | HttpClient.HttpClient
87 | ModelManifest.ModelManifest
88 | Path.Path
89 | ProviderEventLoggers
90 | ServerConfig
91 | ServerSettingsService;
92​
93export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
94 driverKind: DRIVER_KIND,
95 metadata: {
96 displayName: "Codex",
97 supportsMultipleInstances: true,
98 },
99 configSchema: CodexSettings,
100 defaultConfig: (): CodexSettings => decodeCodexSettings({}),
101 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
102 Effect.gen(function* () {
103 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
104 const httpClient = yield* HttpClient.HttpClient;
105 const serverSettings = yield* ServerSettingsService;
106 const eventLoggers = yield* ProviderEventLoggers;
107 const modelManifest = yield* ModelManifest.ModelManifest;
108 const processEnv = mergeProviderInstanceEnvironment(environment);
109 const homeLayout = yield* resolveCodexHomeLayout(config);
110 const continuationIdentity = codexContinuationIdentity(homeLayout);
111 const stampIdentity = withInstanceIdentity({
112 instanceId,
113 driverKind: DRIVER_KIND,
114 displayName,
115 accentColor,
116 continuationGroupKey: continuationIdentity.continuationKey,
117 });
118 yield* materializeCodexShadowHome(homeLayout).pipe(
119 Effect.mapError(
120 (cause) =>
121 new ProviderDriverError({
122 driver: DRIVER_KIND,
123 instanceId,
124 detail: cause.message,
125 cause,
126 }),
127 ),
128 );
129 const effectiveConfig = {
130 ...config,
131 enabled,
132 homePath: homeLayout.effectiveHomePath ?? "",
133 } satisfies CodexSettings;
134 const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
135 binaryPath: effectiveConfig.binaryPath,
136 env: processEnv,
137 });
138​
139 // `makeCodexAdapter` and `makeCodexTextGeneration` have `never` error
140 // channels at construction time — their failure modes are all on the
141 // per-operation closures they return. No `mapError` wrapper is needed
142 // here; the registry only has to worry about snapshot-build and
143 // spawner-availability failures surfaced from `checkCodexProviderStatus`
144 // below.
145 const adapter = yield* makeCodexAdapter(effectiveConfig, {
146 instanceId,
147 environment: processEnv,
148 ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
149 });
150 const textGeneration = yield* makeCodexTextGeneration(effectiveConfig, processEnv);
151​
152 // Build a managed snapshot whose settings never change — mutations come
153 // in as instance rebuilds from the registry rather than in-place
154 // updates. Pre-provide `ChildProcessSpawner` so the check fits
155 // `makeManagedServerProvider.checkProvider`'s `R = never`.
156 // Kick the TTL-gated manifest refresh in the background and classify
157 // with the in-memory manifest, so a slow or hung fetch never delays the
158 // provider check. A refresh that lands mid-probe applies on the next one.
159 const checkProvider = modelManifest.refreshInBackground.pipe(
160 Effect.andThen(
161 Effect.zipWith(
162 checkCodexProviderStatus(effectiveConfig, undefined, processEnv),
163 modelManifest.current,
164 (draft, manifest) =>
165 stampIdentity(ModelManifest.applyModelManifest(draft, manifest, DRIVER_KIND)),
166 { concurrent: true },
167 ),
168 ),
169 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
170 );
171 const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
172 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CodexSettings>>({
173 maintenanceCapabilities,
174 getSettings: snapshotSettings.getSettings,
175 streamSettings: snapshotSettings.streamSettings,
176 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
177 initialSnapshot: (settings) =>
178 Effect.zipWith(
179 makePendingCodexProvider(settings.provider),
180 modelManifest.current,
181 (draft, manifest) =>
182 stampIdentity(ModelManifest.applyModelManifest(draft, manifest, DRIVER_KIND)),
183 ),
184 checkProvider,
185 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
186 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
187 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
188 }).pipe(
189 Effect.provideService(HttpClient.HttpClient, httpClient),
190 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
191 ),
192 }).pipe(
193 Effect.mapError(
194 (cause) =>
195 new ProviderDriverError({
196 driver: DRIVER_KIND,
197 instanceId,
198 detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,
199 cause,
200 }),
201 ),
202 );
203 const snapshotForCwd = (cwd: string) =>
204 !effectiveConfig.enabled
205 ? snapshot.getSnapshot
206 : Effect.all([
207 snapshot.getSnapshot,
208 probeCodexSkillsForCwd({
209 binaryPath: effectiveConfig.binaryPath,
210 homePath: effectiveConfig.homePath,
211 launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),
212 cwd,
213 environment: processEnv,
214 }).pipe(
215 Effect.scoped,
216 Effect.timeout("20 seconds"),
217 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
218 ),
219 ]).pipe(
220 Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })),
221 Effect.mapError(
222 (cause) =>
223 new ProviderDriverError({
224 driver: DRIVER_KIND,
225 instanceId,
226 detail: `Failed to probe Codex skills for '${cwd}'`,
227 cause,
228 }),
229 ),
230 );
231​
232 return {
233 instanceId,
234 driverKind: DRIVER_KIND,
235 continuationIdentity,
236 displayName,
237 accentColor,
238 enabled,
239 snapshot,
240 snapshotForCwd,
241 adapter,
242 textGeneration,
243 } satisfies ProviderInstance;
244 }),
245};