Open History to see the last commit
1import {
2 DEFAULT_MODEL_BY_PROVIDER,
3 defaultInstanceIdForDriver,
4 resolveProjectProviderInstanceEnabled,
5 type ModelSelection,
6 type ProjectId,
7 type ProviderDriverKind,
8 ProviderInstanceId,
9 type ServerProvider,
10 type ServerProviderModel,
11 type ServerSettings,
12 type ServerProviderState,
13} from "@t3tools/contracts";
14import {
15 normalizeProviderAccentColor,
16 resolveProviderInstanceDisplayName,
17 shouldShowInstanceBadge,
18} from "@t3tools/client-runtime/state/provider-instance-display";
19
20export { normalizeProviderAccentColor, shouldShowInstanceBadge };
21
22/**
23 * Local-only placeholder used while a draft has no provider it can safely
24 * target. It must never be persisted or dispatched; the composer disables
25 * send until a live provider replaces it.
26 */
27export const NO_PROVIDER_MODEL_SELECTION: ModelSelection = {
28 instanceId: ProviderInstanceId.make("t3code_no_provider"),
29 model: "",
30};
31
32export interface ProviderInstanceEntry {
33 readonly instanceId: ProviderInstanceId;
34 readonly driverKind: ProviderDriverKind;
35 readonly displayName: string;
36 readonly accentColor?: string | undefined;
37 readonly acpRegistryAgentId?: string | undefined;
38 readonly acpRegistryIconUrl?: string | undefined;
39 readonly continuationGroupKey?: string | undefined;
40 readonly enabled: boolean;
41 readonly installed: boolean;
42 readonly status: ServerProviderState;
43 readonly isDefault: boolean;
44 readonly isAvailable: boolean;
45 readonly snapshot: ServerProvider;
46 readonly models: ReadonlyArray<ServerProviderModel>;
47}
48
49export type ProviderCatalogAvailability = "loading" | "ready" | "unavailable" | "unconfigured";
50
51/**
52 * Environment config streams are reactive: treating their initial `null` as a
53 * final empty list strands otherwise recoverable threads behind a misleading
54 * "no providers" state.
55 */
56export function resolveProviderCatalogAvailability(input: {
57 readonly catalogLoaded: boolean;
58 readonly entries: ReadonlyArray<ProviderInstanceEntry>;
59 readonly selectedEntry: ProviderInstanceEntry | undefined;
60}): ProviderCatalogAvailability {
61 if (!input.catalogLoaded) return "loading";
62 if (input.selectedEntry !== undefined) return "ready";
63 return input.entries.length === 0 ? "unconfigured" : "unavailable";
64}
65
66/**
67 * Disabling an instance updates `enabled` independently, while its previous `ready` probe
68 * status can remain in the streamed snapshot until reconciliation.
69 */
70export function isProviderInstancePickerReady(entry: ProviderInstanceEntry): boolean {
71 return entry.enabled && entry.isAvailable && entry.status === "ready";
72}
73
74export function isProviderInstancePickerVisible(entry: ProviderInstanceEntry): boolean {
75 return entry.enabled;
76}
77
78export function deriveProviderInstanceEntries(
79 providers: ReadonlyArray<ServerProvider>,
80): ReadonlyArray<ProviderInstanceEntry> {
81 return providers.map((snapshot) => {
82 const instanceId = snapshot.instanceId;
83 const driverKind = snapshot.driver;
84 const defaultId = defaultInstanceIdForDriver(driverKind);
85 const isDefault = instanceId === defaultId;
86 return {
87 instanceId,
88 driverKind,
89 displayName: resolveProviderInstanceDisplayName(snapshot),
90 accentColor: normalizeProviderAccentColor(snapshot.accentColor),
91 ...(driverKind === "acpRegistry" && snapshot.iconUrl
92 ? { acpRegistryIconUrl: snapshot.iconUrl }
93 : {}),
94 continuationGroupKey: snapshot.continuation?.groupKey,
95 enabled: snapshot.enabled,
96 installed: snapshot.installed,
97 status: snapshot.status,
98 isDefault,
99 isAvailable: snapshot.availability !== "unavailable",
100 snapshot,
101 models: snapshot.models,
102 } satisfies ProviderInstanceEntry;
103 });
104}
105
106/**
107 * Instance ids are per-environment routing keys, and `defaultInstanceIdForDriver` makes the
108 * default id literally the driver slug, so every environment running the same driver reports
109 * the same id. Flattening across environments would clobber entries and mis-resolve accent
110 * colors; lookups must stay scoped to the thread's own environment.
111 */
112export function deriveProviderEntriesByEnvironment(
113 providersByEnvironment: Iterable<
114 readonly [
115 string,
116 ReadonlyArray<ServerProvider>,
117 Pick<ServerSettings, "providerInstances" | "projectSettingsOverrides">?,
118 ]
119 >,
120): ReadonlyMap<string, ReadonlyMap<string, ProviderInstanceEntry>> {
121 const byEnvironment = new Map<string, ReadonlyMap<string, ProviderInstanceEntry>>();
122 for (const [environmentId, providers, settings] of providersByEnvironment) {
123 const derived = deriveProviderInstanceEntries(providers);
124 // The snapshot includes instances enabled by any project; machine settings alone do not.
125 const entries = settings
126 ? derived.map((entry) => applyProviderInstanceBranding(entry, settings))
127 : derived;
128 byEnvironment.set(
129 environmentId,
130 new Map(entries.map((entry) => [entry.instanceId as string, entry] as const)),
131 );
132 }
133 return byEnvironment;
134}
135
136/**
137 * `projectId` folds in that project's `providerInstances[id].enabled` override (enable or
138 * disable in either direction over the machine value); `null` resolves the machine value only.
139 * It has no default: a caller that renders for a single project but forgets to pass it would
140 * silently show the machine's enablement instead of that project's, so passing `null` for a
141 * surface that isn't project-aware must be a deliberate choice, not an omission.
142 */
143export function applyProviderInstanceSettings(
144 entries: ReadonlyArray<ProviderInstanceEntry>,
145 settings: Pick<ServerSettings, "providerInstances" | "projectSettingsOverrides">,
146 projectId: ProjectId | null,
147): ReadonlyArray<ProviderInstanceEntry> {
148 return entries.map((entry) => {
149 const enabled = resolveProjectProviderInstanceEnabled(settings, projectId, entry.instanceId);
150 return applyProviderInstanceBranding(
151 enabled === entry.enabled ? entry : { ...entry, enabled },
152 settings,
153 );
154 });
155}
156
157function applyProviderInstanceBranding(
158 entry: ProviderInstanceEntry,
159 settings: Pick<ServerSettings, "providerInstances">,
160): ProviderInstanceEntry {
161 const explicitInstance = Object.hasOwn(settings.providerInstances, entry.instanceId)
162 ? settings.providerInstances[entry.instanceId]
163 : undefined;
164 if (entry.driverKind !== "acpRegistry" || explicitInstance === undefined) return entry;
165 const config =
166 explicitInstance.config !== null && typeof explicitInstance.config === "object"
167 ? (explicitInstance.config as Readonly<Record<string, unknown>>)
168 : null;
169 if (config?.source === "local") {
170 return { ...entry, acpRegistryAgentId: undefined, acpRegistryIconUrl: undefined };
171 }
172 const agentId = config?.agentId;
173 const iconUrl = config?.registryIconUrl;
174 return {
175 ...entry,
176 ...(typeof agentId === "string" && agentId.trim()
177 ? { acpRegistryAgentId: agentId.trim() }
178 : {}),
179 ...(typeof iconUrl === "string" && iconUrl.trim()
180 ? { acpRegistryIconUrl: iconUrl.trim() }
181 : {}),
182 };
183}
184
185export function sortProviderInstanceEntries(
186 entries: ReadonlyArray<ProviderInstanceEntry>,
187): ReadonlyArray<ProviderInstanceEntry> {
188 const byKind = new Map<ProviderDriverKind, ProviderInstanceEntry[]>();
189 for (const entry of entries) {
190 const bucket = byKind.get(entry.driverKind);
191 if (bucket) {
192 bucket.push(entry);
193 } else {
194 byKind.set(entry.driverKind, [entry]);
195 }
196 }
197 const sorted: ProviderInstanceEntry[] = [];
198 for (const bucket of byKind.values()) {
199 const defaults = bucket.filter((entry) => entry.isDefault);
200 const customs = bucket.filter((entry) => !entry.isDefault);
201 sorted.push(...defaults, ...customs);
202 }
203 return sorted;
204}
205
206function getProviderInstanceEntry(
207 providers: ReadonlyArray<ServerProvider>,
208 instanceId: ProviderInstanceId,
209): ProviderInstanceEntry | undefined {
210 return deriveProviderInstanceEntries(providers).find((entry) => entry.instanceId === instanceId);
211}
212
213export function getDefaultProviderInstanceModel(
214 providers: ReadonlyArray<ServerProvider>,
215 instanceId: ProviderInstanceId,
216): string | undefined {
217 const entry = getProviderInstanceEntry(providers, instanceId);
218 if (!entry) return undefined;
219 return (
220 entry.models.find((model) => model.isDefault && !model.isCustom)?.slug ??
221 entry.models.find((model) => !model.isCustom)?.slug ??
222 entry.models[0]?.slug ??
223 DEFAULT_MODEL_BY_PROVIDER[entry.driverKind]
224 );
225}
226
227const isSelectableProviderInstanceEntry = (entry: ProviderInstanceEntry): boolean =>
228 entry.enabled && entry.isAvailable;
229
230export function resolveSelectableProviderInstanceEntry(
231 entries: ReadonlyArray<ProviderInstanceEntry>,
232 instanceId: ProviderInstanceId | undefined,
233): ProviderInstanceEntry | undefined {
234 if (instanceId !== undefined) {
235 const requested = entries.find((entry) => entry.instanceId === instanceId);
236 if (requested && isSelectableProviderInstanceEntry(requested)) {
237 return requested;
238 }
239 }
240 return (
241 entries.find(isProviderInstancePickerReady) ??
242 entries.find((entry) => isSelectableProviderInstanceEntry(entry) && entry.status !== "error")
243 );
244}
245
246export function resolveSelectableProviderInstance(
247 providers: ReadonlyArray<ServerProvider>,
248 instanceId: ProviderInstanceId | undefined,
249): ProviderInstanceId | undefined {
250 const entries = deriveProviderInstanceEntries(providers);
251 return resolveSelectableProviderInstanceEntry(entries, instanceId)?.instanceId;
252}
253
254export function resolveDefaultProviderModelSelection(
255 providers: ReadonlyArray<ServerProvider>,
256 selection: ModelSelection | null | undefined,
257): ModelSelection | null {
258 const instanceId = resolveSelectableProviderInstance(providers, selection?.instanceId);
259 if (instanceId === undefined) return null;
260 if (selection?.instanceId === instanceId) return selection;
261 const model = getDefaultProviderInstanceModel(providers, instanceId);
262 return model ? { instanceId, model } : null;
263}