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

ProviderDriver.ts

186 lines7.9 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 /** Invalidate T3-owned discovery caches before an explicit provider refresh. */
78 readonly invalidateCaches?: Effect.Effect<void>;
79 /**
80 * Redeem one banked rate-limit reset credit on the signed-in account, then
81 * re-probe so the snapshot reflects the cleared windows. Account-level,
82 * not thread-level, which is why it lives here rather than on the adapter.
83 */
84 readonly consumeResetCredit?: () => Effect.Effect<
85 ProviderConsumeResetCreditOutcome,
86 ProviderDriverError
87 >;
88 readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
89 readonly textGeneration: TextGeneration.TextGeneration["Service"];
90 readonly auth?: ProviderAuthController;
92​
93export interface ProviderContinuationIdentity {
94 readonly driverKind: ProviderDriverKind;
95 readonly continuationKey: string;
97​
98export function defaultProviderContinuationIdentity(input: {
99 readonly driverKind: ProviderDriverKind;
100 readonly instanceId: ProviderInstanceId;
101}): ProviderContinuationIdentity {
102 return {
103 driverKind: input.driverKind,
104 continuationKey: `${input.driverKind}:instance:${input.instanceId}`,
105 };
107​
108/**
109 * Inputs the registry passes to a driver's `create` function.
110 *
111 * `config` is the typed payload — already decoded by the registry through
112 * `driver.configSchema`. Drivers never decode their own raw envelope.
113 */
114export interface ProviderDriverCreateInput<Config> {
115 readonly instanceId: ProviderInstanceId;
116 readonly displayName: string | undefined;
117 readonly accentColor?: string | undefined;
118 readonly environment: ProviderInstanceEnvironment;
119 readonly enabled: boolean;
120 readonly config: Config;
122​
123/**
124 * Driver SPI — registered as a plain value, not a Layer.
125 *
126 * `Config` is whatever the driver decoded from
127 * `ProviderInstanceConfig.config`. `R` is the union of infrastructure
128 * services the driver depends on; the registry layer aggregates `R` across
129 * all registered drivers and the runtime supplies them.
130 *
131 * `create` is responsible for *all* per-instance state — process handles,
132 * pubsub topics, refs, file watchers — and must release them when its
133 * scope closes. Two calls to `create` with different `instanceId` /
134 * `config` MUST yield instances with no shared mutable state.
135 */
136export interface ProviderDriver<Config, R = never> {
137 readonly driverKind: ProviderDriverKind;
138 readonly metadata: ProviderDriverMetadata;
139 /**
140 * Decoder for the opaque `ProviderInstanceConfig.config` envelope. The
141 * registry runs this exactly once per (re)load of an instance; a decode
142 * failure is surfaced as `ProviderDriverError` and downgraded to an
143 * unavailable shadow snapshot.
144 *
145 * The `Encoded` parameter is intentionally left as `unknown` (not
146 * `Config`) so schemas with `withDecodingDefault` / transformations — where
147 * the encoded shape differs from the decoded shape — satisfy the SPI
148 * without casts. The registry only ever decodes `unknown` envelopes here,
149 * so the precise encoded type is irrelevant at this boundary.
150 *
151 * Using `Codec` rather than `Schema` pins `DecodingServices = never` — if
152 * we used `Schema<Config>`, the erased `any` in `AnyProviderDriver` would
153 * widen `DecodingServices` to `unknown` and poison the R channel of every
154 * caller of `decodeUnknownEffect`.
155 */
156 readonly configSchema: Schema.Codec<Config, unknown>;
157 /**
158 * Default config payload used when the legacy
159 * `ServerSettings.providers.<kind>` entry is empty or when the driver
160 * is auto-bootstrapped without user configuration. Returning a typed
161 * default keeps the migration path simple — no special-casing needed
162 * to construct a "blank" instance.
163 */
164 readonly defaultConfig: () => Config;
165 /**
166 * Materialize one instance. The returned effect runs in a scope owned
167 * by the registry; closing that scope releases every resource the
168 * driver opened. Failures become unavailable shadow snapshots — the
169 * driver MUST NOT throw defects.
170 */
171 readonly create: (
172 input: ProviderDriverCreateInput<Config>,
173 ) => Effect.Effect<ProviderInstance, ProviderDriverError, R | Scope.Scope>;
175​
176/**
177 * Heterogeneous-array convenience: the registry stores drivers as
178 * `ReadonlyArray<AnyProviderDriver<R>>` where `R` is the union of all
179 * registered drivers' env requirements.
180 */
181// `any` here intentionally erases the per-driver Config; the registry
182// already decoded it before invoking `create`, so downstream code never
183// needs the original `Config` type. Using `unknown` instead would force
184// `create` callers into casts since `unknown` is not assignable to a
185// concrete `Config` from inside the driver body.
186export type AnyProviderDriver<R = never> = ProviderDriver<any, R>;