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

ProviderDriver.ts

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