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