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

ProviderDriver.ts

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