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

ProviderDriver.ts

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