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 { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
26import { HttpClient } from "effect/unstable/http";
27import { ChildProcessSpawner } from "effect/unstable/process";
28
29import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
30import { ServerConfig } from "../../config.ts";
31import { ProviderDriverError } from "../Errors.ts";
32import { makeCodexAdapter } from "../Layers/CodexAdapter.ts";
33import { checkCodexProviderStatus, makePendingCodexProvider } from "../Layers/CodexProvider.ts";
34import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
35import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
36import type { ProviderDriver, ProviderInstance } from "../ProviderDriver.ts";
37import type { ServerProviderDraft } from "../providerSnapshot.ts";
38import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
39import {
40 enrichProviderSnapshotWithVersionAdvisory,
41 makePackageManagedProviderMaintenanceResolver,
42 resolveProviderMaintenanceCapabilitiesEffect,
43} from "../providerMaintenance.ts";
44import {
45 codexContinuationIdentity,
46 materializeCodexShadowHome,
47 resolveCodexHomeLayout,
48} from "./CodexHomeLayout.ts";
49
50const DRIVER_KIND = ProviderDriverKind.make("codex");
51const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
52const UPDATE = makePackageManagedProviderMaintenanceResolver({
53 provider: DRIVER_KIND,
54 npmPackageName: "@openai/codex",
55 homebrewFormula: "codex",
56 nativeUpdate: null,
57});
58
59/**
60 * Services the driver needs to materialize an instance. Surfaced as the
61 * driver's `R` so the registry layer aggregates these across every
62 * registered driver and the runtime satisfies them once.
63 */
64export type CodexDriverEnv =
65 | ChildProcessSpawner.ChildProcessSpawner
66 | FileSystem.FileSystem
67 | HttpClient.HttpClient
68 | Path.Path
69 | ProviderEventLoggers
70 | ServerConfig;
71
72/**
73 * Stamp instance identity onto a `ServerProvider` snapshot produced by the
74 * driver-kind-only codex helpers. Once `buildServerProvider` in
75 * `providerSnapshot.ts` is widened to accept `instanceId`/`driver`, this
76 * wrapper disappears.
77 */
78const withInstanceIdentity =
79 (input: {
80 readonly instanceId: ProviderInstance["instanceId"];
81 readonly displayName: string | undefined;
82 readonly accentColor: string | undefined;
83 readonly continuationGroupKey: string;
84 }) =>
85 (snapshot: ServerProviderDraft): ServerProvider => ({
86 ...snapshot,
87 instanceId: input.instanceId,
88 driver: DRIVER_KIND,
89 ...(input.displayName ? { displayName: input.displayName } : {}),
90 ...(input.accentColor ? { accentColor: input.accentColor } : {}),
91 continuation: { groupKey: input.continuationGroupKey },
92 });
93
94export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
95 driverKind: DRIVER_KIND,
96 metadata: {
97 displayName: "Codex",
98 supportsMultipleInstances: true,
99 },
100 configSchema: CodexSettings,
101 defaultConfig: (): CodexSettings => Schema.decodeSync(CodexSettings)({}),
102 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
103 Effect.gen(function* () {
104 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
105 const httpClient = yield* HttpClient.HttpClient;
106 const eventLoggers = yield* ProviderEventLoggers;
107 const processEnv = mergeProviderInstanceEnvironment(environment);
108 const homeLayout = yield* resolveCodexHomeLayout(config);
109 const continuationIdentity = codexContinuationIdentity(homeLayout);
110 const stampIdentity = withInstanceIdentity({
111 instanceId,
112 displayName,
113 accentColor,
114 continuationGroupKey: continuationIdentity.continuationKey,
115 });
116 yield* materializeCodexShadowHome(homeLayout).pipe(
117 Effect.mapError(
118 (cause) =>
119 new ProviderDriverError({
120 driver: DRIVER_KIND,
121 instanceId,
122 detail: cause.message,
123 cause,
124 }),
125 ),
126 );
127 const effectiveConfig = {
128 ...config,
129 enabled,
130 homePath: homeLayout.effectiveHomePath ?? "",
131 } satisfies CodexSettings;
132 const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
133 binaryPath: effectiveConfig.binaryPath,
134 env: processEnv,
135 });
136
137 // `makeCodexAdapter` and `makeCodexTextGeneration` have `never` error
138 // channels at construction time — their failure modes are all on the
139 // per-operation closures they return. No `mapError` wrapper is needed
140 // here; the registry only has to worry about snapshot-build and
141 // spawner-availability failures surfaced from `checkCodexProviderStatus`
142 // below.
143 const adapter = yield* makeCodexAdapter(effectiveConfig, {
144 instanceId,
145 environment: processEnv,
146 ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
147 });
148 const textGeneration = yield* makeCodexTextGeneration(effectiveConfig, processEnv);
149
150 // Build a managed snapshot whose settings never change — mutations come
151 // in as instance rebuilds from the registry rather than in-place
152 // updates. Pre-provide `ChildProcessSpawner` so the check fits
153 // `makeManagedServerProvider.checkProvider`'s `R = never`.
154 const checkProvider = checkCodexProviderStatus(effectiveConfig, undefined, processEnv).pipe(
155 Effect.map(stampIdentity),
156 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
157 );
158 const snapshot = yield* makeManagedServerProvider<CodexSettings>({
159 maintenanceCapabilities,
160 getSettings: Effect.succeed(effectiveConfig),
161 streamSettings: Stream.never,
162 haveSettingsChanged: () => false,
163 initialSnapshot: (settings) => stampIdentity(makePendingCodexProvider(settings)),
164 checkProvider,
165 enrichSnapshot: ({ snapshot, publishSnapshot }) =>
166 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
167 Effect.provideService(HttpClient.HttpClient, httpClient),
168 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
169 ),
170 refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
171 }).pipe(
172 Effect.mapError(
173 (cause) =>
174 new ProviderDriverError({
175 driver: DRIVER_KIND,
176 instanceId,
177 detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,
178 cause,
179 }),
180 ),
181 );
182
183 return {
184 instanceId,
185 driverKind: DRIVER_KIND,
186 continuationIdentity,
187 displayName,
188 accentColor,
189 enabled,
190 snapshot,
191 adapter,
192 textGeneration,
193 } satisfies ProviderInstance;
194 }),
195};