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

CodexDriver.ts

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