Open History to see the last commit
1import {
2 isProviderDriverKind,
3 isProviderAvailable,
4 resolveProviderInstanceEnabled,
5 type ModelSelection,
6 type ProviderDriverKind,
7 type ServerProvider,
8 ServerSettings,
9 type ServerSettingsPatch,
10} from "@t3tools/contracts";
11import * as Option from "effect/Option";
12import * as Schema from "effect/Schema";
13import { deepMerge } from "./Struct.ts";
14import { fromLenientJson } from "./schemaJson.ts";
15import { createModelSelection } from "./model.ts";
16import {
17 getBackgroundActivityBaseProfile,
18 normalizeBackgroundActivitySettings,
19 normalizeServerBackgroundActivitySettings,
20 resolveBackgroundActivitySettings,
21} from "./backgroundActivitySettings.ts";
22
23const ServerSettingsJson = fromLenientJson(ServerSettings);
24const decodeServerSettingsJson = Schema.decodeUnknownOption(ServerSettingsJson);
25
26type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];
27
28const getLegacyProviderSettings = (
29 settings: ServerSettings,
30 provider: ProviderDriverKind,
31): LegacyProviderSettings | undefined =>
32 (settings.providers as Record<string, LegacyProviderSettings | undefined>)[provider];
33
34export function isModelSelectionProviderEnabled(
35 settings: ServerSettings,
36 selection: ModelSelection,
37): boolean {
38 const instanceConfig = settings.providerInstances[selection.instanceId];
39 if (instanceConfig !== undefined) {
40 return resolveProviderInstanceEnabled(instanceConfig);
41 }
42
43 return (
44 isProviderDriverKind(selection.instanceId) &&
45 getLegacyProviderSettings(settings, selection.instanceId)?.enabled === true
46 );
47}
48
49export function resolveSourceControlWriterModelSelection(
50 settings: ServerSettings,
51 providers?: ReadonlyArray<ServerProvider>,
52): ModelSelection {
53 const selection = settings.sourceControlWriterModelSelection;
54 if (!selection || !isModelSelectionProviderEnabled(settings, selection)) {
55 return settings.textGenerationModelSelection;
56 }
57 if (providers === undefined) {
58 return selection;
59 }
60
61 const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId);
62 return provider?.enabled === true && isProviderAvailable(provider)
63 ? selection
64 : settings.textGenerationModelSelection;
65}
66
67export interface PersistedServerObservabilitySettings {
68 readonly otlpTracesUrl: string | undefined;
69 readonly otlpMetricsUrl: string | undefined;
70}
71
72export function normalizePersistedServerSettingString(
73 value: string | null | undefined,
74): string | undefined {
75 const trimmed = value?.trim();
76 return trimmed && trimmed.length > 0 ? trimmed : undefined;
77}
78
79export function extractPersistedServerObservabilitySettings(input: {
80 readonly observability?: {
81 readonly otlpTracesUrl?: string;
82 readonly otlpMetricsUrl?: string;
83 };
84}): PersistedServerObservabilitySettings {
85 return {
86 otlpTracesUrl: normalizePersistedServerSettingString(input.observability?.otlpTracesUrl),
87 otlpMetricsUrl: normalizePersistedServerSettingString(input.observability?.otlpMetricsUrl),
88 };
89}
90
91export function parsePersistedServerObservabilitySettings(
92 raw: string,
93): PersistedServerObservabilitySettings {
94 const decoded = decodeServerSettingsJson(raw);
95 if (Option.isSome(decoded)) {
96 return extractPersistedServerObservabilitySettings(decoded.value);
97 }
98 return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
99}
100
101function shouldReplaceTextGenerationModelSelection(
102 patch: ServerSettingsPatch["textGenerationModelSelection"] | undefined,
103): boolean {
104 return Boolean(patch && (patch.instanceId !== undefined || patch.model !== undefined));
105}
106
107function mergeModelSelectionOptionsById(input: {
108 current: ReadonlyArray<{ readonly id: string; readonly value: string | boolean }> | undefined;
109 patch: ReadonlyArray<{ readonly id: string; readonly value: string | boolean }> | undefined;
110}): Array<{ id: string; value: string | boolean }> | undefined {
111 if (input.patch === undefined) {
112 return input.current ? [...input.current] : undefined;
113 }
114 if (input.patch.length === 0) {
115 return undefined;
116 }
117
118 const merged = new Map((input.current ?? []).map((selection) => [selection.id, selection.value]));
119 for (const selection of input.patch) {
120 merged.set(selection.id, selection.value);
121 }
122 return [...merged.entries()].map(([id, value]) => ({ id, value }));
123}
124
125/** Upsert each patched entry; `null` removes it. Entries the patch omits are untouched. */
126function mergeUsageLimitSources(
127 current: ServerSettings["usageLimitSources"],
128 patch: NonNullable<ServerSettingsPatch["usageLimitSources"]>,
129): ServerSettings["usageLimitSources"] {
130 const next = new Map(Object.entries(current));
131 for (const [id, config] of Object.entries(patch)) {
132 if (config === null) {
133 next.delete(id);
134 } else {
135 next.set(id, config);
136 }
137 }
138 return Object.fromEntries(next) as ServerSettings["usageLimitSources"];
139}
140
141export function applyServerSettingsPatch(
142 current: ServerSettings,
143 patch: ServerSettingsPatch,
144): ServerSettings {
145 const selectionPatch = patch.textGenerationModelSelection;
146 const {
147 automaticGitFetchInterval,
148 providerHealthRefreshInterval,
149 backgroundActivityProfile,
150 backgroundActivity,
151 // Merged per entry below; its `null` removals must not reach deepMerge.
152 usageLimitSources: usageLimitSourcesPatch,
153 ...patchForMerge
154 } = patch;
155 const currentBackgroundActivity = normalizeServerBackgroundActivitySettings(current);
156 const backgroundActivityPatch =
157 backgroundActivityProfile !== undefined
158 ? {
159 schemaVersion: 1 as const,
160 profile:
161 automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
162 ? ("custom" as const)
163 : backgroundActivityProfile,
164 ...(automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
165 ? { baseProfile: backgroundActivityProfile }
166 : {}),
167 overrides: {
168 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
169 ...(providerHealthRefreshInterval !== undefined
170 ? { providerHealthRefreshInterval }
171 : {}),
172 },
173 }
174 : automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
175 ? {
176 schemaVersion: 1 as const,
177 profile: "custom" as const,
178 baseProfile: getBackgroundActivityBaseProfile(currentBackgroundActivity),
179 overrides: {
180 ...(currentBackgroundActivity.profile === "custom"
181 ? currentBackgroundActivity.overrides
182 : {}),
183 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
184 ...(providerHealthRefreshInterval !== undefined
185 ? { providerHealthRefreshInterval }
186 : {}),
187 },
188 }
189 : undefined;
190 const next = deepMerge(current, patchForMerge);
191 const nextWithReplacementsBase = {
192 ...next,
193 ...(backgroundActivity !== undefined
194 ? {
195 backgroundActivity: {
196 ...deepMerge(currentBackgroundActivity, backgroundActivity),
197 ...(backgroundActivity.overrides !== undefined
198 ? { overrides: backgroundActivity.overrides }
199 : {}),
200 },
201 }
202 : { backgroundActivity: currentBackgroundActivity }),
203 ...(backgroundActivity === undefined && backgroundActivityPatch !== undefined
204 ? { backgroundActivity: backgroundActivityPatch }
205 : {}),
206 ...(patch.providerInstances !== undefined
207 ? { providerInstances: patch.providerInstances }
208 : {}),
209 ...(usageLimitSourcesPatch !== undefined
210 ? {
211 usageLimitSources: mergeUsageLimitSources(
212 current.usageLimitSources,
213 usageLimitSourcesPatch,
214 ),
215 }
216 : {}),
217 ...(patch.sourceControlWriterModelSelection !== undefined
218 ? { sourceControlWriterModelSelection: patch.sourceControlWriterModelSelection }
219 : {}),
220 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
221 ...(providerHealthRefreshInterval !== undefined ? { providerHealthRefreshInterval } : {}),
222 };
223 const normalizedBackgroundActivity = normalizeBackgroundActivitySettings(
224 nextWithReplacementsBase.backgroundActivity,
225 );
226 const resolvedBackgroundActivity = resolveBackgroundActivitySettings(
227 normalizedBackgroundActivity,
228 );
229 const nextWithReplacements = {
230 ...nextWithReplacementsBase,
231 backgroundActivity: normalizedBackgroundActivity,
232 automaticGitFetchInterval: resolvedBackgroundActivity.automaticGitFetchInterval,
233 providerHealthRefreshInterval: resolvedBackgroundActivity.providerHealthRefreshInterval,
234 backgroundActivityProfile: resolvedBackgroundActivity.profile,
235 };
236 if (!selectionPatch) {
237 return nextWithReplacements;
238 }
239
240 const instanceId = selectionPatch.instanceId ?? current.textGenerationModelSelection.instanceId;
241 const model = selectionPatch.model ?? current.textGenerationModelSelection.model;
242 const options = shouldReplaceTextGenerationModelSelection(selectionPatch)
243 ? selectionPatch.options
244 : mergeModelSelectionOptionsById({
245 current: current.textGenerationModelSelection.options,
246 patch: selectionPatch.options,
247 });
248
249 return {
250 ...nextWithReplacements,
251 textGenerationModelSelection: createModelSelection(instanceId, model, options),
252 };
253}