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

providerInstances.ts

318 lines12.4 KB

1/**
2 * Instance-aware view over the wire `ServerProvider[]`.
3 *
4 * The wire carries one `ServerProvider` per *configured instance* — the
5 * default built-in codex instance, a user-authored `codex_personal`, an
6 * unavailable shadow for a fork driver, etc. Legacy UI code collapsed these
7 * into a single bucket per built-in driver via `.find((p) => p.driver === kind)`,
8 * which silently dropped every custom instance after the first. This module
9 * replaces that pattern with `ProviderInstanceEntry[]`, keyed on
10 * `ProviderInstanceId`, so the model picker, settings list, and composer
11 * can treat built-in and custom instances uniformly.
12 *
13 * @module providerInstances
14 */
15import {
16 DEFAULT_MODEL_BY_PROVIDER,
17 defaultInstanceIdForDriver,
18 resolveProviderInstanceEnabled,
19 type ModelSelection,
20 type ProviderDriverKind,
21 ProviderInstanceId,
22 type ServerProvider,
23 type ServerProviderModel,
24 type ServerSettings,
25 type ServerProviderState,
26} from "@t3tools/contracts";
27import {
28 normalizeProviderAccentColor,
29 resolveProviderInstanceDisplayName,
30 shouldShowInstanceBadge,
31} from "@t3tools/client-runtime/state/provider-instance-display";
32​
33export { normalizeProviderAccentColor, shouldShowInstanceBadge };
34​
35/**
36 * Local-only placeholder used while a draft has no provider it can safely
37 * target. It must never be persisted or dispatched; the composer disables
38 * send until a live provider replaces it.
39 */
40export const NO_PROVIDER_MODEL_SELECTION: ModelSelection = {
41 instanceId: ProviderInstanceId.make("t3code_no_provider"),
42 model: "",
43};
44​
45/**
46 * UI-facing projection of one configured provider instance. Carries the
47 * snapshot verbatim for callers that need server-side fields we don't
48 * hoist here, plus the precomputed `instanceId` / `driverKind` /
49 * `displayName` used by every picker and settings view.
50 */
51export interface ProviderInstanceEntry {
52 readonly instanceId: ProviderInstanceId;
53 readonly driverKind: ProviderDriverKind;
54 readonly displayName: string;
55 readonly accentColor?: string | undefined;
56 readonly continuationGroupKey?: string | undefined;
57 readonly enabled: boolean;
58 readonly installed: boolean;
59 readonly status: ServerProviderState;
60 /**
61 * True when this entry is the default instance for its driver kind —
62 * i.e. its instance id equals `defaultInstanceIdForDriver(driverKind)`.
63 * The settings panel and picker sort defaults before customs.
64 */
65 readonly isDefault: boolean;
66 /** True when `availability === "unavailable"` is absent or "available". */
67 readonly isAvailable: boolean;
68 readonly snapshot: ServerProvider;
69 readonly models: ReadonlyArray<ServerProviderModel>;
71​
72/**
73 * Whether an instance can currently contribute models to an interactive picker.
74 *
75 * Disabling an instance updates `enabled` independently, while its previous
76 * `ready` probe status can remain in the streamed snapshot until reconciliation.
77 */
78export function isProviderInstancePickerReady(entry: ProviderInstanceEntry): boolean {
79 return entry.enabled && entry.isAvailable && entry.status === "ready";
81​
82/** Picker rails contain configured, enabled instances only. */
83export function isProviderInstancePickerVisible(entry: ProviderInstanceEntry): boolean {
84 return entry.enabled;
86​
87/**
88 * Project the wire `ServerProvider[]` into instance entries, one per
89 * configured instance. Preserves the server's ordering (which sources
90 * from `deriveProviderInstanceConfigMap` — explicit `providerInstances.*`
91 * first, synthesized defaults after) so callers that want "default first"
92 * should sort with `sortProviderInstanceEntries` below.
93 */
94export function deriveProviderInstanceEntries(
95 providers: ReadonlyArray<ServerProvider>,
96): ReadonlyArray<ProviderInstanceEntry> {
97 return providers.map((snapshot) => {
98 const instanceId = snapshot.instanceId;
99 const driverKind = snapshot.driver;
100 const defaultId = defaultInstanceIdForDriver(driverKind);
101 const isDefault = instanceId === defaultId;
102 return {
103 instanceId,
104 driverKind,
105 displayName: resolveProviderInstanceDisplayName(snapshot),
106 accentColor: normalizeProviderAccentColor(snapshot.accentColor),
107 continuationGroupKey: snapshot.continuation?.groupKey,
108 enabled: snapshot.enabled,
109 installed: snapshot.installed,
110 status: snapshot.status,
111 isDefault,
112 isAvailable: snapshot.availability !== "unavailable",
113 snapshot,
114 models: snapshot.models,
115 } satisfies ProviderInstanceEntry;
116 });
118​
119/**
120 * Project several environments' `ServerProvider[]` into a nested
121 * `environmentId → instanceId → entry` lookup.
122 *
123 * Instance ids are per-environment routing keys, and `defaultInstanceIdForDriver`
124 * makes the default id literally the driver slug, so every environment running
125 * the same driver reports the same id. Flattening across environments would
126 * clobber entries and mis-resolve accent colors; lookups must stay scoped to
127 * the thread's own environment.
128 */
129export function deriveProviderEntriesByEnvironment(
130 providersByEnvironment: Iterable<readonly [string, ReadonlyArray<ServerProvider>]>,
131): ReadonlyMap<string, ReadonlyMap<string, ProviderInstanceEntry>> {
132 const byEnvironment = new Map<string, ReadonlyMap<string, ProviderInstanceEntry>>();
133 for (const [environmentId, providers] of providersByEnvironment) {
134 byEnvironment.set(
135 environmentId,
136 new Map(
137 deriveProviderInstanceEntries(providers).map(
138 (entry) => [entry.instanceId as string, entry] as const,
139 ),
140 ),
141 );
142 }
143 return byEnvironment;
145​
146/**
147 * Overlay the current settings configuration onto streamed provider snapshots.
148 * Provider probes can briefly retain their previous `enabled` value after a
149 * settings write, so picker visibility must follow settings rather than waiting
150 * for probe reconciliation.
151 *
152 * Only built-in default instances have a legacy `providers` entry. Every
153 * other instance exists through `providerInstances`; if it is absent there,
154 * its streamed snapshot is stale (for example immediately after deletion)
155 * and is treated as disabled.
156 */
157export function applyProviderInstanceSettings(
158 entries: ReadonlyArray<ProviderInstanceEntry>,
159 settings: Pick<ServerSettings, "providerInstances" | "providers">,
160): ReadonlyArray<ProviderInstanceEntry> {
161 const legacyProviders = settings.providers as Readonly<
162 Record<string, { readonly enabled?: boolean } | undefined>
163 >;
164​
165 return entries.map((entry) => {
166 const explicitInstance = Object.hasOwn(settings.providerInstances, entry.instanceId)
167 ? settings.providerInstances[entry.instanceId]
168 : undefined;
169 const legacyProvider = Object.hasOwn(legacyProviders, entry.driverKind)
170 ? legacyProviders[entry.driverKind]
171 : undefined;
172 const enabled = explicitInstance
173 ? resolveProviderInstanceEnabled(explicitInstance)
174 : entry.isDefault && legacyProvider
175 ? (legacyProvider.enabled ?? entry.enabled)
176 : false;
177 return enabled === entry.enabled ? entry : { ...entry, enabled };
178 });
180​
181/**
182 * Sort instance entries so the default instance of each driver kind appears
183 * before any custom instances of the same kind. Within a kind, custom
184 * instances keep their settings-author order (which is how the server
185 * emits them). Stable across kinds: entries retain the server's
186 * cross-driver ordering.
187 */
188export function sortProviderInstanceEntries(
189 entries: ReadonlyArray<ProviderInstanceEntry>,
190): ReadonlyArray<ProviderInstanceEntry> {
191 // Group by driver kind preserving first-appearance order, then emit
192 // default-first within each kind. Using a Map keeps the "first-seen"
193 // semantics for kinds whose default instance is absent (unusual but
194 // possible during the migration).
195 const byKind = new Map<ProviderDriverKind, ProviderInstanceEntry[]>();
196 for (const entry of entries) {
197 const bucket = byKind.get(entry.driverKind);
198 if (bucket) {
199 bucket.push(entry);
200 } else {
201 byKind.set(entry.driverKind, [entry]);
202 }
203 }
204 const sorted: ProviderInstanceEntry[] = [];
205 for (const bucket of byKind.values()) {
206 const defaults = bucket.filter((entry) => entry.isDefault);
207 const customs = bucket.filter((entry) => !entry.isDefault);
208 sorted.push(...defaults, ...customs);
209 }
210 return sorted;
212​
213/**
214 * Look up a single instance entry by exact `instanceId`. Missing snapshots
215 * are not inferred from driver kind in UI routing code.
216 */
217function getProviderInstanceEntry(
218 providers: ReadonlyArray<ServerProvider>,
219 instanceId: ProviderInstanceId,
220): ProviderInstanceEntry | undefined {
221 return deriveProviderInstanceEntries(providers).find((entry) => entry.instanceId === instanceId);
223​
224/**
225 * Default model slug for a specific instance: its declared built-in default,
226 * then its first built-in model, then any model it reports, then the driver-level default. Custom
227 * instances can serve a different model list than the default instance of
228 * the same driver kind, so the lookup must be instance-scoped rather than
229 * kind-scoped.
230 */
231export function getDefaultProviderInstanceModel(
232 providers: ReadonlyArray<ServerProvider>,
233 instanceId: ProviderInstanceId,
234): string | undefined {
235 const entry = getProviderInstanceEntry(providers, instanceId);
236 if (!entry) return undefined;
237 return (
238 entry.models.find((model) => model.isDefault && !model.isCustom)?.slug ??
239 entry.models.find((model) => !model.isCustom)?.slug ??
240 entry.models[0]?.slug ??
241 DEFAULT_MODEL_BY_PROVIDER[entry.driverKind]
242 );
244​
245const isSelectableProviderInstanceEntry = (entry: ProviderInstanceEntry): boolean =>
246 entry.enabled && entry.isAvailable;
247​
248/**
249 * Resolve an exact stored instance when it remains enabled and available.
250 * Otherwise choose a deterministic fallback that can plausibly start now:
251 * ready first, then a non-error probe result. An errored provider is retained
252 * only when it was explicitly requested; it is never invented as a new-user
253 * default.
254 */
255export function resolveSelectableProviderInstanceEntry(
256 entries: ReadonlyArray<ProviderInstanceEntry>,
257 instanceId: ProviderInstanceId | undefined,
258): ProviderInstanceEntry | undefined {
259 if (instanceId !== undefined) {
260 const requested = entries.find((entry) => entry.instanceId === instanceId);
261 if (requested && isSelectableProviderInstanceEntry(requested)) {
262 return requested;
263 }
264 }
265 return (
266 entries.find(isProviderInstancePickerReady) ??
267 entries.find((entry) => isSelectableProviderInstanceEntry(entry) && entry.status !== "error")
268 );
270​
271/**
272 * Resolve the routing key for a selection that may reference an instance
273 * id that no longer exists (e.g. a persisted thread selection after the
274 * user deleted the custom instance). Returns a ready or non-error fallback,
275 * or `undefined` when no provider can safely become a new selection.
276 */
277export function resolveSelectableProviderInstance(
278 providers: ReadonlyArray<ServerProvider>,
279 instanceId: ProviderInstanceId | undefined,
280): ProviderInstanceId | undefined {
281 const entries = deriveProviderInstanceEntries(providers);
282 return resolveSelectableProviderInstanceEntry(entries, instanceId)?.instanceId;
284​
285/**
286 * Resolve the model selection persisted for a project or new thread. A valid
287 * stored selection is preserved byte-for-byte. Falling back to another
288 * instance also resets the model to that instance's own default, avoiding
289 * cross-provider instance/model pairs.
290 */
291export function resolveDefaultProviderModelSelection(
292 providers: ReadonlyArray<ServerProvider>,
293 selection: ModelSelection | null | undefined,
294): ModelSelection | null {
295 const instanceId = resolveSelectableProviderInstance(providers, selection?.instanceId);
296 if (instanceId === undefined) return null;
297 if (selection?.instanceId === instanceId) return selection;
298 const model = getDefaultProviderInstanceModel(providers, instanceId);
299 return model ? { instanceId, model } : null;
301​
302/**
303 * Resolve an open model-selection routing key back to a driver kind.
304 * Custom instance ids such as `claude_openrouter` are not themselves
305 * driver-kind slugs, but the composer still needs the owning driver kind
306 * for capabilities, options, icons, and turn dispatch metadata.
307 */
308export function resolveProviderDriverKindForInstanceSelection(
309 entries: ReadonlyArray<ProviderInstanceEntry>,
310 providers: ReadonlyArray<ServerProvider>,
311 selection: ProviderInstanceId | ProviderDriverKind | null | undefined,
312): ProviderDriverKind | undefined {
313 const matchedEntry = entries.find((entry) => entry.instanceId === selection);
314 if (matchedEntry) {
315 return matchedEntry.driverKind;
316 }
317 return undefined;