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

ProviderDriver.ts

211 lines8.8 KB

1/**
2 * ProviderDriver / ProviderInstance — driver SPI as plain values.
3 *
4 * `ProviderDriver` is a record, not a Context.Service. The thing it produces
5 * (`ProviderInstance`) is also a record of captured closures
6 * (`snapshot`, `orchestrationAdapter`, `textGeneration`), an id, and a driver kind. There
7 * are intentionally no per-driver Context tags because tags are
8 * singleton-per-runtime and we need many instances of the same driver.
9 *
10 * The only Effect service involved is `ProviderInstanceRegistry`, which
11 * owns the live `Map<InstanceId, ProviderInstance>` and is itself a
12 * singleton.
13 *
14 * Driver factories are functions of `(typed config, env)` where:
15 * - `typed config` is decoded once by the registry via `configSchema`,
16 * so drivers never deal with raw `unknown`.
17 * - `env` flows through Effect's R channel. Each driver declares the
18 * subset of infrastructure services it needs (FileSystem,
19 * ChildProcessSpawner, …) on its `create` return type; the registry
20 * layer's R is the union of those, and the runtime layer satisfies it.
21 *
22 * @module provider/ProviderDriver
23 */
24import type {
25 ProviderConsumeResetCreditOutcome,
26 AcpRegistryListSessionsResult,
27 AcpRegistryListProvidersResult,
28 AcpRegistryOperationError,
29 AcpRegistrySetProviderInput,
30 ProviderDriverKind,
31 ProviderInstanceEnvironment,
32 ProviderInstanceId,
33 ServerProvider,
34} from "@t3tools/contracts";
35import type * as Effect from "effect/Effect";
36import type * as Schema from "effect/Schema";
37import type * as Scope from "effect/Scope";
38​
39import type { TextGeneration } from "../textGeneration/TextGeneration.ts";
40import type { ProviderAdapterV2Shape } from "../orchestration-v2/ProviderAdapter.ts";
41import type { ProviderDriverError } from "./Errors.ts";
42import type { ProviderAuthController } from "./Services/ProviderAuthService.ts";
43import type { ServerProviderShape } from "./Services/ServerProvider.ts";
44​
45/**
46 * Static metadata advertised by a driver. Used for default presentation
47 * and (later) settings UI. Doesn't need to be Effect-typed because nothing
48 * about it is dynamic — drivers are registered at startup.
49 */
50export interface ProviderDriverMetadata {
51 /** Human-readable name for the driver itself (e.g. "Codex"). */
52 readonly displayName: string;
53 /**
54 * Whether the driver may be instantiated more than once concurrently.
55 * Defaults to `true`. Set to `false` for drivers that wrap a global
56 * resource (e.g. a single desktop app socket) — the registry then
57 * rejects multi-instance configurations with a clear error.
58 */
59 readonly supportsMultipleInstances?: boolean;
61​
62/**
63 * One materialized provider instance. Held by the registry, looked up by
64 * `instanceId`, torn down by closing the scope it was created in.
65 *
66 * The three "shape" fields are captured closures owned by this instance —
67 * stopping one instance cannot affect another, and starting a second
68 * instance of the same driver does not reach into the first instance's
69 * state.
70 */
71export interface ProviderInstance {
72 readonly instanceId: ProviderInstanceId;
73 readonly driverKind: ProviderDriverKind;
74 readonly continuationIdentity: ProviderContinuationIdentity;
75 readonly displayName: string | undefined;
76 readonly accentColor?: string | undefined;
77 readonly enabled: boolean;
78 readonly snapshot: ServerProviderShape;
79 readonly snapshotForCwd?: (cwd: string) => Effect.Effect<ServerProvider, ProviderDriverError>;
80 readonly refreshModels?: () => Effect.Effect<void, ProviderDriverError>;
81 /**
82 * Redeem one banked rate-limit reset credit on the signed-in account, then
83 * re-probe so the snapshot reflects the cleared windows. Account-level,
84 * not thread-level, which is why it lives here rather than on the adapter.
85 */
86 readonly consumeResetCredit?: () => Effect.Effect<
87 ProviderConsumeResetCreditOutcome,
88 ProviderDriverError
89 >;
90 readonly orchestrationAdapter: ProviderAdapterV2Shape;
91 readonly textGeneration: TextGeneration["Service"];
92 readonly auth?: ProviderAuthController;
93 readonly acpSessionManagement?: {
94 readonly listSessions: (input: {
95 readonly cwd: string;
96 readonly cursor?: string;
97 }) => Effect.Effect<AcpRegistryListSessionsResult, AcpRegistryOperationError>;
98 readonly logout: (cwd: string) => Effect.Effect<void, AcpRegistryOperationError>;
99 readonly deleteSession: (input: {
100 readonly cwd: string;
101 readonly sessionId: string;
102 }) => Effect.Effect<void, AcpRegistryOperationError>;
103 readonly listProviders: (
104 cwd: string,
105 ) => Effect.Effect<AcpRegistryListProvidersResult, AcpRegistryOperationError>;
106 readonly setProvider: (
107 input: Omit<AcpRegistrySetProviderInput, "instanceId" | "projectId"> & {
108 readonly cwd: string;
109 },
110 ) => Effect.Effect<void, AcpRegistryOperationError>;
111 readonly disableProvider: (input: {
112 readonly cwd: string;
113 readonly providerId: string;
114 }) => Effect.Effect<void, AcpRegistryOperationError>;
115 };
117​
118export interface ProviderContinuationIdentity {
119 readonly driverKind: ProviderDriverKind;
120 readonly continuationKey: string;
122​
123export function defaultProviderContinuationIdentity(input: {
124 readonly driverKind: ProviderDriverKind;
125 readonly instanceId: ProviderInstanceId;
126}): ProviderContinuationIdentity {
127 return {
128 driverKind: input.driverKind,
129 continuationKey: `${input.driverKind}:instance:${input.instanceId}`,
130 };
132​
133/**
134 * Inputs the registry passes to a driver's `create` function.
135 *
136 * `config` is the typed payload — already decoded by the registry through
137 * `driver.configSchema`. Drivers never decode their own raw envelope.
138 */
139export interface ProviderDriverCreateInput<Config> {
140 readonly instanceId: ProviderInstanceId;
141 readonly displayName: string | undefined;
142 readonly accentColor?: string | undefined;
143 readonly environment: ProviderInstanceEnvironment;
144 readonly enabled: boolean;
145 readonly config: Config;
147​
148/**
149 * Driver SPI — registered as a plain value, not a Layer.
150 *
151 * `Config` is whatever the driver decoded from
152 * `ProviderInstanceConfig.config`. `R` is the union of infrastructure
153 * services the driver depends on; the registry layer aggregates `R` across
154 * all registered drivers and the runtime supplies them.
155 *
156 * `create` is responsible for *all* per-instance state — process handles,
157 * pubsub topics, refs, file watchers — and must release them when its
158 * scope closes. Two calls to `create` with different `instanceId` /
159 * `config` MUST yield instances with no shared mutable state.
160 */
161export interface ProviderDriver<Config, R = never> {
162 readonly driverKind: ProviderDriverKind;
163 readonly metadata: ProviderDriverMetadata;
164 /**
165 * Decoder for the opaque `ProviderInstanceConfig.config` envelope. The
166 * registry runs this exactly once per (re)load of an instance; a decode
167 * failure is surfaced as `ProviderDriverError` and downgraded to an
168 * unavailable shadow snapshot.
169 *
170 * The `Encoded` parameter is intentionally left as `unknown` (not
171 * `Config`) so schemas with `withDecodingDefault` / transformations — where
172 * the encoded shape differs from the decoded shape — satisfy the SPI
173 * without casts. The registry only ever decodes `unknown` envelopes here,
174 * so the precise encoded type is irrelevant at this boundary.
175 *
176 * Using `Codec` rather than `Schema` pins `DecodingServices = never` — if
177 * we used `Schema<Config>`, the erased `any` in `AnyProviderDriver` would
178 * widen `DecodingServices` to `unknown` and poison the R channel of every
179 * caller of `decodeUnknownEffect`.
180 */
181 readonly configSchema: Schema.Codec<Config, unknown>;
182 /**
183 * Default config payload used when the legacy
184 * `ServerSettings.providers.<kind>` entry is empty or when the driver
185 * is auto-bootstrapped without user configuration. Returning a typed
186 * default keeps the migration path simple — no special-casing needed
187 * to construct a "blank" instance.
188 */
189 readonly defaultConfig: () => Config;
190 /**
191 * Materialize one instance. The returned effect runs in a scope owned
192 * by the registry; closing that scope releases every resource the
193 * driver opened. Failures become unavailable shadow snapshots — the
194 * driver MUST NOT throw defects.
195 */
196 readonly create: (
197 input: ProviderDriverCreateInput<Config>,
198 ) => Effect.Effect<ProviderInstance, ProviderDriverError, R | Scope.Scope>;
200​
201/**
202 * Heterogeneous-array convenience: the registry stores drivers as
203 * `ReadonlyArray<AnyProviderDriver<R>>` where `R` is the union of all
204 * registered drivers' env requirements.
205 */
206// `any` here intentionally erases the per-driver Config; the registry
207// already decoded it before invoking `create`, so downstream code never
208// needs the original `Config` type. Using `unknown` instead would force
209// `create` callers into casts since `unknown` is not assignable to a
210// concrete `Config` from inside the driver body.
211export type AnyProviderDriver<R = never> = ProviderDriver<any, R>;