Open History to see the last commit
1import { pipe } from "effect/Function";
2import {
3 DEFAULT_MODEL_BY_PROVIDER,
4 defaultInstanceIdForDriver,
5 resolveProjectProviderInstanceEnabled,
6 type ModelSelection,
7 type ProjectId,
8 type ProviderDriverKind,
9 ProviderInstanceId,
10 type ServerProvider,
11 type ServerProviderModel,
12 type ServerSettings,
13 type ServerProviderState,
14} from "@t3tools/contracts";
15import {
16 normalizeProviderAccentColor,
17 resolveProviderInstanceDisplayName,
18 shouldShowInstanceBadge,
19} from "@t3tools/client-runtime/state/provider-instance-display";
20
21export { normalizeProviderAccentColor, shouldShowInstanceBadge };
22
23/** Placeholder for untargetable drafts. Never persist or dispatch it; disable send until replaced. */
24export const NO_PROVIDER_MODEL_SELECTION: ModelSelection = {
25 instanceId: ProviderInstanceId.make("t3code_no_provider"),
26 model: "",
27};
28
29export interface ProviderInstanceEntry {
30 readonly instanceId: ProviderInstanceId;
31 readonly driverKind: ProviderDriverKind;
32 readonly displayName: string;
33 readonly accentColor?: string | undefined;
34 readonly acpRegistryAgentId?: string | undefined;
35 readonly acpRegistryIconUrl?: string | undefined;
36 readonly continuationGroupKey?: string | undefined;
37 readonly enabled: boolean;
38 readonly installed: boolean;
39 readonly status: ServerProviderState;
40 readonly isDefault: boolean;
41 readonly isAvailable: boolean;
42 readonly snapshot: ServerProvider;
43 readonly models: ReadonlyArray<ServerProviderModel>;
44}
45
46/** Status dots share one corner per user, so a badge on one row can't move only that row's dot. */
47export function hasInstanceBadge(entries: ReadonlyArray<ProviderInstanceEntry>): boolean {
48 return entries.some((entry) => shouldShowInstanceBadge(entry, entries));
49}
50
51/**
52 * Disabled instances may retain ready status until reconciliation. A warning still offers
53 * the models of sub-providers that report no problem of their own.
54 */
55export function isProviderInstancePickerReady(entry: ProviderInstanceEntry): boolean {
56 if (!entry.enabled || !entry.isAvailable) return false;
57 if (entry.status === "ready") return true;
58 if (entry.status !== "warning") return false;
59 const usable = new Set(
60 entry.snapshot.subProviders?.flatMap((subProvider) =>
61 subProvider.unavailableReason === undefined ? [subProvider.name] : [],
62 ),
63 );
64 return entry.models.some(
65 (model) => model.subProvider !== undefined && usable.has(model.subProvider),
66 );
67}
68
69export function isProviderInstancePickerVisible(entry: ProviderInstanceEntry): boolean {
70 return entry.enabled;
71}
72
73export function deriveProviderInstanceEntries(
74 providers: ReadonlyArray<ServerProvider>,
75): ReadonlyArray<ProviderInstanceEntry> {
76 return providers.map((snapshot) => {
77 const instanceId = snapshot.instanceId;
78 const driverKind = snapshot.driver;
79 const defaultId = defaultInstanceIdForDriver(driverKind);
80 const isDefault = instanceId === defaultId;
81 return {
82 instanceId,
83 driverKind,
84 displayName: resolveProviderInstanceDisplayName(snapshot),
85 accentColor: normalizeProviderAccentColor(snapshot.accentColor),
86 ...(driverKind === "acpRegistry" && snapshot.iconUrl
87 ? { acpRegistryIconUrl: snapshot.iconUrl }
88 : {}),
89 continuationGroupKey: snapshot.continuation?.groupKey,
90 enabled: snapshot.enabled,
91 installed: snapshot.installed,
92 status: snapshot.status,
93 isDefault,
94 isAvailable: snapshot.availability !== "unavailable",
95 snapshot,
96 models: snapshot.models,
97 } satisfies ProviderInstanceEntry;
98 });
99}
100
101/** Instance ids repeat across environments; lookups must stay scoped. */
102export function deriveProviderEntriesByEnvironment(
103 providersByEnvironment: Iterable<
104 readonly [
105 string,
106 ReadonlyArray<ServerProvider>,
107 Pick<ServerSettings, "providerInstances" | "projectSettingsOverrides">?,
108 ]
109 >,
110): ReadonlyMap<string, ReadonlyMap<string, ProviderInstanceEntry>> {
111 const byEnvironment = new Map<string, ReadonlyMap<string, ProviderInstanceEntry>>();
112 for (const [environmentId, providers, settings] of providersByEnvironment) {
113 const derived = deriveProviderInstanceEntries(providers);
114 const entries = settings ? brandProviderInstanceEntries(derived, settings) : derived;
115 byEnvironment.set(
116 environmentId,
117 new Map(entries.map((entry) => [entry.instanceId as string, entry] as const)),
118 );
119 }
120 return byEnvironment;
121}
122
123// The snapshot includes instances enabled by any project; machine settings alone do not.
124export function brandProviderInstanceEntries(
125 entries: ReadonlyArray<ProviderInstanceEntry>,
126 settings: Pick<ServerSettings, "providerInstances">,
127): ReadonlyArray<ProviderInstanceEntry> {
128 return entries.map((entry) => applyProviderInstanceBranding(entry, settings));
129}
130
131/** projectId applies project overrides; explicit null uses machine settings. */
132export function applyProviderInstanceSettings(
133 entries: ReadonlyArray<ProviderInstanceEntry>,
134 settings: Pick<ServerSettings, "providerInstances" | "projectSettingsOverrides">,
135 projectId: ProjectId | null,
136): ReadonlyArray<ProviderInstanceEntry> {
137 return entries.map((entry) => {
138 const enabled = resolveProjectProviderInstanceEnabled(settings, projectId, entry.instanceId);
139 return applyProviderInstanceBranding(
140 enabled === entry.enabled ? entry : { ...entry, enabled },
141 settings,
142 );
143 });
144}
145
146function applyProviderInstanceBranding(
147 entry: ProviderInstanceEntry,
148 settings: Pick<ServerSettings, "providerInstances">,
149): ProviderInstanceEntry {
150 const explicitInstance = Object.hasOwn(settings.providerInstances, entry.instanceId)
151 ? settings.providerInstances[entry.instanceId]
152 : undefined;
153 if (entry.driverKind !== "acpRegistry" || explicitInstance === undefined) return entry;
154 const config =
155 explicitInstance.config !== null && typeof explicitInstance.config === "object"
156 ? (explicitInstance.config as Readonly<Record<string, unknown>>)
157 : null;
158 if (config?.source === "local") {
159 return { ...entry, acpRegistryAgentId: undefined, acpRegistryIconUrl: undefined };
160 }
161 const agentId = config?.agentId;
162 const iconUrl = config?.registryIconUrl;
163 return {
164 ...entry,
165 ...(typeof agentId === "string" && agentId.trim()
166 ? { acpRegistryAgentId: agentId.trim() }
167 : {}),
168 ...(typeof iconUrl === "string" && iconUrl.trim()
169 ? { acpRegistryIconUrl: iconUrl.trim() }
170 : {}),
171 };
172}
173
174/** Picker order: each driver's default instance first, then its custom instances. */
175export function providerInstanceEntriesFor(
176 providers: ReadonlyArray<ServerProvider>,
177 settings: Pick<ServerSettings, "providerInstances" | "projectSettingsOverrides">,
178 projectId: ProjectId | null,
179): ReadonlyArray<ProviderInstanceEntry> {
180 return pipe(
181 deriveProviderInstanceEntries(providers),
182 (entries) => applyProviderInstanceSettings(entries, settings, projectId),
183 sortProviderInstanceEntries,
184 );
185}
186
187function sortProviderInstanceEntries(
188 entries: ReadonlyArray<ProviderInstanceEntry>,
189): ReadonlyArray<ProviderInstanceEntry> {
190 const byKind = new Map<ProviderDriverKind, ProviderInstanceEntry[]>();
191 for (const entry of entries) {
192 const bucket = byKind.get(entry.driverKind);
193 if (bucket) {
194 bucket.push(entry);
195 } else {
196 byKind.set(entry.driverKind, [entry]);
197 }
198 }
199 const sorted: ProviderInstanceEntry[] = [];
200 for (const bucket of byKind.values()) {
201 const defaults = bucket.filter((entry) => entry.isDefault);
202 const customs = bucket.filter((entry) => !entry.isDefault);
203 sorted.push(...defaults, ...customs);
204 }
205 return sorted;
206}
207
208function getProviderInstanceEntry(
209 providers: ReadonlyArray<ServerProvider>,
210 instanceId: ProviderInstanceId,
211): ProviderInstanceEntry | undefined {
212 return deriveProviderInstanceEntries(providers).find((entry) => entry.instanceId === instanceId);
213}
214
215export function getDefaultProviderInstanceModel(
216 providers: ReadonlyArray<ServerProvider>,
217 instanceId: ProviderInstanceId,
218): string | undefined {
219 const entry = getProviderInstanceEntry(providers, instanceId);
220 if (!entry) return undefined;
221 return (
222 entry.models.find((model) => model.isDefault && !model.isCustom)?.slug ??
223 entry.models.find((model) => !model.isCustom)?.slug ??
224 entry.models[0]?.slug ??
225 DEFAULT_MODEL_BY_PROVIDER[entry.driverKind]
226 );
227}
228
229const isSelectableProviderInstanceEntry = (entry: ProviderInstanceEntry): boolean =>
230 entry.enabled && entry.isAvailable;
231
232export function resolveSelectableProviderInstanceEntry(
233 entries: ReadonlyArray<ProviderInstanceEntry>,
234 instanceId: ProviderInstanceId | undefined,
235): ProviderInstanceEntry | undefined {
236 if (instanceId !== undefined) {
237 const requested = entries.find((entry) => entry.instanceId === instanceId);
238 if (requested && isSelectableProviderInstanceEntry(requested)) {
239 return requested;
240 }
241 }
242 return (
243 entries.find(isProviderInstancePickerReady) ??
244 entries.find((entry) => isSelectableProviderInstanceEntry(entry) && entry.status !== "error")
245 );
246}
247
248export function resolveSelectableProviderInstance(
249 providers: ReadonlyArray<ServerProvider>,
250 instanceId: ProviderInstanceId | undefined,
251): ProviderInstanceId | undefined {
252 const entries = deriveProviderInstanceEntries(providers);
253 return resolveSelectableProviderInstanceEntry(entries, instanceId)?.instanceId;
254}
255
256export function resolveDefaultProviderModelSelection(
257 providers: ReadonlyArray<ServerProvider>,
258 selection: ModelSelection | null | undefined,
259): ModelSelection | null {
260 const instanceId = resolveSelectableProviderInstance(providers, selection?.instanceId);
261 if (instanceId === undefined) return null;
262 if (selection?.instanceId === instanceId) return selection;
263 const model = getDefaultProviderInstanceModel(providers, instanceId);
264 return model ? { instanceId, model } : null;
265}
266
267export function resolveProjectDefaultProviderModelSelection(
268 providers: ReadonlyArray<ServerProvider>,
269 settings: ServerSettings,
270 projectId: ProjectId | null,
271): ModelSelection | null {
272 const entries = providerInstanceEntriesFor(providers, settings, projectId);
273 // Matches resolveComposerProviderSelection: the first driver group wins before any other.
274 const entry =
275 resolveSelectableProviderInstanceEntry(
276 entries.filter((candidate) => candidate.driverKind === entries[0]?.driverKind),
277 undefined,
278 ) ?? resolveSelectableProviderInstanceEntry(entries, undefined);
279 const model = entry ? getDefaultProviderInstanceModel(providers, entry.instanceId) : undefined;
280 return entry && model ? { instanceId: entry.instanceId, model } : null;
281}