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

ProviderDriver.ts

174 lines7.4 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 — three captured closures
6 * (`snapshot`, `adapter`, `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 ProviderDriverKind,
26 ProviderInstanceEnvironment,
27 ProviderInstanceId,
28 ServerProvider,
29} from "@t3tools/contracts";
30import type * as Effect from "effect/Effect";
31import type * as Schema from "effect/Schema";
32import type * as Scope from "effect/Scope";
33​
34import type * as TextGeneration from "../textGeneration/TextGeneration.ts";
35import type { ProviderAdapterError, ProviderDriverError } from "./Errors.ts";
36import type { ProviderAdapterShape } from "./Services/ProviderAdapter.ts";
37import type { ServerProviderShape } from "./Services/ServerProvider.ts";
38import type { ProviderAuthController } from "./Services/ProviderAuthService.ts";
39​
40/**
41 * Static metadata advertised by a driver. Used for default presentation
42 * and (later) settings UI. Doesn't need to be Effect-typed because nothing
43 * about it is dynamic — drivers are registered at startup.
44 */
45export interface ProviderDriverMetadata {
46 /** Human-readable name for the driver itself (e.g. "Codex"). */
47 readonly displayName: string;
48 /**
49 * Whether the driver may be instantiated more than once concurrently.
50 * Defaults to `true`. Set to `false` for drivers that wrap a global
51 * resource (e.g. a single desktop app socket) — the registry then
52 * rejects multi-instance configurations with a clear error.
53 */
54 readonly supportsMultipleInstances?: boolean;
56​
57/**
58 * One materialized provider instance. Held by the registry, looked up by
59 * `instanceId`, torn down by closing the scope it was created in.
60 *
61 * The three "shape" fields are captured closures owned by this instance —
62 * stopping one instance cannot affect another, and starting a second
63 * instance of the same driver does not reach into the first instance's
64 * state.
65 */
66export interface ProviderInstance {
67 readonly instanceId: ProviderInstanceId;
68 readonly driverKind: ProviderDriverKind;
69 readonly continuationIdentity: ProviderContinuationIdentity;
70 readonly displayName: string | undefined;
71 readonly accentColor?: string | undefined;
72 readonly enabled: boolean;
73 readonly snapshot: ServerProviderShape;
74 readonly snapshotForCwd?: (cwd: string) => Effect.Effect<ServerProvider, ProviderDriverError>;
75 readonly refreshModels?: () => Effect.Effect<void, ProviderDriverError>;
76 readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
77 readonly textGeneration: TextGeneration.TextGeneration["Service"];
78 readonly auth?: ProviderAuthController;
80​
81export interface ProviderContinuationIdentity {
82 readonly driverKind: ProviderDriverKind;
83 readonly continuationKey: string;
85​
86export function defaultProviderContinuationIdentity(input: {
87 readonly driverKind: ProviderDriverKind;
88 readonly instanceId: ProviderInstanceId;
89}): ProviderContinuationIdentity {
90 return {
91 driverKind: input.driverKind,
92 continuationKey: `${input.driverKind}:instance:${input.instanceId}`,
93 };
95​
96/**
97 * Inputs the registry passes to a driver's `create` function.
98 *
99 * `config` is the typed payload — already decoded by the registry through
100 * `driver.configSchema`. Drivers never decode their own raw envelope.
101 */
102export interface ProviderDriverCreateInput<Config> {
103 readonly instanceId: ProviderInstanceId;
104 readonly displayName: string | undefined;
105 readonly accentColor?: string | undefined;
106 readonly environment: ProviderInstanceEnvironment;
107 readonly enabled: boolean;
108 readonly config: Config;
110​
111/**
112 * Driver SPI — registered as a plain value, not a Layer.
113 *
114 * `Config` is whatever the driver decoded from
115 * `ProviderInstanceConfig.config`. `R` is the union of infrastructure
116 * services the driver depends on; the registry layer aggregates `R` across
117 * all registered drivers and the runtime supplies them.
118 *
119 * `create` is responsible for *all* per-instance state — process handles,
120 * pubsub topics, refs, file watchers — and must release them when its
121 * scope closes. Two calls to `create` with different `instanceId` /
122 * `config` MUST yield instances with no shared mutable state.
123 */
124export interface ProviderDriver<Config, R = never> {
125 readonly driverKind: ProviderDriverKind;
126 readonly metadata: ProviderDriverMetadata;
127 /**
128 * Decoder for the opaque `ProviderInstanceConfig.config` envelope. The
129 * registry runs this exactly once per (re)load of an instance; a decode
130 * failure is surfaced as `ProviderDriverError` and downgraded to an
131 * unavailable shadow snapshot.
132 *
133 * The `Encoded` parameter is intentionally left as `unknown` (not
134 * `Config`) so schemas with `withDecodingDefault` / transformations — where
135 * the encoded shape differs from the decoded shape — satisfy the SPI
136 * without casts. The registry only ever decodes `unknown` envelopes here,
137 * so the precise encoded type is irrelevant at this boundary.
138 *
139 * Using `Codec` rather than `Schema` pins `DecodingServices = never` — if
140 * we used `Schema<Config>`, the erased `any` in `AnyProviderDriver` would
141 * widen `DecodingServices` to `unknown` and poison the R channel of every
142 * caller of `decodeUnknownEffect`.
143 */
144 readonly configSchema: Schema.Codec<Config, unknown>;
145 /**
146 * Default config payload used when the legacy
147 * `ServerSettings.providers.<kind>` entry is empty or when the driver
148 * is auto-bootstrapped without user configuration. Returning a typed
149 * default keeps the migration path simple — no special-casing needed
150 * to construct a "blank" instance.
151 */
152 readonly defaultConfig: () => Config;
153 /**
154 * Materialize one instance. The returned effect runs in a scope owned
155 * by the registry; closing that scope releases every resource the
156 * driver opened. Failures become unavailable shadow snapshots — the
157 * driver MUST NOT throw defects.
158 */
159 readonly create: (
160 input: ProviderDriverCreateInput<Config>,
161 ) => Effect.Effect<ProviderInstance, ProviderDriverError, R | Scope.Scope>;
163​
164/**
165 * Heterogeneous-array convenience: the registry stores drivers as
166 * `ReadonlyArray<AnyProviderDriver<R>>` where `R` is the union of all
167 * registered drivers' env requirements.
168 */
169// `any` here intentionally erases the per-driver Config; the registry
170// already decoded it before invoking `create`, so downstream code never
171// needs the original `Config` type. Using `unknown` instead would force
172// `create` callers into casts since `unknown` is not assignable to a
173// concrete `Config` from inside the driver body.
174export type AnyProviderDriver<R = never> = ProviderDriver<any, R>;