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

providerInstances.ts

255 lines9.6 KB

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>;
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";
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";
73​
74export function isProviderInstancePickerVisible(entry: ProviderInstanceEntry): boolean {
75 return entry.enabled;
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 });
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 // One map per environment serves every project with a thread there, so
125 // there is no single project to scope `enabled` to; it stays machine-wide.
126 const entries = settings ? applyProviderInstanceSettings(derived, settings, null) : derived;
127 byEnvironment.set(
128 environmentId,
129 new Map(entries.map((entry) => [entry.instanceId as string, entry] as const)),
130 );
131 }
132 return byEnvironment;
134​
135/**
136 * `projectId` folds in that project's `providerInstances[id].enabled` override (enable or
137 * disable in either direction over the machine value); `null` resolves the machine value only.
138 * It has no default: a caller that renders for a single project but forgets to pass it would
139 * silently show the machine's enablement instead of that project's, so passing `null` for a
140 * surface that isn't project-aware must be a deliberate choice, not an omission.
141 */
142export function applyProviderInstanceSettings(
143 entries: ReadonlyArray<ProviderInstanceEntry>,
144 settings: Pick<ServerSettings, "providerInstances" | "projectSettingsOverrides">,
145 projectId: ProjectId | null,
146): ReadonlyArray<ProviderInstanceEntry> {
147 return entries.map((entry) => {
148 const explicitInstance = Object.hasOwn(settings.providerInstances, entry.instanceId)
149 ? settings.providerInstances[entry.instanceId]
150 : undefined;
151 const enabled = resolveProjectProviderInstanceEnabled(settings, projectId, entry.instanceId);
152 if (entry.driverKind !== "acpRegistry" || explicitInstance === undefined) {
153 return enabled === entry.enabled ? entry : { ...entry, enabled };
154 }
155 const config =
156 explicitInstance.config !== null && typeof explicitInstance.config === "object"
157 ? (explicitInstance.config as Readonly<Record<string, unknown>>)
158 : null;
159 if (config?.source === "local") {
160 return { ...entry, enabled, acpRegistryAgentId: undefined, acpRegistryIconUrl: undefined };
161 }
162 const agentId = config?.agentId;
163 const iconUrl = config?.registryIconUrl;
164 return {
165 ...entry,
166 enabled,
167 ...(typeof agentId === "string" && agentId.trim()
168 ? { acpRegistryAgentId: agentId.trim() }
169 : {}),
170 ...(typeof iconUrl === "string" && iconUrl.trim()
171 ? { acpRegistryIconUrl: iconUrl.trim() }
172 : {}),
173 };
174 });
176​
177export function sortProviderInstanceEntries(
178 entries: ReadonlyArray<ProviderInstanceEntry>,
179): ReadonlyArray<ProviderInstanceEntry> {
180 const byKind = new Map<ProviderDriverKind, ProviderInstanceEntry[]>();
181 for (const entry of entries) {
182 const bucket = byKind.get(entry.driverKind);
183 if (bucket) {
184 bucket.push(entry);
185 } else {
186 byKind.set(entry.driverKind, [entry]);
187 }
188 }
189 const sorted: ProviderInstanceEntry[] = [];
190 for (const bucket of byKind.values()) {
191 const defaults = bucket.filter((entry) => entry.isDefault);
192 const customs = bucket.filter((entry) => !entry.isDefault);
193 sorted.push(...defaults, ...customs);
194 }
195 return sorted;
197​
198export function getProviderInstanceEntry(
199 providers: ReadonlyArray<ServerProvider>,
200 instanceId: ProviderInstanceId,
201): ProviderInstanceEntry | undefined {
202 return deriveProviderInstanceEntries(providers).find((entry) => entry.instanceId === instanceId);
204​
205export function getDefaultProviderInstanceModel(
206 providers: ReadonlyArray<ServerProvider>,
207 instanceId: ProviderInstanceId,
208): string | undefined {
209 const entry = getProviderInstanceEntry(providers, instanceId);
210 if (!entry) return undefined;
211 return (
212 entry.models.find((model) => model.isDefault && !model.isCustom)?.slug ??
213 entry.models.find((model) => !model.isCustom)?.slug ??
214 entry.models[0]?.slug ??
215 DEFAULT_MODEL_BY_PROVIDER[entry.driverKind]
216 );
218​
219const isSelectableProviderInstanceEntry = (entry: ProviderInstanceEntry): boolean =>
220 entry.enabled && entry.isAvailable;
221​
222export function resolveSelectableProviderInstanceEntry(
223 entries: ReadonlyArray<ProviderInstanceEntry>,
224 instanceId: ProviderInstanceId | undefined,
225): ProviderInstanceEntry | undefined {
226 if (instanceId !== undefined) {
227 const requested = entries.find((entry) => entry.instanceId === instanceId);
228 if (requested && isSelectableProviderInstanceEntry(requested)) {
229 return requested;
230 }
231 }
232 return (
233 entries.find(isProviderInstancePickerReady) ??
234 entries.find((entry) => isSelectableProviderInstanceEntry(entry) && entry.status !== "error")
235 );
237​
238export function resolveSelectableProviderInstance(
239 providers: ReadonlyArray<ServerProvider>,
240 instanceId: ProviderInstanceId | undefined,
241): ProviderInstanceId | undefined {
242 const entries = deriveProviderInstanceEntries(providers);
243 return resolveSelectableProviderInstanceEntry(entries, instanceId)?.instanceId;
245​
246export function resolveDefaultProviderModelSelection(
247 providers: ReadonlyArray<ServerProvider>,
248 selection: ModelSelection | null | undefined,
249): ModelSelection | null {
250 const instanceId = resolveSelectableProviderInstance(providers, selection?.instanceId);
251 if (instanceId === undefined) return null;
252 if (selection?.instanceId === instanceId) return selection;
253 const model = getDefaultProviderInstanceModel(providers, instanceId);
254 return model ? { instanceId, model } : null;