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

CodexDriver.ts

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