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/** Placeholder for untargetable drafts. Never persist or dispatch it; disable send until replaced. */
23export const NO_PROVIDER_MODEL_SELECTION: ModelSelection = {
24 instanceId: ProviderInstanceId.make("t3code_no_provider"),
25 model: "",
26};
27
28export interface ProviderInstanceEntry {
29 readonly instanceId: ProviderInstanceId;
30 readonly driverKind: ProviderDriverKind;
31 readonly displayName: string;
32 readonly accentColor?: string | undefined;
33 readonly acpRegistryAgentId?: string | undefined;
34 readonly acpRegistryIconUrl?: string | undefined;
35 readonly continuationGroupKey?: string | undefined;
36 readonly enabled: boolean;
37 readonly installed: boolean;
38 readonly status: ServerProviderState;
39 readonly isDefault: boolean;
40 readonly isAvailable: boolean;
41 readonly snapshot: ServerProvider;
42 readonly models: ReadonlyArray<ServerProviderModel>;
43}
44
45export type ProviderCatalogAvailability = "loading" | "ready" | "unavailable" | "unconfigured";
46
47/** Initial null config is still loading; treating it as empty would strand recoverable threads. */
48export function resolveProviderCatalogAvailability(input: {
49 readonly catalogLoaded: boolean;
50 readonly entries: ReadonlyArray<ProviderInstanceEntry>;
51 readonly selectedEntry: ProviderInstanceEntry | undefined;
52}): ProviderCatalogAvailability {
53 if (!input.catalogLoaded) return "loading";
54 if (input.selectedEntry !== undefined) return "ready";
55 return input.entries.length === 0 ? "unconfigured" : "unavailable";
56}
57
58/** Disabled instances may retain ready status until reconciliation. */
59export function isProviderInstancePickerReady(entry: ProviderInstanceEntry): boolean {
60 return entry.enabled && entry.isAvailable && entry.status === "ready";
61}
62
63export function isProviderInstancePickerVisible(entry: ProviderInstanceEntry): boolean {
64 return entry.enabled;
65}
66
67export function deriveProviderInstanceEntries(
68 providers: ReadonlyArray<ServerProvider>,
69): ReadonlyArray<ProviderInstanceEntry> {
70 return providers.map((snapshot) => {
71 const instanceId = snapshot.instanceId;
72 const driverKind = snapshot.driver;
73 const defaultId = defaultInstanceIdForDriver(driverKind);
74 const isDefault = instanceId === defaultId;
75 return {
76 instanceId,
77 driverKind,
78 displayName: resolveProviderInstanceDisplayName(snapshot),
79 accentColor: normalizeProviderAccentColor(snapshot.accentColor),
80 ...(driverKind === "acpRegistry" && snapshot.iconUrl
81 ? { acpRegistryIconUrl: snapshot.iconUrl }
82 : {}),
83 continuationGroupKey: snapshot.continuation?.groupKey,
84 enabled: snapshot.enabled,
85 installed: snapshot.installed,
86 status: snapshot.status,
87 isDefault,
88 isAvailable: snapshot.availability !== "unavailable",
89 snapshot,
90 models: snapshot.models,
91 } satisfies ProviderInstanceEntry;
92 });
93}
94
95/** Instance ids repeat across environments; lookups must stay scoped. */
96export function deriveProviderEntriesByEnvironment(
97 providersByEnvironment: Iterable<
98 readonly [
99 string,
100 ReadonlyArray<ServerProvider>,
101 Pick<ServerSettings, "providerInstances" | "projectSettingsOverrides">?,
102 ]
103 >,
104): ReadonlyMap<string, ReadonlyMap<string, ProviderInstanceEntry>> {
105 const byEnvironment = new Map<string, ReadonlyMap<string, ProviderInstanceEntry>>();
106 for (const [environmentId, providers, settings] of providersByEnvironment) {
107 const derived = deriveProviderInstanceEntries(providers);
108 // The snapshot includes instances enabled by any project; machine settings alone do not.
109 const entries = settings
110 ? derived.map((entry) => applyProviderInstanceBranding(entry, settings))
111 : derived;
112 byEnvironment.set(
113 environmentId,
114 new Map(entries.map((entry) => [entry.instanceId as string, entry] as const)),
115 );
116 }
117 return byEnvironment;
118}
119
120/** projectId applies project overrides; explicit null uses machine settings. */
121export function applyProviderInstanceSettings(
122 entries: ReadonlyArray<ProviderInstanceEntry>,
123 settings: Pick<ServerSettings, "providerInstances" | "projectSettingsOverrides">,
124 projectId: ProjectId | null,
125): ReadonlyArray<ProviderInstanceEntry> {
126 return entries.map((entry) => {
127 const enabled = resolveProjectProviderInstanceEnabled(settings, projectId, entry.instanceId);
128 return applyProviderInstanceBranding(
129 enabled === entry.enabled ? entry : { ...entry, enabled },
130 settings,
131 );
132 });
133}
134
135function applyProviderInstanceBranding(
136 entry: ProviderInstanceEntry,
137 settings: Pick<ServerSettings, "providerInstances">,
138): ProviderInstanceEntry {
139 const explicitInstance = Object.hasOwn(settings.providerInstances, entry.instanceId)
140 ? settings.providerInstances[entry.instanceId]
141 : undefined;
142 if (entry.driverKind !== "acpRegistry" || explicitInstance === undefined) return entry;
143 const config =
144 explicitInstance.config !== null && typeof explicitInstance.config === "object"
145 ? (explicitInstance.config as Readonly<Record<string, unknown>>)
146 : null;
147 if (config?.source === "local") {
148 return { ...entry, acpRegistryAgentId: undefined, acpRegistryIconUrl: undefined };
149 }
150 const agentId = config?.agentId;
151 const iconUrl = config?.registryIconUrl;
152 return {
153 ...entry,
154 ...(typeof agentId === "string" && agentId.trim()
155 ? { acpRegistryAgentId: agentId.trim() }
156 : {}),
157 ...(typeof iconUrl === "string" && iconUrl.trim()
158 ? { acpRegistryIconUrl: iconUrl.trim() }
159 : {}),
160 };
161}
162
163export function sortProviderInstanceEntries(
164 entries: ReadonlyArray<ProviderInstanceEntry>,
165): ReadonlyArray<ProviderInstanceEntry> {
166 const byKind = new Map<ProviderDriverKind, ProviderInstanceEntry[]>();
167 for (const entry of entries) {
168 const bucket = byKind.get(entry.driverKind);
169 if (bucket) {
170 bucket.push(entry);
171 } else {
172 byKind.set(entry.driverKind, [entry]);
173 }
174 }
175 const sorted: ProviderInstanceEntry[] = [];
176 for (const bucket of byKind.values()) {
177 const defaults = bucket.filter((entry) => entry.isDefault);
178 const customs = bucket.filter((entry) => !entry.isDefault);
179 sorted.push(...defaults, ...customs);
180 }
181 return sorted;
182}
183
184function getProviderInstanceEntry(
185 providers: ReadonlyArray<ServerProvider>,
186 instanceId: ProviderInstanceId,
187): ProviderInstanceEntry | undefined {
188 return deriveProviderInstanceEntries(providers).find((entry) => entry.instanceId === instanceId);
189}
190
191export function getDefaultProviderInstanceModel(
192 providers: ReadonlyArray<ServerProvider>,
193 instanceId: ProviderInstanceId,
194): string | undefined {
195 const entry = getProviderInstanceEntry(providers, instanceId);
196 if (!entry) return undefined;
197 return (
198 entry.models.find((model) => model.isDefault && !model.isCustom)?.slug ??
199 entry.models.find((model) => !model.isCustom)?.slug ??
200 entry.models[0]?.slug ??
201 DEFAULT_MODEL_BY_PROVIDER[entry.driverKind]
202 );
203}
204
205const isSelectableProviderInstanceEntry = (entry: ProviderInstanceEntry): boolean =>
206 entry.enabled && entry.isAvailable;
207
208export function resolveSelectableProviderInstanceEntry(
209 entries: ReadonlyArray<ProviderInstanceEntry>,
210 instanceId: ProviderInstanceId | undefined,
211): ProviderInstanceEntry | undefined {
212 if (instanceId !== undefined) {
213 const requested = entries.find((entry) => entry.instanceId === instanceId);
214 if (requested && isSelectableProviderInstanceEntry(requested)) {
215 return requested;
216 }
217 }
218 return (
219 entries.find(isProviderInstancePickerReady) ??
220 entries.find((entry) => isSelectableProviderInstanceEntry(entry) && entry.status !== "error")
221 );
222}
223
224export function resolveSelectableProviderInstance(
225 providers: ReadonlyArray<ServerProvider>,
226 instanceId: ProviderInstanceId | undefined,
227): ProviderInstanceId | undefined {
228 const entries = deriveProviderInstanceEntries(providers);
229 return resolveSelectableProviderInstanceEntry(entries, instanceId)?.instanceId;
230}
231
232export function resolveDefaultProviderModelSelection(
233 providers: ReadonlyArray<ServerProvider>,
234 selection: ModelSelection | null | undefined,
235): ModelSelection | null {
236 const instanceId = resolveSelectableProviderInstance(providers, selection?.instanceId);
237 if (instanceId === undefined) return null;
238 if (selection?.instanceId === instanceId) return selection;
239 const model = getDefaultProviderInstanceModel(providers, instanceId);
240 return model ? { instanceId, model } : null;
241}