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 {
37 CodexAdapterV2Driver,
38 type CodexAdapterV2DriverEnv,
39} from "../../orchestration-v2/Adapters/CodexAdapterV2.ts";
40import { ServerSettingsService } from "../../serverSettings.ts";
41import { ProviderDriverError } from "../Errors.ts";
42import { checkCodexProviderStatus, makePendingCodexProvider } from "../Layers/CodexProvider.ts";
43import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
44import type { ProviderDriver, ProviderInstance } from "../ProviderDriver.ts";
45import type { ServerProviderDraft } from "../providerSnapshot.ts";
46import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
47import {
48 enrichProviderSnapshotWithVersionAdvisory,
49 makePackageManagedProviderMaintenanceResolver,
50 resolveProviderMaintenanceCapabilitiesEffect,
51} from "../providerMaintenance.ts";
52import {
53 haveProviderSnapshotSettingsChanged,
54 makeProviderSnapshotSettingsSource,
55 type ProviderSnapshotSettings,
56} from "../providerUpdateSettings.ts";
57import {
58 codexContinuationIdentity,
59 materializeCodexShadowHome,
60 resolveCodexHomeLayout,
61} from "./CodexHomeLayout.ts";
62const decodeCodexSettings = Schema.decodeSync(CodexSettings);
63
64const DRIVER_KIND = ProviderDriverKind.make("codex");
65const UPDATE = makePackageManagedProviderMaintenanceResolver({
66 provider: DRIVER_KIND,
67 npmPackageName: "@openai/codex",
68 homebrewFormula: "codex",
69 nativeUpdate: null,
70});
71
72/**
73 * Services the driver needs to materialize an instance. Surfaced as the
74 * driver's `R` so the registry layer aggregates these across every
75 * registered driver and the runtime satisfies them once.
76 */
77export type CodexDriverEnv =
78 | CodexAdapterV2DriverEnv
79 | BackgroundPolicy.BackgroundPolicy
80 | ChildProcessSpawner.ChildProcessSpawner
81 | Crypto.Crypto
82 | FileSystem.FileSystem
83 | HttpClient.HttpClient
84 | Path.Path
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 processEnv = mergeProviderInstanceEnvironment(environment);
124 const homeLayout = yield* resolveCodexHomeLayout(config);
125 const continuationIdentity = codexContinuationIdentity(homeLayout);
126 const stampIdentity = withInstanceIdentity({
127 instanceId,
128 displayName,
129 accentColor,
130 continuationGroupKey: continuationIdentity.continuationKey,
131 });
132 yield* materializeCodexShadowHome(homeLayout).pipe(
133 Effect.mapError(
134 (cause) =>
135 new ProviderDriverError({
136 driver: DRIVER_KIND,
137 instanceId,
138 detail: cause.message,
139 cause,
140 }),
141 ),
142 );
143 const effectiveConfig = {
144 ...config,
145 enabled,
146 homePath: homeLayout.effectiveHomePath ?? "",
147 } satisfies CodexSettings;
148 const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
149 binaryPath: effectiveConfig.binaryPath,
150 env: processEnv,
151 });
152
153 const orchestrationAdapter = yield* CodexAdapterV2Driver.create({
154 instanceId,
155 displayName,
156 accentColor,
157 environment,
158 enabled,
159 config,
160 }).pipe(
161 Effect.mapError(
162 (cause) =>
163 new ProviderDriverError({
164 driver: DRIVER_KIND,
165 instanceId,
166 detail: "Failed to build Codex orchestration adapter.",
167 cause,
168 }),
169 ),
170 );
171 const textGeneration = yield* makeCodexTextGeneration(effectiveConfig, processEnv);
172
173 // Build a managed snapshot whose settings never change — mutations come
174 // in as instance rebuilds from the registry rather than in-place
175 // updates. Pre-provide `ChildProcessSpawner` so the check fits
176 // `makeManagedServerProvider.checkProvider`'s `R = never`.
177 const checkProvider = checkCodexProviderStatus(effectiveConfig, undefined, processEnv).pipe(
178 Effect.map(stampIdentity),
179 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
180 );
181 const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
182 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CodexSettings>>({
183 maintenanceCapabilities,
184 getSettings: snapshotSettings.getSettings,
185 streamSettings: snapshotSettings.streamSettings,
186 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
187 initialSnapshot: (settings) =>
188 makePendingCodexProvider(settings.provider).pipe(Effect.map(stampIdentity)),
189 checkProvider,
190 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
191 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
192 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
193 }).pipe(
194 Effect.provideService(HttpClient.HttpClient, httpClient),
195 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
196 ),
197 }).pipe(
198 Effect.mapError(
199 (cause) =>
200 new ProviderDriverError({
201 driver: DRIVER_KIND,
202 instanceId,
203 detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,
204 cause,
205 }),
206 ),
207 );
208
209 return {
210 instanceId,
211 driverKind: DRIVER_KIND,
212 continuationIdentity,
213 displayName,
214 accentColor,
215 enabled,
216 snapshot,
217 orchestrationAdapter,
218 textGeneration,
219 } satisfies ProviderInstance;
220 }),
221};