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

providerInstances.ts

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