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 readonly otlpLogsUrl: string | undefined;
109}
110
111function normalizePersistedServerSettingString(
112 value: string | null | undefined,
113): string | undefined {
114 const trimmed = value?.trim();
115 return trimmed && trimmed.length > 0 ? trimmed : undefined;
116}
117
118function extractPersistedServerObservabilitySettings(input: {
119 readonly observability?: {
120 readonly otlpTracesUrl?: string;
121 readonly otlpMetricsUrl?: string;
122 readonly otlpLogsUrl?: string;
123 };
124}): PersistedServerObservabilitySettings {
125 return {
126 otlpTracesUrl: normalizePersistedServerSettingString(input.observability?.otlpTracesUrl),
127 otlpMetricsUrl: normalizePersistedServerSettingString(input.observability?.otlpMetricsUrl),
128 otlpLogsUrl: normalizePersistedServerSettingString(input.observability?.otlpLogsUrl),
129 };
130}
131
132export function parsePersistedServerObservabilitySettings(
133 raw: string,
134): PersistedServerObservabilitySettings {
135 const decoded = decodeServerSettingsJson(raw);
136 if (Option.isSome(decoded)) {
137 return extractPersistedServerObservabilitySettings(decoded.value);
138 }
139 return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined, otlpLogsUrl: undefined };
140}
141
142function shouldReplaceTextGenerationModelSelection(
143 patch: ServerSettingsPatch["textGenerationModelSelection"] | undefined,
144): boolean {
145 return Boolean(patch && (patch.instanceId !== undefined || patch.model !== undefined));
146}
147
148function mergeModelSelectionOptionsById(input: {
149 current: ReadonlyArray<{ readonly id: string; readonly value: string | boolean }> | undefined;
150 patch: ReadonlyArray<{ readonly id: string; readonly value: string | boolean }> | undefined;
151}): Array<{ id: string; value: string | boolean }> | undefined {
152 if (input.patch === undefined) {
153 return input.current ? [...input.current] : undefined;
154 }
155 if (input.patch.length === 0) {
156 return undefined;
157 }
158
159 const merged = new Map((input.current ?? []).map((selection) => [selection.id, selection.value]));
160 for (const selection of input.patch) {
161 merged.set(selection.id, selection.value);
162 }
163 return [...merged.entries()].map(([id, value]) => ({ id, value }));
164}
165
166/** Upsert each patched entry; `null` removes it. Entries the patch omits are untouched. */
167function mergeSettingsEntries<Value>(
168 current: Readonly<Record<string, Value>>,
169 patch: Readonly<Record<string, Value | null>>,
170): Record<string, Value> {
171 const next = new Map(Object.entries(current));
172 for (const [id, config] of Object.entries(patch)) {
173 if (config === null) {
174 next.delete(id);
175 } else {
176 next.set(id, config);
177 }
178 }
179 return Object.fromEntries(next);
180}
181
182/**
183 * Derived views of `projectSettingsOverrides` for clients that still read
184 * the legacy per-key maps. Recomputed on every patch and load so they
185 * cannot drift from the generic record.
186 */
187export function deriveLegacyProjectOverrides(
188 settings: Pick<ServerSettings, "projectSettingsOverrides">,
189): Pick<
190 ServerSettings,
191 "projectAgentBrowserAccessOverrides" | "projectAutoPullOverrides" | "projectScriptOverrides"
192> {
193 const projectAgentBrowserAccessOverrides: Record<string, boolean> = {};
194 const projectAutoPullOverrides: Record<string, boolean> = {};
195 const projectScriptOverrides: Record<string, ServerSettings["defaultProjectScripts"] | null> = {};
196 for (const [projectId, entry] of Object.entries(settings.projectSettingsOverrides)) {
197 if (entry.enableAgentBrowserAccess !== undefined) {
198 projectAgentBrowserAccessOverrides[projectId] = entry.enableAgentBrowserAccess;
199 }
200 if (entry.defaultAutoPull !== undefined) {
201 projectAutoPullOverrides[projectId] = entry.defaultAutoPull;
202 }
203 if (entry.defaultProjectScripts !== undefined) {
204 projectScriptOverrides[projectId] = entry.defaultProjectScripts;
205 }
206 }
207 return { projectAgentBrowserAccessOverrides, projectAutoPullOverrides, projectScriptOverrides };
208}
209
210/**
211 * Rewrite a patch that still uses the legacy per-key project maps into
212 * entries of `projectSettingsOverrides`, so older clients keep editing the
213 * values the server actually reads. `null` in a legacy map clears that one
214 * override.
215 */
216function translateLegacyProjectOverridePatch(
217 current: Pick<ServerSettings, "projectSettingsOverrides">,
218 patch: ServerSettingsPatch,
219): ServerSettingsPatch {
220 const {
221 projectAgentBrowserAccessOverrides,
222 projectAutoPullOverrides,
223 projectScriptOverrides,
224 ...rest
225 } = patch;
226 if (
227 projectAgentBrowserAccessOverrides === undefined &&
228 projectAutoPullOverrides === undefined &&
229 projectScriptOverrides === undefined
230 ) {
231 return patch;
232 }
233 const currentEntries: Readonly<Record<string, ProjectSettingsOverrides>> =
234 current.projectSettingsOverrides;
235 const entries = new Map<string, ProjectSettingsOverrides | null>(
236 Object.entries(rest.projectSettingsOverrides ?? {}),
237 );
238 // A canonical entry in the same patch is the newer representation; a legacy
239 // map must not resurrect a key that entry deliberately omits.
240 const canonicalProjectIds = new Set(Object.keys(rest.projectSettingsOverrides ?? {}));
241 const applyKey = <K extends ProjectScopedServerSettingKey>(
242 map: Readonly<Record<string, ProjectSettingsOverrides[K] | null>> | undefined,
243 key: K,
244 ) => {
245 if (map === undefined) return;
246 for (const [projectId, value] of Object.entries(map)) {
247 if (canonicalProjectIds.has(projectId)) continue;
248 const entry: ProjectSettingsOverrides = {
249 ...(entries.get(projectId) ?? currentEntries[projectId] ?? {}),
250 };
251 if (value === null || value === undefined) {
252 delete entry[key];
253 } else {
254 entry[key] = value;
255 }
256 entries.set(projectId, Object.keys(entry).length === 0 ? null : entry);
257 }
258 };
259 applyKey(projectAgentBrowserAccessOverrides, "enableAgentBrowserAccess");
260 applyKey(projectAutoPullOverrides, "defaultAutoPull");
261 applyKey(projectScriptOverrides, "defaultProjectScripts");
262 return {
263 ...rest,
264 projectSettingsOverrides: Object.fromEntries(entries),
265 } as ServerSettingsPatch;
266}
267
268export function applyServerSettingsPatch(
269 current: ServerSettings,
270 rawPatch: ServerSettingsPatch,
271): ServerSettings {
272 const patch = translateLegacyProjectOverridePatch(current, rawPatch);
273 const selectionPatch = patch.textGenerationModelSelection;
274 const {
275 automaticGitFetchInterval,
276 providerHealthRefreshInterval,
277 backgroundActivityProfile,
278 backgroundActivity,
279 worktreeCleanup: worktreeCleanupPatch,
280 // Merged per entry below; its `null` removals must not reach deepMerge.
281 usageLimitSources: usageLimitSourcesPatch,
282 usagePriceOverrides: usagePriceOverridesPatch,
283 // Entry replacement: deepMerge would keep keys the client meant to clear.
284 projectSettingsOverrides: projectSettingsOverridesPatch,
285 // Already translated into `projectSettingsOverrides` above; the legacy
286 // maps are derived views and must never be merged directly.
287 projectAgentBrowserAccessOverrides: _legacyBrowserAccess,
288 projectAutoPullOverrides: _legacyAutoPull,
289 projectScriptOverrides: _legacyScripts,
290 ...patchForMerge
291 } = patch;
292 const currentBackgroundActivity = normalizeServerBackgroundActivitySettings(current);
293 const backgroundActivityPatch =
294 backgroundActivityProfile !== undefined
295 ? {
296 schemaVersion: 1 as const,
297 profile:
298 automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
299 ? ("custom" as const)
300 : backgroundActivityProfile,
301 ...(automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
302 ? { baseProfile: backgroundActivityProfile }
303 : {}),
304 overrides: {
305 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
306 ...(providerHealthRefreshInterval !== undefined
307 ? { providerHealthRefreshInterval }
308 : {}),
309 },
310 }
311 : automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
312 ? {
313 schemaVersion: 1 as const,
314 profile: "custom" as const,
315 baseProfile: getBackgroundActivityBaseProfile(currentBackgroundActivity),
316 overrides: {
317 ...(currentBackgroundActivity.profile === "custom"
318 ? currentBackgroundActivity.overrides
319 : {}),
320 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
321 ...(providerHealthRefreshInterval !== undefined
322 ? { providerHealthRefreshInterval }
323 : {}),
324 },
325 }
326 : undefined;
327 const next = deepMerge(current, patchForMerge);
328 const nextWithReplacementsBase = {
329 ...next,
330 ...(worktreeCleanupPatch === undefined
331 ? {}
332 : {
333 worktreeCleanup:
334 worktreeCleanupPatch?.mode === "custom"
335 ? {
336 mode: "custom" as const,
337 rules: {
338 worktreeAfterDays: next.storageCleanup.worktreeAfterDays,
339 worktreeOnMerge: next.storageCleanup.worktreeOnMerge,
340 worktreeOnDelete: next.storageCleanup.worktreeOnDelete,
341 worktreeUnchanged: next.storageCleanup.worktreeUnchanged,
342 ...(current.worktreeCleanup?.mode === "custom"
343 ? current.worktreeCleanup.rules
344 : {}),
345 ...worktreeCleanupPatch.rules,
346 },
347 }
348 : worktreeCleanupPatch,
349 }),
350 ...(backgroundActivity !== undefined
351 ? {
352 backgroundActivity: {
353 ...deepMerge(currentBackgroundActivity, backgroundActivity),
354 ...(backgroundActivity.overrides !== undefined
355 ? { overrides: backgroundActivity.overrides }
356 : {}),
357 },
358 }
359 : { backgroundActivity: currentBackgroundActivity }),
360 ...(backgroundActivity === undefined && backgroundActivityPatch !== undefined
361 ? { backgroundActivity: backgroundActivityPatch }
362 : {}),
363 ...(patch.providerInstances !== undefined
364 ? { providerInstances: patch.providerInstances }
365 : {}),
366 ...(projectSettingsOverridesPatch !== undefined
367 ? {
368 projectSettingsOverrides: Object.fromEntries(
369 Object.entries(
370 mergeSettingsEntries(current.projectSettingsOverrides, projectSettingsOverridesPatch),
371 ).filter(([, entry]) => Object.keys(entry).length > 0),
372 ),
373 }
374 : {}),
375 ...(patch.defaultModelSelection !== undefined
376 ? { defaultModelSelection: patch.defaultModelSelection }
377 : {}),
378 ...(patch.defaultProjectScripts !== undefined
379 ? { defaultProjectScripts: patch.defaultProjectScripts }
380 : {}),
381 ...(usageLimitSourcesPatch !== undefined
382 ? {
383 usageLimitSources: mergeSettingsEntries(
384 current.usageLimitSources,
385 usageLimitSourcesPatch,
386 ),
387 }
388 : {}),
389 ...(usagePriceOverridesPatch !== undefined
390 ? {
391 usagePriceOverrides: mergeSettingsEntries(
392 current.usagePriceOverrides,
393 usagePriceOverridesPatch,
394 ),
395 }
396 : {}),
397 ...(patch.sourceControlWriterModelSelection !== undefined
398 ? { sourceControlWriterModelSelection: patch.sourceControlWriterModelSelection }
399 : {}),
400 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
401 ...(providerHealthRefreshInterval !== undefined ? { providerHealthRefreshInterval } : {}),
402 };
403 const normalizedBackgroundActivity = normalizeBackgroundActivitySettings(
404 nextWithReplacementsBase.backgroundActivity,
405 );
406 const resolvedBackgroundActivity = resolveBackgroundActivitySettings(
407 normalizedBackgroundActivity,
408 );
409 const nextWithReplacements = {
410 ...nextWithReplacementsBase,
411 ...deriveLegacyProjectOverrides(nextWithReplacementsBase),
412 backgroundActivity: normalizedBackgroundActivity,
413 automaticGitFetchInterval: resolvedBackgroundActivity.automaticGitFetchInterval,
414 providerHealthRefreshInterval: resolvedBackgroundActivity.providerHealthRefreshInterval,
415 backgroundActivityProfile: resolvedBackgroundActivity.profile,
416 };
417 if (!selectionPatch) {
418 return nextWithReplacements;
419 }
420
421 const instanceId = selectionPatch.instanceId ?? current.textGenerationModelSelection.instanceId;
422 const model = selectionPatch.model ?? current.textGenerationModelSelection.model;
423 const options = shouldReplaceTextGenerationModelSelection(selectionPatch)
424 ? selectionPatch.options
425 : mergeModelSelectionOptionsById({
426 current: current.textGenerationModelSelection.options,
427 patch: selectionPatch.options,
428 });
429
430 return {
431 ...nextWithReplacements,
432 textGenerationModelSelection: createModelSelection(instanceId, model, options),
433 };
434}