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

serverSettings.ts

428 lines16.0 KB

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