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

providerInstances.ts

350 lines13.8 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 /** Registry identity used to resolve the official icon for generic ACP instances. */
57 readonly acpRegistryAgentId?: string | undefined;
58 /** Catalog-advertised icon URL. The renderer still applies the official-CDN allowlist. */
59 readonly acpRegistryIconUrl?: string | undefined;
60 readonly continuationGroupKey?: string | undefined;
61 readonly enabled: boolean;
62 readonly installed: boolean;
63 readonly status: ServerProviderState;
64 /**
65 * True when this entry is the default instance for its driver kind —
66 * i.e. its instance id equals `defaultInstanceIdForDriver(driverKind)`.
67 * The settings panel and picker sort defaults before customs.
68 */
69 readonly isDefault: boolean;
70 /** True when `availability === "unavailable"` is absent or "available". */
71 readonly isAvailable: boolean;
72 readonly snapshot: ServerProvider;
73 readonly models: ReadonlyArray<ServerProviderModel>;
75​
76export type ProviderCatalogAvailability = "loading" | "ready" | "unavailable" | "unconfigured";
77​
78/**
79 * Keep a provider catalogue that has not arrived yet distinct from a loaded
80 * catalogue with no usable entries. Environment config streams are reactive:
81 * treating their initial `null` as a final empty list strands otherwise
82 * recoverable threads behind a misleading "no providers" state.
83 */
84export function resolveProviderCatalogAvailability(input: {
85 readonly catalogLoaded: boolean;
86 readonly entries: ReadonlyArray<ProviderInstanceEntry>;
87 readonly selectedEntry: ProviderInstanceEntry | undefined;
88}): ProviderCatalogAvailability {
89 if (!input.catalogLoaded) return "loading";
90 if (input.selectedEntry !== undefined) return "ready";
91 return input.entries.length === 0 ? "unconfigured" : "unavailable";
93​
94/**
95 * Whether an instance can currently contribute models to an interactive picker.
96 *
97 * Disabling an instance updates `enabled` independently, while its previous
98 * `ready` probe status can remain in the streamed snapshot until reconciliation.
99 */
100export function isProviderInstancePickerReady(entry: ProviderInstanceEntry): boolean {
101 return entry.enabled && entry.isAvailable && entry.status === "ready";
103​
104/** Picker rails contain configured, enabled instances only. */
105export function isProviderInstancePickerVisible(entry: ProviderInstanceEntry): boolean {
106 return entry.enabled;
108​
109/**
110 * Project the wire `ServerProvider[]` into instance entries, one per
111 * configured instance. Preserves the server's ordering (which sources
112 * from `deriveProviderInstanceConfigMap` — explicit `providerInstances.*`
113 * first, synthesized defaults after) so callers that want "default first"
114 * should sort with `sortProviderInstanceEntries` below.
115 */
116export function deriveProviderInstanceEntries(
117 providers: ReadonlyArray<ServerProvider>,
118): ReadonlyArray<ProviderInstanceEntry> {
119 return providers.map((snapshot) => {
120 const instanceId = snapshot.instanceId;
121 const driverKind = snapshot.driver;
122 const defaultId = defaultInstanceIdForDriver(driverKind);
123 const isDefault = instanceId === defaultId;
124 return {
125 instanceId,
126 driverKind,
127 displayName: resolveProviderInstanceDisplayName(snapshot),
128 accentColor: normalizeProviderAccentColor(snapshot.accentColor),
129 ...(driverKind === "acpRegistry" && snapshot.iconUrl
130 ? { acpRegistryIconUrl: snapshot.iconUrl }
131 : {}),
132 continuationGroupKey: snapshot.continuation?.groupKey,
133 enabled: snapshot.enabled,
134 installed: snapshot.installed,
135 status: snapshot.status,
136 isDefault,
137 isAvailable: snapshot.availability !== "unavailable",
138 snapshot,
139 models: snapshot.models,
140 } satisfies ProviderInstanceEntry;
141 });
143​
144/**
145 * Project several environments' `ServerProvider[]` into a nested
146 * `environmentId → instanceId → entry` lookup.
147 *
148 * Instance ids are per-environment routing keys, and `defaultInstanceIdForDriver`
149 * makes the default id literally the driver slug, so every environment running
150 * the same driver reports the same id. Flattening across environments would
151 * clobber entries and mis-resolve accent colors; lookups must stay scoped to
152 * the thread's own environment.
153 */
154export function deriveProviderEntriesByEnvironment(
155 providersByEnvironment: Iterable<
156 readonly [
157 string,
158 ReadonlyArray<ServerProvider>,
159 Pick<ServerSettings, "providerInstances" | "providers">?,
160 ]
161 >,
162): ReadonlyMap<string, ReadonlyMap<string, ProviderInstanceEntry>> {
163 const byEnvironment = new Map<string, ReadonlyMap<string, ProviderInstanceEntry>>();
164 for (const [environmentId, providers, settings] of providersByEnvironment) {
165 const derived = deriveProviderInstanceEntries(providers);
166 const entries = settings ? applyProviderInstanceSettings(derived, settings) : derived;
167 byEnvironment.set(
168 environmentId,
169 new Map(entries.map((entry) => [entry.instanceId as string, entry] as const)),
170 );
171 }
172 return byEnvironment;
174​
175/**
176 * Overlay the current settings configuration onto streamed provider snapshots.
177 * Provider probes can briefly retain their previous `enabled` value after a
178 * settings write, so picker visibility must follow settings rather than waiting
179 * for probe reconciliation.
180 *
181 * Only built-in default instances have a legacy `providers` entry. Every
182 * other instance exists through `providerInstances`; if it is absent there,
183 * its streamed snapshot is stale (for example immediately after deletion)
184 * and is treated as disabled.
185 */
186export function applyProviderInstanceSettings(
187 entries: ReadonlyArray<ProviderInstanceEntry>,
188 settings: Pick<ServerSettings, "providerInstances" | "providers">,
189): ReadonlyArray<ProviderInstanceEntry> {
190 const legacyProviders = settings.providers as Readonly<
191 Record<string, { readonly enabled?: boolean } | undefined>
192 >;
193​
194 return entries.map((entry) => {
195 const explicitInstance = Object.hasOwn(settings.providerInstances, entry.instanceId)
196 ? settings.providerInstances[entry.instanceId]
197 : undefined;
198 const legacyProvider = Object.hasOwn(legacyProviders, entry.driverKind)
199 ? legacyProviders[entry.driverKind]
200 : undefined;
201 const enabled = explicitInstance
202 ? resolveProviderInstanceEnabled(explicitInstance)
203 : entry.isDefault && legacyProvider
204 ? (legacyProvider.enabled ?? entry.enabled)
205 : false;
206 if (entry.driverKind !== "acpRegistry" || explicitInstance === undefined) {
207 return enabled === entry.enabled ? entry : { ...entry, enabled };
208 }
209 const config =
210 explicitInstance.config !== null && typeof explicitInstance.config === "object"
211 ? (explicitInstance.config as Readonly<Record<string, unknown>>)
212 : null;
213 if (config?.source === "local") {
214 return { ...entry, enabled, acpRegistryAgentId: undefined, acpRegistryIconUrl: undefined };
215 }
216 const agentId = config?.agentId;
217 const iconUrl = config?.registryIconUrl;
218 return {
219 ...entry,
220 enabled,
221 ...(typeof agentId === "string" && agentId.trim()
222 ? { acpRegistryAgentId: agentId.trim() }
223 : {}),
224 ...(typeof iconUrl === "string" && iconUrl.trim()
225 ? { acpRegistryIconUrl: iconUrl.trim() }
226 : {}),
227 };
228 });
230​
231/**
232 * Sort instance entries so the default instance of each driver kind appears
233 * before any custom instances of the same kind. Within a kind, custom
234 * instances keep their settings-author order (which is how the server
235 * emits them). Stable across kinds: entries retain the server's
236 * cross-driver ordering.
237 */
238export function sortProviderInstanceEntries(
239 entries: ReadonlyArray<ProviderInstanceEntry>,
240): ReadonlyArray<ProviderInstanceEntry> {
241 // Group by driver kind preserving first-appearance order, then emit
242 // default-first within each kind. Using a Map keeps the "first-seen"
243 // semantics for kinds whose default instance is absent (unusual but
244 // possible during the migration).
245 const byKind = new Map<ProviderDriverKind, ProviderInstanceEntry[]>();
246 for (const entry of entries) {
247 const bucket = byKind.get(entry.driverKind);
248 if (bucket) {
249 bucket.push(entry);
250 } else {
251 byKind.set(entry.driverKind, [entry]);
252 }
253 }
254 const sorted: ProviderInstanceEntry[] = [];
255 for (const bucket of byKind.values()) {
256 const defaults = bucket.filter((entry) => entry.isDefault);
257 const customs = bucket.filter((entry) => !entry.isDefault);
258 sorted.push(...defaults, ...customs);
259 }
260 return sorted;
262​
263/**
264 * Look up a single instance entry by exact `instanceId`. Missing snapshots
265 * are not inferred from driver kind in UI routing code.
266 */
267export function getProviderInstanceEntry(
268 providers: ReadonlyArray<ServerProvider>,
269 instanceId: ProviderInstanceId,
270): ProviderInstanceEntry | undefined {
271 return deriveProviderInstanceEntries(providers).find((entry) => entry.instanceId === instanceId);
273​
274/**
275 * Default model slug for a specific instance: its declared built-in default,
276 * then its first built-in model, then any model it reports, then the driver-level default. Custom
277 * instances can serve a different model list than the default instance of
278 * the same driver kind, so the lookup must be instance-scoped rather than
279 * kind-scoped.
280 */
281export function getDefaultProviderInstanceModel(
282 providers: ReadonlyArray<ServerProvider>,
283 instanceId: ProviderInstanceId,
284): string | undefined {
285 const entry = getProviderInstanceEntry(providers, instanceId);
286 if (!entry) return undefined;
287 return (
288 entry.models.find((model) => model.isDefault && !model.isCustom)?.slug ??
289 entry.models.find((model) => !model.isCustom)?.slug ??
290 entry.models[0]?.slug ??
291 DEFAULT_MODEL_BY_PROVIDER[entry.driverKind]
292 );
294​
295const isSelectableProviderInstanceEntry = (entry: ProviderInstanceEntry): boolean =>
296 entry.enabled && entry.isAvailable;
297​
298/**
299 * Resolve an exact stored instance when it remains enabled and available.
300 * Otherwise choose a deterministic fallback that can plausibly start now:
301 * ready first, then a non-error probe result. An errored provider is retained
302 * only when it was explicitly requested; it is never invented as a new-user
303 * default.
304 */
305export function resolveSelectableProviderInstanceEntry(
306 entries: ReadonlyArray<ProviderInstanceEntry>,
307 instanceId: ProviderInstanceId | undefined,
308): ProviderInstanceEntry | undefined {
309 if (instanceId !== undefined) {
310 const requested = entries.find((entry) => entry.instanceId === instanceId);
311 if (requested && isSelectableProviderInstanceEntry(requested)) {
312 return requested;
313 }
314 }
315 return (
316 entries.find(isProviderInstancePickerReady) ??
317 entries.find((entry) => isSelectableProviderInstanceEntry(entry) && entry.status !== "error")
318 );
320​
321/**
322 * Resolve the routing key for a selection that may reference an instance
323 * id that no longer exists (e.g. a persisted thread selection after the
324 * user deleted the custom instance). Returns a ready or non-error fallback,
325 * or `undefined` when no provider can safely become a new selection.
326 */
327export function resolveSelectableProviderInstance(
328 providers: ReadonlyArray<ServerProvider>,
329 instanceId: ProviderInstanceId | undefined,
330): ProviderInstanceId | undefined {
331 const entries = deriveProviderInstanceEntries(providers);
332 return resolveSelectableProviderInstanceEntry(entries, instanceId)?.instanceId;
334​
335/**
336 * Resolve the model selection persisted for a project or new thread. A valid
337 * stored selection is preserved byte-for-byte. Falling back to another
338 * instance also resets the model to that instance's own default, avoiding
339 * cross-provider instance/model pairs.
340 */
341export function resolveDefaultProviderModelSelection(
342 providers: ReadonlyArray<ServerProvider>,
343 selection: ModelSelection | null | undefined,
344): ModelSelection | null {
345 const instanceId = resolveSelectableProviderInstance(providers, selection?.instanceId);
346 if (instanceId === undefined) return null;
347 if (selection?.instanceId === instanceId) return selection;
348 const model = getDefaultProviderInstanceModel(providers, instanceId);
349 return model ? { instanceId, model } : null;