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

CodexDriver.ts

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