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