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

providerInstances.ts

258 lines9.5 KB

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