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

providerInstances.ts

347 lines13.7 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 const agentId = config?.agentId;
214 const iconUrl = config?.registryIconUrl;
215 return {
216 ...entry,
217 enabled,
218 ...(typeof agentId === "string" && agentId.trim()
219 ? { acpRegistryAgentId: agentId.trim() }
220 : {}),
221 ...(typeof iconUrl === "string" && iconUrl.trim()
222 ? { acpRegistryIconUrl: iconUrl.trim() }
223 : {}),
224 };
225 });
227​
228/**
229 * Sort instance entries so the default instance of each driver kind appears
230 * before any custom instances of the same kind. Within a kind, custom
231 * instances keep their settings-author order (which is how the server
232 * emits them). Stable across kinds: entries retain the server's
233 * cross-driver ordering.
234 */
235export function sortProviderInstanceEntries(
236 entries: ReadonlyArray<ProviderInstanceEntry>,
237): ReadonlyArray<ProviderInstanceEntry> {
238 // Group by driver kind preserving first-appearance order, then emit
239 // default-first within each kind. Using a Map keeps the "first-seen"
240 // semantics for kinds whose default instance is absent (unusual but
241 // possible during the migration).
242 const byKind = new Map<ProviderDriverKind, ProviderInstanceEntry[]>();
243 for (const entry of entries) {
244 const bucket = byKind.get(entry.driverKind);
245 if (bucket) {
246 bucket.push(entry);
247 } else {
248 byKind.set(entry.driverKind, [entry]);
249 }
250 }
251 const sorted: ProviderInstanceEntry[] = [];
252 for (const bucket of byKind.values()) {
253 const defaults = bucket.filter((entry) => entry.isDefault);
254 const customs = bucket.filter((entry) => !entry.isDefault);
255 sorted.push(...defaults, ...customs);
256 }
257 return sorted;
259​
260/**
261 * Look up a single instance entry by exact `instanceId`. Missing snapshots
262 * are not inferred from driver kind in UI routing code.
263 */
264export function getProviderInstanceEntry(
265 providers: ReadonlyArray<ServerProvider>,
266 instanceId: ProviderInstanceId,
267): ProviderInstanceEntry | undefined {
268 return deriveProviderInstanceEntries(providers).find((entry) => entry.instanceId === instanceId);
270​
271/**
272 * Default model slug for a specific instance: its declared built-in default,
273 * then its first built-in model, then any model it reports, then the driver-level default. Custom
274 * instances can serve a different model list than the default instance of
275 * the same driver kind, so the lookup must be instance-scoped rather than
276 * kind-scoped.
277 */
278export function getDefaultProviderInstanceModel(
279 providers: ReadonlyArray<ServerProvider>,
280 instanceId: ProviderInstanceId,
281): string | undefined {
282 const entry = getProviderInstanceEntry(providers, instanceId);
283 if (!entry) return undefined;
284 return (
285 entry.models.find((model) => model.isDefault && !model.isCustom)?.slug ??
286 entry.models.find((model) => !model.isCustom)?.slug ??
287 entry.models[0]?.slug ??
288 DEFAULT_MODEL_BY_PROVIDER[entry.driverKind]
289 );
291​
292const isSelectableProviderInstanceEntry = (entry: ProviderInstanceEntry): boolean =>
293 entry.enabled && entry.isAvailable;
294​
295/**
296 * Resolve an exact stored instance when it remains enabled and available.
297 * Otherwise choose a deterministic fallback that can plausibly start now:
298 * ready first, then a non-error probe result. An errored provider is retained
299 * only when it was explicitly requested; it is never invented as a new-user
300 * default.
301 */
302export function resolveSelectableProviderInstanceEntry(
303 entries: ReadonlyArray<ProviderInstanceEntry>,
304 instanceId: ProviderInstanceId | undefined,
305): ProviderInstanceEntry | undefined {
306 if (instanceId !== undefined) {
307 const requested = entries.find((entry) => entry.instanceId === instanceId);
308 if (requested && isSelectableProviderInstanceEntry(requested)) {
309 return requested;
310 }
311 }
312 return (
313 entries.find(isProviderInstancePickerReady) ??
314 entries.find((entry) => isSelectableProviderInstanceEntry(entry) && entry.status !== "error")
315 );
317​
318/**
319 * Resolve the routing key for a selection that may reference an instance
320 * id that no longer exists (e.g. a persisted thread selection after the
321 * user deleted the custom instance). Returns a ready or non-error fallback,
322 * or `undefined` when no provider can safely become a new selection.
323 */
324export function resolveSelectableProviderInstance(
325 providers: ReadonlyArray<ServerProvider>,
326 instanceId: ProviderInstanceId | undefined,
327): ProviderInstanceId | undefined {
328 const entries = deriveProviderInstanceEntries(providers);
329 return resolveSelectableProviderInstanceEntry(entries, instanceId)?.instanceId;
331​
332/**
333 * Resolve the model selection persisted for a project or new thread. A valid
334 * stored selection is preserved byte-for-byte. Falling back to another
335 * instance also resets the model to that instance's own default, avoiding
336 * cross-provider instance/model pairs.
337 */
338export function resolveDefaultProviderModelSelection(
339 providers: ReadonlyArray<ServerProvider>,
340 selection: ModelSelection | null | undefined,
341): ModelSelection | null {
342 const instanceId = resolveSelectableProviderInstance(providers, selection?.instanceId);
343 if (instanceId === undefined) return null;
344 if (selection?.instanceId === instanceId) return selection;
345 const model = getDefaultProviderInstanceModel(providers, instanceId);
346 return model ? { instanceId, model } : null;