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