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

serverSettings.ts

407 lines15.1 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 // Merged per entry below; its `null` removals must not reach deepMerge.
274 usageLimitSources: usageLimitSourcesPatch,
275 usagePriceOverrides: usagePriceOverridesPatch,
276 // Entry replacement: deepMerge would keep keys the client meant to clear.
277 projectSettingsOverrides: projectSettingsOverridesPatch,
278 // Already translated into `projectSettingsOverrides` above; the legacy
279 // maps are derived views and must never be merged directly.
280 projectAgentBrowserAccessOverrides: _legacyBrowserAccess,
281 projectAutoPullOverrides: _legacyAutoPull,
282 projectScriptOverrides: _legacyScripts,
283 ...patchForMerge
284 } = patch;
285 const currentBackgroundActivity = normalizeServerBackgroundActivitySettings(current);
286 const backgroundActivityPatch =
287 backgroundActivityProfile !== undefined
288 ? {
289 schemaVersion: 1 as const,
290 profile:
291 automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
292 ? ("custom" as const)
293 : backgroundActivityProfile,
294 ...(automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
295 ? { baseProfile: backgroundActivityProfile }
296 : {}),
297 overrides: {
298 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
299 ...(providerHealthRefreshInterval !== undefined
300 ? { providerHealthRefreshInterval }
301 : {}),
302 },
303 }
304 : automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
305 ? {
306 schemaVersion: 1 as const,
307 profile: "custom" as const,
308 baseProfile: getBackgroundActivityBaseProfile(currentBackgroundActivity),
309 overrides: {
310 ...(currentBackgroundActivity.profile === "custom"
311 ? currentBackgroundActivity.overrides
312 : {}),
313 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
314 ...(providerHealthRefreshInterval !== undefined
315 ? { providerHealthRefreshInterval }
316 : {}),
317 },
318 }
319 : undefined;
320 const next = deepMerge(current, patchForMerge);
321 const nextWithReplacementsBase = {
322 ...next,
323 ...(backgroundActivity !== undefined
324 ? {
325 backgroundActivity: {
326 ...deepMerge(currentBackgroundActivity, backgroundActivity),
327 ...(backgroundActivity.overrides !== undefined
328 ? { overrides: backgroundActivity.overrides }
329 : {}),
330 },
331 }
332 : { backgroundActivity: currentBackgroundActivity }),
333 ...(backgroundActivity === undefined && backgroundActivityPatch !== undefined
334 ? { backgroundActivity: backgroundActivityPatch }
335 : {}),
336 ...(patch.providerInstances !== undefined
337 ? { providerInstances: patch.providerInstances }
338 : {}),
339 ...(projectSettingsOverridesPatch !== undefined
340 ? {
341 projectSettingsOverrides: Object.fromEntries(
342 Object.entries(
343 mergeSettingsEntries(current.projectSettingsOverrides, projectSettingsOverridesPatch),
344 ).filter(([, entry]) => Object.keys(entry).length > 0),
345 ),
346 }
347 : {}),
348 ...(patch.defaultModelSelection !== undefined
349 ? { defaultModelSelection: patch.defaultModelSelection }
350 : {}),
351 ...(patch.defaultProjectScripts !== undefined
352 ? { defaultProjectScripts: patch.defaultProjectScripts }
353 : {}),
354 ...(usageLimitSourcesPatch !== undefined
355 ? {
356 usageLimitSources: mergeSettingsEntries(
357 current.usageLimitSources,
358 usageLimitSourcesPatch,
359 ),
360 }
361 : {}),
362 ...(usagePriceOverridesPatch !== undefined
363 ? {
364 usagePriceOverrides: mergeSettingsEntries(
365 current.usagePriceOverrides,
366 usagePriceOverridesPatch,
367 ),
368 }
369 : {}),
370 ...(patch.sourceControlWriterModelSelection !== undefined
371 ? { sourceControlWriterModelSelection: patch.sourceControlWriterModelSelection }
372 : {}),
373 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
374 ...(providerHealthRefreshInterval !== undefined ? { providerHealthRefreshInterval } : {}),
375 };
376 const normalizedBackgroundActivity = normalizeBackgroundActivitySettings(
377 nextWithReplacementsBase.backgroundActivity,
378 );
379 const resolvedBackgroundActivity = resolveBackgroundActivitySettings(
380 normalizedBackgroundActivity,
381 );
382 const nextWithReplacements = {
383 ...nextWithReplacementsBase,
384 ...deriveLegacyProjectOverrides(nextWithReplacementsBase),
385 backgroundActivity: normalizedBackgroundActivity,
386 automaticGitFetchInterval: resolvedBackgroundActivity.automaticGitFetchInterval,
387 providerHealthRefreshInterval: resolvedBackgroundActivity.providerHealthRefreshInterval,
388 backgroundActivityProfile: resolvedBackgroundActivity.profile,
389 };
390 if (!selectionPatch) {
391 return nextWithReplacements;
392 }
393​
394 const instanceId = selectionPatch.instanceId ?? current.textGenerationModelSelection.instanceId;
395 const model = selectionPatch.model ?? current.textGenerationModelSelection.model;
396 const options = shouldReplaceTextGenerationModelSelection(selectionPatch)
397 ? selectionPatch.options
398 : mergeModelSelectionOptionsById({
399 current: current.textGenerationModelSelection.options,
400 patch: selectionPatch.options,
401 });
402​
403 return {
404 ...nextWithReplacements,
405 textGenerationModelSelection: createModelSelection(instanceId, model, options),
406 };