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