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

CodexDriver.ts

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