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

ProviderDriver.ts

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