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/** Disabled instances may retain ready status until reconciliation. */
52export function isProviderInstancePickerReady(entry: ProviderInstanceEntry): boolean {
53 return entry.enabled && entry.isAvailable && entry.status === "ready";
54}
55
56export function isProviderInstancePickerVisible(entry: ProviderInstanceEntry): boolean {
57 return entry.enabled;
58}
59
60export function deriveProviderInstanceEntries(
61 providers: ReadonlyArray<ServerProvider>,
62): ReadonlyArray<ProviderInstanceEntry> {
63 return providers.map((snapshot) => {
64 const instanceId = snapshot.instanceId;
65 const driverKind = snapshot.driver;
66 const defaultId = defaultInstanceIdForDriver(driverKind);
67 const isDefault = instanceId === defaultId;
68 return {
69 instanceId,
70 driverKind,
71 displayName: resolveProviderInstanceDisplayName(snapshot),
72 accentColor: normalizeProviderAccentColor(snapshot.accentColor),
73 ...(driverKind === "acpRegistry" && snapshot.iconUrl
74 ? { acpRegistryIconUrl: snapshot.iconUrl }
75 : {}),
76 continuationGroupKey: snapshot.continuation?.groupKey,
77 enabled: snapshot.enabled,
78 installed: snapshot.installed,
79 status: snapshot.status,
80 isDefault,
81 isAvailable: snapshot.availability !== "unavailable",
82 snapshot,
83 models: snapshot.models,
84 } satisfies ProviderInstanceEntry;
85 });
86}
87
88/** Instance ids repeat across environments; lookups must stay scoped. */
89export function deriveProviderEntriesByEnvironment(
90 providersByEnvironment: Iterable<
91 readonly [
92 string,
93 ReadonlyArray<ServerProvider>,
94 Pick<ServerSettings, "providerInstances" | "projectSettingsOverrides">?,
95 ]
96 >,
97): ReadonlyMap<string, ReadonlyMap<string, ProviderInstanceEntry>> {
98 const byEnvironment = new Map<string, ReadonlyMap<string, ProviderInstanceEntry>>();
99 for (const [environmentId, providers, settings] of providersByEnvironment) {
100 const derived = deriveProviderInstanceEntries(providers);
101 const entries = settings ? brandProviderInstanceEntries(derived, settings) : derived;
102 byEnvironment.set(
103 environmentId,
104 new Map(entries.map((entry) => [entry.instanceId as string, entry] as const)),
105 );
106 }
107 return byEnvironment;
108}
109
110// The snapshot includes instances enabled by any project; machine settings alone do not.
111export function brandProviderInstanceEntries(
112 entries: ReadonlyArray<ProviderInstanceEntry>,
113 settings: Pick<ServerSettings, "providerInstances">,
114): ReadonlyArray<ProviderInstanceEntry> {
115 return entries.map((entry) => applyProviderInstanceBranding(entry, settings));
116}
117
118/** projectId applies project overrides; explicit null uses machine settings. */
119export function applyProviderInstanceSettings(
120 entries: ReadonlyArray<ProviderInstanceEntry>,
121 settings: Pick<ServerSettings, "providerInstances" | "projectSettingsOverrides">,
122 projectId: ProjectId | null,
123): ReadonlyArray<ProviderInstanceEntry> {
124 return entries.map((entry) => {
125 const enabled = resolveProjectProviderInstanceEnabled(settings, projectId, entry.instanceId);
126 return applyProviderInstanceBranding(
127 enabled === entry.enabled ? entry : { ...entry, enabled },
128 settings,
129 );
130 });
131}
132
133function applyProviderInstanceBranding(
134 entry: ProviderInstanceEntry,
135 settings: Pick<ServerSettings, "providerInstances">,
136): ProviderInstanceEntry {
137 const explicitInstance = Object.hasOwn(settings.providerInstances, entry.instanceId)
138 ? settings.providerInstances[entry.instanceId]
139 : undefined;
140 if (entry.driverKind !== "acpRegistry" || explicitInstance === undefined) return entry;
141 const config =
142 explicitInstance.config !== null && typeof explicitInstance.config === "object"
143 ? (explicitInstance.config as Readonly<Record<string, unknown>>)
144 : null;
145 if (config?.source === "local") {
146 return { ...entry, acpRegistryAgentId: undefined, acpRegistryIconUrl: undefined };
147 }
148 const agentId = config?.agentId;
149 const iconUrl = config?.registryIconUrl;
150 return {
151 ...entry,
152 ...(typeof agentId === "string" && agentId.trim()
153 ? { acpRegistryAgentId: agentId.trim() }
154 : {}),
155 ...(typeof iconUrl === "string" && iconUrl.trim()
156 ? { acpRegistryIconUrl: iconUrl.trim() }
157 : {}),
158 };
159}
160
161/** Picker order: each driver's default instance first, then its custom instances. */
162export function providerInstanceEntriesFor(
163 providers: ReadonlyArray<ServerProvider>,
164 settings: Pick<ServerSettings, "providerInstances" | "projectSettingsOverrides">,
165 projectId: ProjectId | null,
166): ReadonlyArray<ProviderInstanceEntry> {
167 return pipe(
168 deriveProviderInstanceEntries(providers),
169 (entries) => applyProviderInstanceSettings(entries, settings, projectId),
170 sortProviderInstanceEntries,
171 );
172}
173
174function sortProviderInstanceEntries(
175 entries: ReadonlyArray<ProviderInstanceEntry>,
176): ReadonlyArray<ProviderInstanceEntry> {
177 const byKind = new Map<ProviderDriverKind, ProviderInstanceEntry[]>();
178 for (const entry of entries) {
179 const bucket = byKind.get(entry.driverKind);
180 if (bucket) {
181 bucket.push(entry);
182 } else {
183 byKind.set(entry.driverKind, [entry]);
184 }
185 }
186 const sorted: ProviderInstanceEntry[] = [];
187 for (const bucket of byKind.values()) {
188 const defaults = bucket.filter((entry) => entry.isDefault);
189 const customs = bucket.filter((entry) => !entry.isDefault);
190 sorted.push(...defaults, ...customs);
191 }
192 return sorted;
193}
194
195function getProviderInstanceEntry(
196 providers: ReadonlyArray<ServerProvider>,
197 instanceId: ProviderInstanceId,
198): ProviderInstanceEntry | undefined {
199 return deriveProviderInstanceEntries(providers).find((entry) => entry.instanceId === instanceId);
200}
201
202export function getDefaultProviderInstanceModel(
203 providers: ReadonlyArray<ServerProvider>,
204 instanceId: ProviderInstanceId,
205): string | undefined {
206 const entry = getProviderInstanceEntry(providers, instanceId);
207 if (!entry) return undefined;
208 return (
209 entry.models.find((model) => model.isDefault && !model.isCustom)?.slug ??
210 entry.models.find((model) => !model.isCustom)?.slug ??
211 entry.models[0]?.slug ??
212 DEFAULT_MODEL_BY_PROVIDER[entry.driverKind]
213 );
214}
215
216const isSelectableProviderInstanceEntry = (entry: ProviderInstanceEntry): boolean =>
217 entry.enabled && entry.isAvailable;
218
219export function resolveSelectableProviderInstanceEntry(
220 entries: ReadonlyArray<ProviderInstanceEntry>,
221 instanceId: ProviderInstanceId | undefined,
222): ProviderInstanceEntry | undefined {
223 if (instanceId !== undefined) {
224 const requested = entries.find((entry) => entry.instanceId === instanceId);
225 if (requested && isSelectableProviderInstanceEntry(requested)) {
226 return requested;
227 }
228 }
229 return (
230 entries.find(isProviderInstancePickerReady) ??
231 entries.find((entry) => isSelectableProviderInstanceEntry(entry) && entry.status !== "error")
232 );
233}
234
235export function resolveSelectableProviderInstance(
236 providers: ReadonlyArray<ServerProvider>,
237 instanceId: ProviderInstanceId | undefined,
238): ProviderInstanceId | undefined {
239 const entries = deriveProviderInstanceEntries(providers);
240 return resolveSelectableProviderInstanceEntry(entries, instanceId)?.instanceId;
241}
242
243export function resolveDefaultProviderModelSelection(
244 providers: ReadonlyArray<ServerProvider>,
245 selection: ModelSelection | null | undefined,
246): ModelSelection | null {
247 const instanceId = resolveSelectableProviderInstance(providers, selection?.instanceId);
248 if (instanceId === undefined) return null;
249 if (selection?.instanceId === instanceId) return selection;
250 const model = getDefaultProviderInstanceModel(providers, instanceId);
251 return model ? { instanceId, model } : null;
252}
253
254export function resolveProjectDefaultProviderModelSelection(
255 providers: ReadonlyArray<ServerProvider>,
256 settings: ServerSettings,
257 projectId: ProjectId | null,
258): ModelSelection | null {
259 const entries = providerInstanceEntriesFor(providers, settings, projectId);
260 // Matches resolveComposerProviderSelection: the first driver group wins before any other.
261 const entry =
262 resolveSelectableProviderInstanceEntry(
263 entries.filter((candidate) => candidate.driverKind === entries[0]?.driverKind),
264 undefined,
265 ) ?? resolveSelectableProviderInstanceEntry(entries, undefined);
266 const model = entry ? getDefaultProviderInstanceModel(providers, entry.instanceId) : undefined;
267 return entry && model ? { instanceId: entry.instanceId, model } : null;
268}