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

serverSettings.ts

461 lines17.2 KB

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