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

CodexDriver.ts

225 lines8.8 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, 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 fileSystem = yield* FileSystem.FileSystem;
122 const httpClient = yield* HttpClient.HttpClient;
123 const path = yield* Path.Path;
124 const serverSettings = yield* ServerSettingsService;
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 const orchestrationAdapter = yield* CodexAdapterV2Driver.create({
156 instanceId,
157 displayName,
158 accentColor,
159 environment,
160 enabled,
161 config,
162 }).pipe(
163 Effect.mapError(
164 (cause) =>
165 new ProviderDriverError({
166 driver: DRIVER_KIND,
167 instanceId,
168 detail: "Failed to build Codex orchestration adapter.",
169 cause,
170 }),
171 ),
172 );
173 const textGeneration = yield* makeCodexTextGeneration(effectiveConfig, processEnv);
174​
175 // Build a managed snapshot whose settings never change — mutations come
176 // in as instance rebuilds from the registry rather than in-place
177 // updates. Pre-provide `ChildProcessSpawner` so the check fits
178 // `makeManagedServerProvider.checkProvider`'s `R = never`.
179 const checkProvider = checkCodexProviderStatus(effectiveConfig, undefined, processEnv).pipe(
180 Effect.map(stampIdentity),
181 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
182 Effect.provideService(FileSystem.FileSystem, fileSystem),
183 Effect.provideService(Path.Path, path),
184 );
185 const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
186 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CodexSettings>>({
187 maintenanceCapabilities,
188 getSettings: snapshotSettings.getSettings,
189 streamSettings: snapshotSettings.streamSettings,
190 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
191 initialSnapshot: (settings) =>
192 makePendingCodexProvider(settings.provider).pipe(Effect.map(stampIdentity)),
193 checkProvider,
194 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
195 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
196 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
197 }).pipe(
198 Effect.provideService(HttpClient.HttpClient, httpClient),
199 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
200 ),
201 }).pipe(
202 Effect.mapError(
203 (cause) =>
204 new ProviderDriverError({
205 driver: DRIVER_KIND,
206 instanceId,
207 detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,
208 cause,
209 }),
210 ),
211 );
212​
213 return {
214 instanceId,
215 driverKind: DRIVER_KIND,
216 continuationIdentity,
217 displayName,
218 accentColor,
219 enabled,
220 snapshot,
221 orchestrationAdapter,
222 textGeneration,
223 } satisfies ProviderInstance;
224 }),
225};