Open History to see the last commit
1import {
2 isProviderDriverKind,
3 isProviderAvailable,
4 resolveProviderInstanceEnabled,
5 isProviderTextGenerationCapable,
6 type ModelSelection,
7 type ProjectId,
8 type ProjectScopedServerSettingKey,
9 type ProjectSettingsOverrides,
10 type ProviderDriverKind,
11 type ServerProvider,
12 ServerSettings,
13 type ServerSettingsPatch,
14} from "@t3tools/contracts";
15import * as Option from "effect/Option";
16import * as Schema from "effect/Schema";
17import { deepMerge } from "./Struct.ts";
18import { fromLenientJson } from "./schemaJson.ts";
19import { createModelSelection } from "./model.ts";
20import {
21 getBackgroundActivityBaseProfile,
22 normalizeBackgroundActivitySettings,
23 normalizeServerBackgroundActivitySettings,
24 resolveBackgroundActivitySettings,
25} from "./backgroundActivitySettings.ts";
26
27const ServerSettingsJson = fromLenientJson(ServerSettings);
28const decodeServerSettingsJson = Schema.decodeUnknownOption(ServerSettingsJson);
29
30/** @deprecated Read `resolveProjectSettings(...).settings.enableAgentBrowserAccess`. */
31export function resolveProjectAgentBrowserAccess(
32 settings: Pick<
33 ServerSettings,
34 "enableAgentBrowserAccess" | "projectAgentBrowserAccessOverrides" | "projectSettingsOverrides"
35 >,
36 projectId: ProjectId,
37): boolean {
38 return (
39 settings.projectSettingsOverrides[projectId]?.enableAgentBrowserAccess ??
40 settings.projectAgentBrowserAccessOverrides[projectId] ??
41 settings.enableAgentBrowserAccess
42 );
43}
44
45/** @deprecated Read `resolveProjectSettings(...).settings.defaultAutoPull`. */
46export function resolveProjectAutoPull(
47 settings: Pick<
48 ServerSettings,
49 "defaultAutoPull" | "projectAutoPullOverrides" | "projectSettingsOverrides"
50 >,
51 projectId: ProjectId,
52 legacyAutoPull: boolean | undefined,
53): boolean {
54 // Existing opt-ins stay enabled until explicitly overridden or reset.
55 return (
56 settings.projectSettingsOverrides[projectId]?.defaultAutoPull ??
57 settings.projectAutoPullOverrides[projectId] ??
58 (legacyAutoPull === true || settings.defaultAutoPull)
59 );
60}
61
62type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];
63
64const getLegacyProviderSettings = (
65 settings: ServerSettings,
66 provider: ProviderDriverKind,
67): LegacyProviderSettings | undefined =>
68 (settings.providers as Record<string, LegacyProviderSettings | undefined>)[provider];
69
70export function isModelSelectionProviderEnabled(
71 settings: ServerSettings,
72 selection: ModelSelection,
73): boolean {
74 const instanceConfig = settings.providerInstances[selection.instanceId];
75 if (instanceConfig !== undefined) {
76 return resolveProviderInstanceEnabled(instanceConfig);
77 }
78
79 return (
80 isProviderDriverKind(selection.instanceId) &&
81 getLegacyProviderSettings(settings, selection.instanceId)?.enabled === true
82 );
83}
84
85export function resolveSourceControlWriterModelSelection(
86 settings: ServerSettings,
87 providers?: ReadonlyArray<ServerProvider>,
88): ModelSelection {
89 const selection = settings.sourceControlWriterModelSelection;
90 if (!selection || !isModelSelectionProviderEnabled(settings, selection)) {
91 return settings.textGenerationModelSelection;
92 }
93 if (providers === undefined) {
94 return selection;
95 }
96
97 const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId);
98 return provider?.enabled === true &&
99 isProviderAvailable(provider) &&
100 isProviderTextGenerationCapable(provider)
101 ? selection
102 : settings.textGenerationModelSelection;
103}
104
105export interface PersistedServerObservabilitySettings {
106 readonly otlpTracesUrl: string | undefined;
107 readonly otlpMetricsUrl: string | undefined;
108}
109
110function normalizePersistedServerSettingString(
111 value: string | null | undefined,
112): string | undefined {
113 const trimmed = value?.trim();
114 return trimmed && trimmed.length > 0 ? trimmed : undefined;
115}
116
117function extractPersistedServerObservabilitySettings(input: {
118 readonly observability?: {
119 readonly otlpTracesUrl?: string;
120 readonly otlpMetricsUrl?: string;
121 };
122}): PersistedServerObservabilitySettings {
123 return {
124 otlpTracesUrl: normalizePersistedServerSettingString(input.observability?.otlpTracesUrl),
125 otlpMetricsUrl: normalizePersistedServerSettingString(input.observability?.otlpMetricsUrl),
126 };
127}
128
129export function parsePersistedServerObservabilitySettings(
130 raw: string,
131): PersistedServerObservabilitySettings {
132 const decoded = decodeServerSettingsJson(raw);
133 if (Option.isSome(decoded)) {
134 return extractPersistedServerObservabilitySettings(decoded.value);
135 }
136 return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
137}
138
139function shouldReplaceTextGenerationModelSelection(
140 patch: ServerSettingsPatch["textGenerationModelSelection"] | undefined,
141): boolean {
142 return Boolean(patch && (patch.instanceId !== undefined || patch.model !== undefined));
143}
144
145function mergeModelSelectionOptionsById(input: {
146 current: ReadonlyArray<{ readonly id: string; readonly value: string | boolean }> | undefined;
147 patch: ReadonlyArray<{ readonly id: string; readonly value: string | boolean }> | undefined;
148}): Array<{ id: string; value: string | boolean }> | undefined {
149 if (input.patch === undefined) {
150 return input.current ? [...input.current] : undefined;
151 }
152 if (input.patch.length === 0) {
153 return undefined;
154 }
155
156 const merged = new Map((input.current ?? []).map((selection) => [selection.id, selection.value]));
157 for (const selection of input.patch) {
158 merged.set(selection.id, selection.value);
159 }
160 return [...merged.entries()].map(([id, value]) => ({ id, value }));
161}
162
163/** Upsert each patched entry; `null` removes it. Entries the patch omits are untouched. */
164function mergeSettingsEntries<Value>(
165 current: Readonly<Record<string, Value>>,
166 patch: Readonly<Record<string, Value | null>>,
167): Record<string, Value> {
168 const next = new Map(Object.entries(current));
169 for (const [id, config] of Object.entries(patch)) {
170 if (config === null) {
171 next.delete(id);
172 } else {
173 next.set(id, config);
174 }
175 }
176 return Object.fromEntries(next);
177}
178
179/**
180 * Derived views of `projectSettingsOverrides` for clients that still read
181 * the legacy per-key maps. Recomputed on every patch and load so they
182 * cannot drift from the generic record.
183 */
184export function deriveLegacyProjectOverrides(
185 settings: Pick<ServerSettings, "projectSettingsOverrides">,
186): Pick<
187 ServerSettings,
188 "projectAgentBrowserAccessOverrides" | "projectAutoPullOverrides" | "projectScriptOverrides"
189> {
190 const projectAgentBrowserAccessOverrides: Record<string, boolean> = {};
191 const projectAutoPullOverrides: Record<string, boolean> = {};
192 const projectScriptOverrides: Record<string, ServerSettings["defaultProjectScripts"] | null> = {};
193 for (const [projectId, entry] of Object.entries(settings.projectSettingsOverrides)) {
194 if (entry.enableAgentBrowserAccess !== undefined) {
195 projectAgentBrowserAccessOverrides[projectId] = entry.enableAgentBrowserAccess;
196 }
197 if (entry.defaultAutoPull !== undefined) {
198 projectAutoPullOverrides[projectId] = entry.defaultAutoPull;
199 }
200 if (entry.defaultProjectScripts !== undefined) {
201 projectScriptOverrides[projectId] = entry.defaultProjectScripts;
202 }
203 }
204 return { projectAgentBrowserAccessOverrides, projectAutoPullOverrides, projectScriptOverrides };
205}
206
207/**
208 * Rewrite a patch that still uses the legacy per-key project maps into
209 * entries of `projectSettingsOverrides`, so older clients keep editing the
210 * values the server actually reads. `null` in a legacy map clears that one
211 * override.
212 */
213function translateLegacyProjectOverridePatch(
214 current: Pick<ServerSettings, "projectSettingsOverrides">,
215 patch: ServerSettingsPatch,
216): ServerSettingsPatch {
217 const {
218 projectAgentBrowserAccessOverrides,
219 projectAutoPullOverrides,
220 projectScriptOverrides,
221 ...rest
222 } = patch;
223 if (
224 projectAgentBrowserAccessOverrides === undefined &&
225 projectAutoPullOverrides === undefined &&
226 projectScriptOverrides === undefined
227 ) {
228 return patch;
229 }
230 const currentEntries: Readonly<Record<string, ProjectSettingsOverrides>> =
231 current.projectSettingsOverrides;
232 const entries = new Map<string, ProjectSettingsOverrides | null>(
233 Object.entries(rest.projectSettingsOverrides ?? {}),
234 );
235 // A canonical entry in the same patch is the newer representation; a legacy
236 // map must not resurrect a key that entry deliberately omits.
237 const canonicalProjectIds = new Set(Object.keys(rest.projectSettingsOverrides ?? {}));
238 const applyKey = <K extends ProjectScopedServerSettingKey>(
239 map: Readonly<Record<string, ProjectSettingsOverrides[K] | null>> | undefined,
240 key: K,
241 ) => {
242 if (map === undefined) return;
243 for (const [projectId, value] of Object.entries(map)) {
244 if (canonicalProjectIds.has(projectId)) continue;
245 const entry: ProjectSettingsOverrides = {
246 ...(entries.get(projectId) ?? currentEntries[projectId] ?? {}),
247 };
248 if (value === null || value === undefined) {
249 delete entry[key];
250 } else {
251 entry[key] = value;
252 }
253 entries.set(projectId, Object.keys(entry).length === 0 ? null : entry);
254 }
255 };
256 applyKey(projectAgentBrowserAccessOverrides, "enableAgentBrowserAccess");
257 applyKey(projectAutoPullOverrides, "defaultAutoPull");
258 applyKey(projectScriptOverrides, "defaultProjectScripts");
259 return {
260 ...rest,
261 projectSettingsOverrides: Object.fromEntries(entries),
262 } as ServerSettingsPatch;
263}
264
265export function applyServerSettingsPatch(
266 current: ServerSettings,
267 rawPatch: ServerSettingsPatch,
268): ServerSettings {
269 const patch = translateLegacyProjectOverridePatch(current, rawPatch);
270 const selectionPatch = patch.textGenerationModelSelection;
271 const {
272 automaticGitFetchInterval,
273 providerHealthRefreshInterval,
274 backgroundActivityProfile,
275 backgroundActivity,
276 // Merged per entry below; its `null` removals must not reach deepMerge.
277 usageLimitSources: usageLimitSourcesPatch,
278 usagePriceOverrides: usagePriceOverridesPatch,
279 // Entry replacement: deepMerge would keep keys the client meant to clear.
280 projectSettingsOverrides: projectSettingsOverridesPatch,
281 // Already translated into `projectSettingsOverrides` above; the legacy
282 // maps are derived views and must never be merged directly.
283 projectAgentBrowserAccessOverrides: _legacyBrowserAccess,
284 projectAutoPullOverrides: _legacyAutoPull,
285 projectScriptOverrides: _legacyScripts,
286 ...patchForMerge
287 } = patch;
288 const currentBackgroundActivity = normalizeServerBackgroundActivitySettings(current);
289 const backgroundActivityPatch =
290 backgroundActivityProfile !== undefined
291 ? {
292 schemaVersion: 1 as const,
293 profile:
294 automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
295 ? ("custom" as const)
296 : backgroundActivityProfile,
297 ...(automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
298 ? { baseProfile: backgroundActivityProfile }
299 : {}),
300 overrides: {
301 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
302 ...(providerHealthRefreshInterval !== undefined
303 ? { providerHealthRefreshInterval }
304 : {}),
305 },
306 }
307 : automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
308 ? {
309 schemaVersion: 1 as const,
310 profile: "custom" as const,
311 baseProfile: getBackgroundActivityBaseProfile(currentBackgroundActivity),
312 overrides: {
313 ...(currentBackgroundActivity.profile === "custom"
314 ? currentBackgroundActivity.overrides
315 : {}),
316 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
317 ...(providerHealthRefreshInterval !== undefined
318 ? { providerHealthRefreshInterval }
319 : {}),
320 },
321 }
322 : undefined;
323 const next = deepMerge(current, patchForMerge);
324 const nextWithReplacementsBase = {
325 ...next,
326 ...(backgroundActivity !== undefined
327 ? {
328 backgroundActivity: {
329 ...deepMerge(currentBackgroundActivity, backgroundActivity),
330 ...(backgroundActivity.overrides !== undefined
331 ? { overrides: backgroundActivity.overrides }
332 : {}),
333 },
334 }
335 : { backgroundActivity: currentBackgroundActivity }),
336 ...(backgroundActivity === undefined && backgroundActivityPatch !== undefined
337 ? { backgroundActivity: backgroundActivityPatch }
338 : {}),
339 ...(patch.providerInstances !== undefined
340 ? { providerInstances: patch.providerInstances }
341 : {}),
342 ...(projectSettingsOverridesPatch !== undefined
343 ? {
344 projectSettingsOverrides: Object.fromEntries(
345 Object.entries(
346 mergeSettingsEntries(current.projectSettingsOverrides, projectSettingsOverridesPatch),
347 ).filter(([, entry]) => Object.keys(entry).length > 0),
348 ),
349 }
350 : {}),
351 ...(patch.defaultModelSelection !== undefined
352 ? { defaultModelSelection: patch.defaultModelSelection }
353 : {}),
354 ...(patch.defaultProjectScripts !== undefined
355 ? { defaultProjectScripts: patch.defaultProjectScripts }
356 : {}),
357 ...(usageLimitSourcesPatch !== undefined
358 ? {
359 usageLimitSources: mergeSettingsEntries(
360 current.usageLimitSources,
361 usageLimitSourcesPatch,
362 ),
363 }
364 : {}),
365 ...(usagePriceOverridesPatch !== undefined
366 ? {
367 usagePriceOverrides: mergeSettingsEntries(
368 current.usagePriceOverrides,
369 usagePriceOverridesPatch,
370 ),
371 }
372 : {}),
373 ...(patch.sourceControlWriterModelSelection !== undefined
374 ? { sourceControlWriterModelSelection: patch.sourceControlWriterModelSelection }
375 : {}),
376 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
377 ...(providerHealthRefreshInterval !== undefined ? { providerHealthRefreshInterval } : {}),
378 };
379 const normalizedBackgroundActivity = normalizeBackgroundActivitySettings(
380 nextWithReplacementsBase.backgroundActivity,
381 );
382 const resolvedBackgroundActivity = resolveBackgroundActivitySettings(
383 normalizedBackgroundActivity,
384 );
385 const nextWithReplacements = {
386 ...nextWithReplacementsBase,
387 ...deriveLegacyProjectOverrides(nextWithReplacementsBase),
388 backgroundActivity: normalizedBackgroundActivity,
389 automaticGitFetchInterval: resolvedBackgroundActivity.automaticGitFetchInterval,
390 providerHealthRefreshInterval: resolvedBackgroundActivity.providerHealthRefreshInterval,
391 backgroundActivityProfile: resolvedBackgroundActivity.profile,
392 };
393 if (!selectionPatch) {
394 return nextWithReplacements;
395 }
396
397 const instanceId = selectionPatch.instanceId ?? current.textGenerationModelSelection.instanceId;
398 const model = selectionPatch.model ?? current.textGenerationModelSelection.model;
399 const options = shouldReplaceTextGenerationModelSelection(selectionPatch)
400 ? selectionPatch.options
401 : mergeModelSelectionOptionsById({
402 current: current.textGenerationModelSelection.options,
403 patch: selectionPatch.options,
404 });
405
406 return {
407 ...nextWithReplacements,
408 textGenerationModelSelection: createModelSelection(instanceId, model, options),
409 };
410}