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

serverSettings.ts

449 lines16.8 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 usagePriceOverrides: usagePriceOverridesPatch,
271 usageModelAliases: usageModelAliasesPatch,
272 // Entry replacement: deepMerge would keep keys the client meant to clear.
273 projectSettingsOverrides: projectSettingsOverridesPatch,
274 // Already translated into `projectSettingsOverrides` above; the legacy
275 // maps are derived views and must never be merged directly.
276 projectAgentBrowserAccessOverrides: _legacyBrowserAccess,
277 projectAutoPullOverrides: _legacyAutoPull,
278 projectScriptOverrides: _legacyScripts,
279 ...patchForMerge
280 } = patch;
281 const currentBackgroundActivity = normalizeServerBackgroundActivitySettings(current);
282 const backgroundActivityPatch =
283 backgroundActivityProfile !== undefined
284 ? {
285 schemaVersion: 1 as const,
286 profile:
287 automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
288 ? ("custom" as const)
289 : backgroundActivityProfile,
290 ...(automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
291 ? { baseProfile: backgroundActivityProfile }
292 : {}),
293 overrides: {
294 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
295 ...(providerHealthRefreshInterval !== undefined
296 ? { providerHealthRefreshInterval }
297 : {}),
298 },
299 }
300 : automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
301 ? {
302 schemaVersion: 1 as const,
303 profile: "custom" as const,
304 baseProfile: getBackgroundActivityBaseProfile(currentBackgroundActivity),
305 overrides: {
306 ...(currentBackgroundActivity.profile === "custom"
307 ? currentBackgroundActivity.overrides
308 : {}),
309 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
310 ...(providerHealthRefreshInterval !== undefined
311 ? { providerHealthRefreshInterval }
312 : {}),
313 },
314 }
315 : undefined;
316 const next = deepMerge(current, patchForMerge);
317 const nextWithReplacementsBase = {
318 ...next,
319 ...(worktreeCleanupPatch === undefined
320 ? {}
321 : {
322 worktreeCleanup:
323 worktreeCleanupPatch?.mode === "custom"
324 ? {
325 mode: "custom" as const,
326 rules: {
327 worktreeAfterDays: next.storageCleanup.worktreeAfterDays,
328 worktreeOnMerge: next.storageCleanup.worktreeOnMerge,
329 worktreeOnDelete: next.storageCleanup.worktreeOnDelete,
330 worktreeUnchanged: next.storageCleanup.worktreeUnchanged,
331 ...(current.worktreeCleanup?.mode === "custom"
332 ? current.worktreeCleanup.rules
333 : {}),
334 ...worktreeCleanupPatch.rules,
335 },
336 }
337 : worktreeCleanupPatch,
338 }),
339 ...(backgroundActivity !== undefined
340 ? {
341 backgroundActivity: {
342 ...deepMerge(currentBackgroundActivity, backgroundActivity),
343 ...(backgroundActivity.overrides !== undefined
344 ? { overrides: backgroundActivity.overrides }
345 : {}),
346 },
347 }
348 : { backgroundActivity: currentBackgroundActivity }),
349 ...(backgroundActivity === undefined && backgroundActivityPatch !== undefined
350 ? { backgroundActivity: backgroundActivityPatch }
351 : {}),
352 ...(patch.providerInstances !== undefined
353 ? { providerInstances: patch.providerInstances }
354 : {}),
355 ...(patch.worktreesDirectory !== undefined &&
356 patch.worktreesDirectory !== current.worktreesDirectory
357 ? {
358 previousWorktreesDirectories: [
359 ...current.previousWorktreesDirectories.filter(
360 (directory) => directory !== patch.worktreesDirectory,
361 ),
362 ...(current.worktreesDirectory !== "" &&
363 !current.previousWorktreesDirectories.includes(current.worktreesDirectory)
364 ? [current.worktreesDirectory]
365 : []),
366 ],
367 }
368 : {}),
369 // Host replacement: deepMerge would keep a cleared account pin.
370 ...(patch.github?.hosts !== undefined
371 ? { github: { ...next.github, hosts: patch.github.hosts } }
372 : {}),
373 ...(projectSettingsOverridesPatch !== undefined
374 ? {
375 projectSettingsOverrides: Object.fromEntries(
376 Object.entries(
377 mergeSettingsEntries(current.projectSettingsOverrides, projectSettingsOverridesPatch),
378 ).filter(([, entry]) => Object.keys(entry).length > 0),
379 ),
380 }
381 : {}),
382 ...(patch.defaultModelSelection !== undefined
383 ? { defaultModelSelection: patch.defaultModelSelection }
384 : {}),
385 ...(patch.defaultProjectScripts !== undefined
386 ? { defaultProjectScripts: patch.defaultProjectScripts }
387 : {}),
388 ...(usageLimitSourcesPatch !== undefined
389 ? {
390 usageLimitSources: mergeSettingsEntries(
391 current.usageLimitSources,
392 usageLimitSourcesPatch,
393 ),
394 }
395 : {}),
396 ...(usagePriceOverridesPatch !== undefined
397 ? {
398 usagePriceOverrides: mergeSettingsEntries(
399 current.usagePriceOverrides,
400 usagePriceOverridesPatch,
401 ),
402 }
403 : {}),
404 ...(usageModelAliasesPatch !== undefined
405 ? {
406 usageModelAliases: mergeSettingsEntries(
407 current.usageModelAliases,
408 usageModelAliasesPatch,
409 ),
410 }
411 : {}),
412 ...(patch.sourceControlWriterModelSelection !== undefined
413 ? { sourceControlWriterModelSelection: patch.sourceControlWriterModelSelection }
414 : {}),
415 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
416 ...(providerHealthRefreshInterval !== undefined ? { providerHealthRefreshInterval } : {}),
417 };
418 const normalizedBackgroundActivity = normalizeBackgroundActivitySettings(
419 nextWithReplacementsBase.backgroundActivity,
420 );
421 const resolvedBackgroundActivity = resolveBackgroundActivitySettings(
422 normalizedBackgroundActivity,
423 );
424 const nextWithReplacements = {
425 ...nextWithReplacementsBase,
426 ...deriveLegacyProjectOverrides(nextWithReplacementsBase),
427 backgroundActivity: normalizedBackgroundActivity,
428 automaticGitFetchInterval: resolvedBackgroundActivity.automaticGitFetchInterval,
429 providerHealthRefreshInterval: resolvedBackgroundActivity.providerHealthRefreshInterval,
430 backgroundActivityProfile: resolvedBackgroundActivity.profile,
431 };
432 if (!selectionPatch) {
433 return nextWithReplacements;
434 }
435​
436 const instanceId = selectionPatch.instanceId ?? current.textGenerationModelSelection.instanceId;
437 const model = selectionPatch.model ?? current.textGenerationModelSelection.model;
438 const options = shouldReplaceTextGenerationModelSelection(selectionPatch)
439 ? selectionPatch.options
440 : mergeModelSelectionOptionsById({
441 current: current.textGenerationModelSelection.options,
442 patch: selectionPatch.options,
443 });
444​
445 return {
446 ...nextWithReplacements,
447 textGenerationModelSelection: createModelSelection(instanceId, model, options),
448 };