Open History to see the last commit
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>;
74}
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";
92}
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";
102}
103
104/** Picker rails contain configured, enabled instances only. */
105export function isProviderInstancePickerVisible(entry: ProviderInstanceEntry): boolean {
106 return entry.enabled;
107}
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 continuationGroupKey: snapshot.continuation?.groupKey,
130 enabled: snapshot.enabled,
131 installed: snapshot.installed,
132 status: snapshot.status,
133 isDefault,
134 isAvailable: snapshot.availability !== "unavailable",
135 snapshot,
136 models: snapshot.models,
137 } satisfies ProviderInstanceEntry;
138 });
139}
140
141/**
142 * Project several environments' `ServerProvider[]` into a nested
143 * `environmentId → instanceId → entry` lookup.
144 *
145 * Instance ids are per-environment routing keys, and `defaultInstanceIdForDriver`
146 * makes the default id literally the driver slug, so every environment running
147 * the same driver reports the same id. Flattening across environments would
148 * clobber entries and mis-resolve accent colors; lookups must stay scoped to
149 * the thread's own environment.
150 */
151export function deriveProviderEntriesByEnvironment(
152 providersByEnvironment: Iterable<readonly [string, ReadonlyArray<ServerProvider>]>,
153): ReadonlyMap<string, ReadonlyMap<string, ProviderInstanceEntry>> {
154 const byEnvironment = new Map<string, ReadonlyMap<string, ProviderInstanceEntry>>();
155 for (const [environmentId, providers] of providersByEnvironment) {
156 byEnvironment.set(
157 environmentId,
158 new Map(
159 deriveProviderInstanceEntries(providers).map(
160 (entry) => [entry.instanceId as string, entry] as const,
161 ),
162 ),
163 );
164 }
165 return byEnvironment;
166}
167
168/**
169 * Overlay the current settings configuration onto streamed provider snapshots.
170 * Provider probes can briefly retain their previous `enabled` value after a
171 * settings write, so picker visibility must follow settings rather than waiting
172 * for probe reconciliation.
173 *
174 * Only built-in default instances have a legacy `providers` entry. Every
175 * other instance exists through `providerInstances`; if it is absent there,
176 * its streamed snapshot is stale (for example immediately after deletion)
177 * and is treated as disabled.
178 */
179export function applyProviderInstanceSettings(
180 entries: ReadonlyArray<ProviderInstanceEntry>,
181 settings: Pick<ServerSettings, "providerInstances" | "providers">,
182): ReadonlyArray<ProviderInstanceEntry> {
183 const legacyProviders = settings.providers as Readonly<
184 Record<string, { readonly enabled?: boolean } | undefined>
185 >;
186
187 return entries.map((entry) => {
188 const explicitInstance = Object.hasOwn(settings.providerInstances, entry.instanceId)
189 ? settings.providerInstances[entry.instanceId]
190 : undefined;
191 const legacyProvider = Object.hasOwn(legacyProviders, entry.driverKind)
192 ? legacyProviders[entry.driverKind]
193 : undefined;
194 const enabled = explicitInstance
195 ? resolveProviderInstanceEnabled(explicitInstance)
196 : entry.isDefault && legacyProvider
197 ? (legacyProvider.enabled ?? entry.enabled)
198 : false;
199 if (entry.driverKind !== "acpRegistry" || explicitInstance === undefined) {
200 return enabled === entry.enabled ? entry : { ...entry, enabled };
201 }
202 const config =
203 explicitInstance.config !== null && typeof explicitInstance.config === "object"
204 ? (explicitInstance.config as Readonly<Record<string, unknown>>)
205 : null;
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 });
219}
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;
251}
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);
262}
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 );
283}
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 );
309}
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;
323}
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;
340}
341
342/**
343 * Resolve an open model-selection routing key back to a driver kind.
344 * Custom instance ids such as `claude_openrouter` are not themselves
345 * driver-kind slugs, but the composer still needs the owning driver kind
346 * for capabilities, options, icons, and turn dispatch metadata.
347 */
348export function resolveProviderDriverKindForInstanceSelection(
349 entries: ReadonlyArray<ProviderInstanceEntry>,
350 providers: ReadonlyArray<ServerProvider>,
351 selection: ProviderInstanceId | ProviderDriverKind | null | undefined,
352): ProviderDriverKind | undefined {
353 const matchedEntry = entries.find((entry) => entry.instanceId === selection);
354 if (matchedEntry) {
355 return matchedEntry.driverKind;
356 }
357 return undefined;
358}