Open History to see the last commit
1import {
2 isProviderDriverKind,
3 isProviderAvailable,
4 resolveProviderInstanceEnabled,
5 type ModelSelection,
6 type ProjectId,
7 type ProjectScopedServerSettingKey,
8 type ProjectSettingsOverrides,
9 type ProviderDriverKind,
10 type ServerProvider,
11 ServerSettings,
12 type ServerSettingsPatch,
13} from "@t3tools/contracts";
14import * as Option from "effect/Option";
15import * as Schema from "effect/Schema";
16import { deepMerge } from "./Struct.ts";
17import { fromLenientJson } from "./schemaJson.ts";
18import { createModelSelection } from "./model.ts";
19import {
20 getBackgroundActivityBaseProfile,
21 normalizeBackgroundActivitySettings,
22 normalizeServerBackgroundActivitySettings,
23 resolveBackgroundActivitySettings,
24} from "./backgroundActivitySettings.ts";
25
26const ServerSettingsJson = fromLenientJson(ServerSettings);
27const decodeServerSettingsJson = Schema.decodeUnknownOption(ServerSettingsJson);
28
29/** @deprecated Read `resolveProjectSettings(...).settings.enableAgentBrowserAccess`. */
30export function resolveProjectAgentBrowserAccess(
31 settings: Pick<
32 ServerSettings,
33 "enableAgentBrowserAccess" | "projectAgentBrowserAccessOverrides" | "projectSettingsOverrides"
34 >,
35 projectId: ProjectId,
36): boolean {
37 return (
38 settings.projectSettingsOverrides[projectId]?.enableAgentBrowserAccess ??
39 settings.projectAgentBrowserAccessOverrides[projectId] ??
40 settings.enableAgentBrowserAccess
41 );
42}
43
44/** @deprecated Read `resolveProjectSettings(...).settings.defaultAutoPull`. */
45export function resolveProjectAutoPull(
46 settings: Pick<
47 ServerSettings,
48 "defaultAutoPull" | "projectAutoPullOverrides" | "projectSettingsOverrides"
49 >,
50 projectId: ProjectId,
51 legacyAutoPull: boolean | undefined,
52): boolean {
53 // Existing opt-ins stay enabled until explicitly overridden or reset.
54 return (
55 settings.projectSettingsOverrides[projectId]?.defaultAutoPull ??
56 settings.projectAutoPullOverrides[projectId] ??
57 (legacyAutoPull === true || settings.defaultAutoPull)
58 );
59}
60
61type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];
62
63const getLegacyProviderSettings = (
64 settings: ServerSettings,
65 provider: ProviderDriverKind,
66): LegacyProviderSettings | undefined =>
67 (settings.providers as Record<string, LegacyProviderSettings | undefined>)[provider];
68
69export function isModelSelectionProviderEnabled(
70 settings: ServerSettings,
71 selection: ModelSelection,
72): boolean {
73 const instanceConfig = settings.providerInstances[selection.instanceId];
74 if (instanceConfig !== undefined) {
75 return resolveProviderInstanceEnabled(instanceConfig);
76 }
77
78 return (
79 isProviderDriverKind(selection.instanceId) &&
80 getLegacyProviderSettings(settings, selection.instanceId)?.enabled === true
81 );
82}
83
84export function resolveSourceControlWriterModelSelection(
85 settings: ServerSettings,
86 providers?: ReadonlyArray<ServerProvider>,
87): ModelSelection {
88 const selection = settings.sourceControlWriterModelSelection;
89 if (!selection || !isModelSelectionProviderEnabled(settings, selection)) {
90 return settings.textGenerationModelSelection;
91 }
92 if (providers === undefined) {
93 return selection;
94 }
95
96 const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId);
97 return provider?.enabled === true && isProviderAvailable(provider)
98 ? selection
99 : settings.textGenerationModelSelection;
100}
101
102export interface PersistedServerObservabilitySettings {
103 readonly otlpTracesUrl: string | undefined;
104 readonly otlpMetricsUrl: string | undefined;
105 readonly otlpLogsUrl: string | undefined;
106}
107
108function normalizePersistedServerSettingString(
109 value: string | null | undefined,
110): string | undefined {
111 const trimmed = value?.trim();
112 return trimmed && trimmed.length > 0 ? trimmed : undefined;
113}
114
115function extractPersistedServerObservabilitySettings(input: {
116 readonly observability?: {
117 readonly otlpTracesUrl?: string;
118 readonly otlpMetricsUrl?: string;
119 readonly otlpLogsUrl?: string;
120 };
121}): PersistedServerObservabilitySettings {
122 return {
123 otlpTracesUrl: normalizePersistedServerSettingString(input.observability?.otlpTracesUrl),
124 otlpMetricsUrl: normalizePersistedServerSettingString(input.observability?.otlpMetricsUrl),
125 otlpLogsUrl: normalizePersistedServerSettingString(input.observability?.otlpLogsUrl),
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, otlpLogsUrl: 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 worktreeCleanup: worktreeCleanupPatch,
277 // Merged per entry below; its `null` removals must not reach deepMerge.
278 usageLimitSources: usageLimitSourcesPatch,
279 usagePriceOverrides: usagePriceOverridesPatch,
280 // Entry replacement: deepMerge would keep keys the client meant to clear.
281 projectSettingsOverrides: projectSettingsOverridesPatch,
282 // Already translated into `projectSettingsOverrides` above; the legacy
283 // maps are derived views and must never be merged directly.
284 projectAgentBrowserAccessOverrides: _legacyBrowserAccess,
285 projectAutoPullOverrides: _legacyAutoPull,
286 projectScriptOverrides: _legacyScripts,
287 ...patchForMerge
288 } = patch;
289 const currentBackgroundActivity = normalizeServerBackgroundActivitySettings(current);
290 const backgroundActivityPatch =
291 backgroundActivityProfile !== undefined
292 ? {
293 schemaVersion: 1 as const,
294 profile:
295 automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
296 ? ("custom" as const)
297 : backgroundActivityProfile,
298 ...(automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
299 ? { baseProfile: backgroundActivityProfile }
300 : {}),
301 overrides: {
302 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
303 ...(providerHealthRefreshInterval !== undefined
304 ? { providerHealthRefreshInterval }
305 : {}),
306 },
307 }
308 : automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
309 ? {
310 schemaVersion: 1 as const,
311 profile: "custom" as const,
312 baseProfile: getBackgroundActivityBaseProfile(currentBackgroundActivity),
313 overrides: {
314 ...(currentBackgroundActivity.profile === "custom"
315 ? currentBackgroundActivity.overrides
316 : {}),
317 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
318 ...(providerHealthRefreshInterval !== undefined
319 ? { providerHealthRefreshInterval }
320 : {}),
321 },
322 }
323 : undefined;
324 const next = deepMerge(current, patchForMerge);
325 const nextWithReplacementsBase = {
326 ...next,
327 ...(worktreeCleanupPatch === undefined
328 ? {}
329 : {
330 worktreeCleanup:
331 worktreeCleanupPatch?.mode === "custom"
332 ? {
333 mode: "custom" as const,
334 rules: {
335 worktreeAfterDays: next.storageCleanup.worktreeAfterDays,
336 worktreeOnMerge: next.storageCleanup.worktreeOnMerge,
337 worktreeOnDelete: next.storageCleanup.worktreeOnDelete,
338 worktreeUnchanged: next.storageCleanup.worktreeUnchanged,
339 ...(current.worktreeCleanup?.mode === "custom"
340 ? current.worktreeCleanup.rules
341 : {}),
342 ...worktreeCleanupPatch.rules,
343 },
344 }
345 : worktreeCleanupPatch,
346 }),
347 ...(backgroundActivity !== undefined
348 ? {
349 backgroundActivity: {
350 ...deepMerge(currentBackgroundActivity, backgroundActivity),
351 ...(backgroundActivity.overrides !== undefined
352 ? { overrides: backgroundActivity.overrides }
353 : {}),
354 },
355 }
356 : { backgroundActivity: currentBackgroundActivity }),
357 ...(backgroundActivity === undefined && backgroundActivityPatch !== undefined
358 ? { backgroundActivity: backgroundActivityPatch }
359 : {}),
360 ...(patch.providerInstances !== undefined
361 ? { providerInstances: patch.providerInstances }
362 : {}),
363 ...(projectSettingsOverridesPatch !== undefined
364 ? {
365 projectSettingsOverrides: Object.fromEntries(
366 Object.entries(
367 mergeSettingsEntries(current.projectSettingsOverrides, projectSettingsOverridesPatch),
368 ).filter(([, entry]) => Object.keys(entry).length > 0),
369 ),
370 }
371 : {}),
372 ...(patch.defaultModelSelection !== undefined
373 ? { defaultModelSelection: patch.defaultModelSelection }
374 : {}),
375 ...(patch.defaultProjectScripts !== undefined
376 ? { defaultProjectScripts: patch.defaultProjectScripts }
377 : {}),
378 ...(usageLimitSourcesPatch !== undefined
379 ? {
380 usageLimitSources: mergeSettingsEntries(
381 current.usageLimitSources,
382 usageLimitSourcesPatch,
383 ),
384 }
385 : {}),
386 ...(usagePriceOverridesPatch !== undefined
387 ? {
388 usagePriceOverrides: mergeSettingsEntries(
389 current.usagePriceOverrides,
390 usagePriceOverridesPatch,
391 ),
392 }
393 : {}),
394 ...(patch.sourceControlWriterModelSelection !== undefined
395 ? { sourceControlWriterModelSelection: patch.sourceControlWriterModelSelection }
396 : {}),
397 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
398 ...(providerHealthRefreshInterval !== undefined ? { providerHealthRefreshInterval } : {}),
399 };
400 const normalizedBackgroundActivity = normalizeBackgroundActivitySettings(
401 nextWithReplacementsBase.backgroundActivity,
402 );
403 const resolvedBackgroundActivity = resolveBackgroundActivitySettings(
404 normalizedBackgroundActivity,
405 );
406 const nextWithReplacements = {
407 ...nextWithReplacementsBase,
408 ...deriveLegacyProjectOverrides(nextWithReplacementsBase),
409 backgroundActivity: normalizedBackgroundActivity,
410 automaticGitFetchInterval: resolvedBackgroundActivity.automaticGitFetchInterval,
411 providerHealthRefreshInterval: resolvedBackgroundActivity.providerHealthRefreshInterval,
412 backgroundActivityProfile: resolvedBackgroundActivity.profile,
413 };
414 if (!selectionPatch) {
415 return nextWithReplacements;
416 }
417
418 const instanceId = selectionPatch.instanceId ?? current.textGenerationModelSelection.instanceId;
419 const model = selectionPatch.model ?? current.textGenerationModelSelection.model;
420 const options = shouldReplaceTextGenerationModelSelection(selectionPatch)
421 ? selectionPatch.options
422 : mergeModelSelectionOptionsById({
423 current: current.textGenerationModelSelection.options,
424 patch: selectionPatch.options,
425 });
426
427 return {
428 ...nextWithReplacements,
429 textGenerationModelSelection: createModelSelection(instanceId, model, options),
430 };
431}