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

providerInstances.ts

295 lines11.5 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 defaultInstanceIdForDriver,
17 PROVIDER_DISPLAY_NAMES,
18 type ProviderDriverKind,
19 type ProviderInstanceId,
20 type ServerProvider,
21 type ServerProviderModel,
22 type ServerSettings,
23 type ServerProviderState,
24} from "@t3tools/contracts";
25​
26import { formatProviderDriverKindLabel } from "./providerModels";
27​
28/**
29 * UI-facing projection of one configured provider instance. Carries the
30 * snapshot verbatim for callers that need server-side fields we don't
31 * hoist here, plus the precomputed `instanceId` / `driverKind` /
32 * `displayName` used by every picker and settings view.
33 */
34export interface ProviderInstanceEntry {
35 readonly instanceId: ProviderInstanceId;
36 readonly driverKind: ProviderDriverKind;
37 readonly displayName: string;
38 readonly accentColor?: string | undefined;
39 readonly continuationGroupKey?: string | undefined;
40 readonly enabled: boolean;
41 readonly installed: boolean;
42 readonly status: ServerProviderState;
43 /**
44 * True when this entry is the default instance for its driver kind —
45 * i.e. its instance id equals `defaultInstanceIdForDriver(driverKind)`.
46 * The settings panel and picker sort defaults before customs.
47 */
48 readonly isDefault: boolean;
49 /** True when `availability === "unavailable"` is absent or "available". */
50 readonly isAvailable: boolean;
51 readonly snapshot: ServerProvider;
52 readonly models: ReadonlyArray<ServerProviderModel>;
54​
55/**
56 * Whether an instance can currently contribute models to an interactive picker.
57 *
58 * Disabling an instance updates `enabled` independently, while its previous
59 * `ready` probe status can remain in the streamed snapshot until reconciliation.
60 */
61export function isProviderInstancePickerReady(entry: ProviderInstanceEntry): boolean {
62 return entry.enabled && entry.isAvailable && entry.status === "ready";
64​
65/** Picker rails contain configured, enabled instances only. */
66export function isProviderInstancePickerVisible(entry: ProviderInstanceEntry): boolean {
67 return entry.enabled;
69​
70/**
71 * Turn an instance id slug into a human-readable label. Splits on `_` / `-`
72 * and camelCase boundaries and title-cases each token, so `codex_personal`
73 * becomes "Codex Personal" and `myCustomInstance` becomes "My Custom
74 * Instance".
75 *
76 * This is a fallback used only when the wire snapshot's `displayName`
77 * doesn't disambiguate a non-default instance from the default one of the
78 * same driver (today every built-in driver hard-codes a single presentation
79 * label per kind, so two instances of the same kind arrive with identical
80 * display names). When a server/driver later plumbs the user's configured
81 * `ProviderInstanceConfig.displayName` through to the snapshot, that value
82 * will take precedence over this fallback.
83 */
84function humanizeInstanceId(instanceId: ProviderInstanceId): string {
85 const words: string[] = [];
86 for (const token of instanceId
87 .replace(/[_-]+/g, " ")
88 .replace(/([a-z])([A-Z])/g, "$1 $2")
89 .split(" ")) {
90 if (token.length === 0) continue;
91 words.push(token.charAt(0).toUpperCase() + token.slice(1));
92 }
93 return words.join(" ");
95​
96function driverKindLabel(driverKind: ProviderDriverKind): string {
97 return PROVIDER_DISPLAY_NAMES[driverKind] ?? formatProviderDriverKindLabel(driverKind);
99​
100export function normalizeProviderAccentColor(value: string | undefined): string | undefined {
101 const trimmed = value?.trim();
102 if (!trimmed) return undefined;
103 return /^#[0-9a-fA-F]{6}$/u.test(trimmed) ? trimmed : undefined;
105​
106/**
107 * Resolve an entry's displayName with a tiered priority:
108 *
109 * 1. A snapshot `displayName` that differs from the driver-kind label —
110 * the server has explicitly named this instance, trust it.
111 * 2. For non-default instances, a humanized `instanceId` — the server
112 * fell back to the driver-level presentation constant (which is the
113 * same for every instance of that kind), so we differentiate at the
114 * UI layer by slug. This is what keeps "Codex" + "Codex Personal"
115 * distinguishable in tooltips and list labels today.
116 * 3. The snapshot's `displayName` (if any) — default instance, trust
117 * whatever label the driver stamped.
118 * 4. `driverKindLabel(driverKind)` — nothing else on hand, so use the
119 * canonical brand label from contracts (falling back to a generic
120 * title-case of the kind slug).
121 */
122function resolveInstanceDisplayName(
123 snapshot: ServerProvider,
124 instanceId: ProviderInstanceId,
125 driverKind: ProviderDriverKind,
126 isDefault: boolean,
127): string {
128 const trimmedSnapshotName = snapshot.displayName?.trim();
129 const kindLabel = driverKindLabel(driverKind);
130 if (trimmedSnapshotName && trimmedSnapshotName !== kindLabel) {
131 return trimmedSnapshotName;
132 }
133 if (!isDefault) {
134 const humanized = humanizeInstanceId(instanceId);
135 if (humanized.length > 0) return humanized;
136 }
137 return trimmedSnapshotName || kindLabel;
139​
140/**
141 * Project the wire `ServerProvider[]` into instance entries, one per
142 * configured instance. Preserves the server's ordering (which sources
143 * from `deriveProviderInstanceConfigMap` — explicit `providerInstances.*`
144 * first, synthesized defaults after) so callers that want "default first"
145 * should sort with `sortProviderInstanceEntries` below.
146 */
147export function deriveProviderInstanceEntries(
148 providers: ReadonlyArray<ServerProvider>,
149): ReadonlyArray<ProviderInstanceEntry> {
150 return providers.map((snapshot) => {
151 const instanceId = snapshot.instanceId;
152 const driverKind = snapshot.driver;
153 const defaultId = defaultInstanceIdForDriver(driverKind);
154 const isDefault = instanceId === defaultId;
155 const displayName = resolveInstanceDisplayName(snapshot, instanceId, driverKind, isDefault);
156 return {
157 instanceId,
158 driverKind,
159 displayName,
160 accentColor: normalizeProviderAccentColor(snapshot.accentColor),
161 continuationGroupKey: snapshot.continuation?.groupKey,
162 enabled: snapshot.enabled,
163 installed: snapshot.installed,
164 status: snapshot.status,
165 isDefault,
166 isAvailable: snapshot.availability !== "unavailable",
167 snapshot,
168 models: snapshot.models,
169 } satisfies ProviderInstanceEntry;
170 });
172​
173/**
174 * Overlay the current settings configuration onto streamed provider snapshots.
175 * Provider probes can briefly retain their previous `enabled` value after a
176 * settings write, so picker visibility must follow settings rather than waiting
177 * for probe reconciliation.
178 *
179 * Non-default instances only exist through `providerInstances`; if one is
180 * absent there, its streamed snapshot is stale (for example immediately after
181 * deletion) and is treated as disabled.
182 */
183export function applyProviderInstanceSettings(
184 entries: ReadonlyArray<ProviderInstanceEntry>,
185 settings: Pick<ServerSettings, "providerInstances" | "providers">,
186): ReadonlyArray<ProviderInstanceEntry> {
187 const legacyProviders = settings.providers as Readonly<
188 Record<string, { readonly enabled?: boolean } | undefined>
189 >;
190​
191 return entries.map((entry) => {
192 const explicitInstance = settings.providerInstances?.[entry.instanceId];
193 const enabled = explicitInstance
194 ? (explicitInstance.enabled ?? true)
195 : entry.isDefault
196 ? (legacyProviders[entry.driverKind]?.enabled ?? entry.enabled)
197 : false;
198 return enabled === entry.enabled ? entry : { ...entry, enabled };
199 });
201​
202/**
203 * Sort instance entries so the default instance of each driver kind appears
204 * before any custom instances of the same kind. Within a kind, custom
205 * instances keep their settings-author order (which is how the server
206 * emits them). Stable across kinds: entries retain the server's
207 * cross-driver ordering.
208 */
209export function sortProviderInstanceEntries(
210 entries: ReadonlyArray<ProviderInstanceEntry>,
211): ReadonlyArray<ProviderInstanceEntry> {
212 // Group by driver kind preserving first-appearance order, then emit
213 // default-first within each kind. Using a Map keeps the "first-seen"
214 // semantics for kinds whose default instance is absent (unusual but
215 // possible during the migration).
216 const byKind = new Map<ProviderDriverKind, ProviderInstanceEntry[]>();
217 for (const entry of entries) {
218 const bucket = byKind.get(entry.driverKind);
219 if (bucket) {
220 bucket.push(entry);
221 } else {
222 byKind.set(entry.driverKind, [entry]);
223 }
224 }
225 const sorted: ProviderInstanceEntry[] = [];
226 for (const bucket of byKind.values()) {
227 const defaults = bucket.filter((entry) => entry.isDefault);
228 const customs = bucket.filter((entry) => !entry.isDefault);
229 sorted.push(...defaults, ...customs);
230 }
231 return sorted;
233​
234/**
235 * Look up a single instance entry by exact `instanceId`. Missing snapshots
236 * are not inferred from driver kind in UI routing code.
237 */
238export function getProviderInstanceEntry(
239 providers: ReadonlyArray<ServerProvider>,
240 instanceId: ProviderInstanceId,
241): ProviderInstanceEntry | undefined {
242 return deriveProviderInstanceEntries(providers).find((entry) => entry.instanceId === instanceId);
244​
245/**
246 * Model list for a specific instance. Returns `[]` when the instance isn't
247 * present so callers don't have to thread optionality through render code.
248 */
249export function getProviderInstanceModels(
250 providers: ReadonlyArray<ServerProvider>,
251 instanceId: ProviderInstanceId,
252): ReadonlyArray<ServerProviderModel> {
253 return getProviderInstanceEntry(providers, instanceId)?.models ?? [];
255​
256/**
257 * Resolve the routing key for a selection that may reference an instance
258 * id that no longer exists (e.g. a persisted thread selection after the
259 * user deleted the custom instance). Returns the first enabled instance
260 * as a fallback so downstream code can still send a turn.
261 */
262export function resolveSelectableProviderInstance(
263 providers: ReadonlyArray<ServerProvider>,
264 instanceId: ProviderInstanceId | undefined,
265): ProviderInstanceId | undefined {
266 if (instanceId === undefined) {
267 return deriveProviderInstanceEntries(providers).find(
268 (entry) => entry.enabled && entry.isAvailable,
269 )?.instanceId;
270 }
271 const entries = deriveProviderInstanceEntries(providers);
272 const requested = entries.find((entry) => entry.instanceId === instanceId);
273 if (requested && requested.enabled && requested.isAvailable) {
274 return instanceId;
275 }
276 return entries.find((entry) => entry.enabled && entry.isAvailable)?.instanceId;
278​
279/**
280 * Resolve an open model-selection routing key back to a driver kind.
281 * Custom instance ids such as `claude_openrouter` are not themselves
282 * driver-kind slugs, but the composer still needs the owning driver kind
283 * for capabilities, options, icons, and turn dispatch metadata.
284 */
285export function resolveProviderDriverKindForInstanceSelection(
286 entries: ReadonlyArray<ProviderInstanceEntry>,
287 providers: ReadonlyArray<ServerProvider>,
288 selection: ProviderInstanceId | ProviderDriverKind | null | undefined,
289): ProviderDriverKind | undefined {
290 const matchedEntry = entries.find((entry) => entry.instanceId === selection);
291 if (matchedEntry) {
292 return matchedEntry.driverKind;
293 }
294 return undefined;