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

serverSettings.ts

316 lines11.3 KB

1import {
2 isProviderDriverKind,
3 isProviderAvailable,
4 resolveProviderInstanceEnabled,
5 type ModelSelection,
6 type ProjectId,
7 type ProviderDriverKind,
8 type ServerProvider,
9 ServerSettings,
10 type ServerSettingsPatch,
11} from "@t3tools/contracts";
12import * as Option from "effect/Option";
13import * as Schema from "effect/Schema";
14import { deepMerge } from "./Struct.ts";
15import { fromLenientJson } from "./schemaJson.ts";
16import { createModelSelection } from "./model.ts";
17import {
18 getBackgroundActivityBaseProfile,
19 normalizeBackgroundActivitySettings,
20 normalizeServerBackgroundActivitySettings,
21 resolveBackgroundActivitySettings,
22} from "./backgroundActivitySettings.ts";
23​
24const ServerSettingsJson = fromLenientJson(ServerSettings);
25const decodeServerSettingsJson = Schema.decodeUnknownOption(ServerSettingsJson);
26​
27export function resolveProjectAgentBrowserAccess(
28 settings: Pick<ServerSettings, "enableAgentBrowserAccess" | "projectAgentBrowserAccessOverrides">,
29 projectId: ProjectId,
30): boolean {
31 return (
32 settings.projectAgentBrowserAccessOverrides[projectId] ?? settings.enableAgentBrowserAccess
33 );
35​
36export function resolveProjectAutoPull(
37 settings: Pick<ServerSettings, "defaultAutoPull" | "projectAutoPullOverrides">,
38 projectId: ProjectId,
39 legacyAutoPull: boolean | undefined,
40): boolean {
41 // Existing opt-ins stay enabled until explicitly overridden or reset.
42 return (
43 settings.projectAutoPullOverrides[projectId] ??
44 (legacyAutoPull === true || settings.defaultAutoPull)
45 );
47​
48type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];
49​
50const getLegacyProviderSettings = (
51 settings: ServerSettings,
52 provider: ProviderDriverKind,
53): LegacyProviderSettings | undefined =>
54 (settings.providers as Record<string, LegacyProviderSettings | undefined>)[provider];
55​
56export function isModelSelectionProviderEnabled(
57 settings: ServerSettings,
58 selection: ModelSelection,
59): boolean {
60 const instanceConfig = settings.providerInstances[selection.instanceId];
61 if (instanceConfig !== undefined) {
62 return resolveProviderInstanceEnabled(instanceConfig);
63 }
64​
65 return (
66 isProviderDriverKind(selection.instanceId) &&
67 getLegacyProviderSettings(settings, selection.instanceId)?.enabled === true
68 );
70​
71export function resolveSourceControlWriterModelSelection(
72 settings: ServerSettings,
73 providers?: ReadonlyArray<ServerProvider>,
74): ModelSelection {
75 const selection = settings.sourceControlWriterModelSelection;
76 if (!selection || !isModelSelectionProviderEnabled(settings, selection)) {
77 return settings.textGenerationModelSelection;
78 }
79 if (providers === undefined) {
80 return selection;
81 }
82​
83 const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId);
84 return provider?.enabled === true && isProviderAvailable(provider)
85 ? selection
86 : settings.textGenerationModelSelection;
88​
89export interface PersistedServerObservabilitySettings {
90 readonly otlpTracesUrl: string | undefined;
91 readonly otlpMetricsUrl: string | undefined;
93​
94function normalizePersistedServerSettingString(
95 value: string | null | undefined,
96): string | undefined {
97 const trimmed = value?.trim();
98 return trimmed && trimmed.length > 0 ? trimmed : undefined;
100​
101function extractPersistedServerObservabilitySettings(input: {
102 readonly observability?: {
103 readonly otlpTracesUrl?: string;
104 readonly otlpMetricsUrl?: string;
105 };
106}): PersistedServerObservabilitySettings {
107 return {
108 otlpTracesUrl: normalizePersistedServerSettingString(input.observability?.otlpTracesUrl),
109 otlpMetricsUrl: normalizePersistedServerSettingString(input.observability?.otlpMetricsUrl),
110 };
112​
113export function parsePersistedServerObservabilitySettings(
114 raw: string,
115): PersistedServerObservabilitySettings {
116 const decoded = decodeServerSettingsJson(raw);
117 if (Option.isSome(decoded)) {
118 return extractPersistedServerObservabilitySettings(decoded.value);
119 }
120 return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
122​
123function shouldReplaceTextGenerationModelSelection(
124 patch: ServerSettingsPatch["textGenerationModelSelection"] | undefined,
125): boolean {
126 return Boolean(patch && (patch.instanceId !== undefined || patch.model !== undefined));
128​
129function mergeModelSelectionOptionsById(input: {
130 current: ReadonlyArray<{ readonly id: string; readonly value: string | boolean }> | undefined;
131 patch: ReadonlyArray<{ readonly id: string; readonly value: string | boolean }> | undefined;
132}): Array<{ id: string; value: string | boolean }> | undefined {
133 if (input.patch === undefined) {
134 return input.current ? [...input.current] : undefined;
135 }
136 if (input.patch.length === 0) {
137 return undefined;
138 }
139​
140 const merged = new Map((input.current ?? []).map((selection) => [selection.id, selection.value]));
141 for (const selection of input.patch) {
142 merged.set(selection.id, selection.value);
143 }
144 return [...merged.entries()].map(([id, value]) => ({ id, value }));
146​
147/** Upsert each patched entry; `null` removes it. Entries the patch omits are untouched. */
148function mergeSettingsEntries<Value>(
149 current: Readonly<Record<string, Value>>,
150 patch: Readonly<Record<string, Value | null>>,
151): Record<string, Value> {
152 const next = new Map(Object.entries(current));
153 for (const [id, config] of Object.entries(patch)) {
154 if (config === null) {
155 next.delete(id);
156 } else {
157 next.set(id, config);
158 }
159 }
160 return Object.fromEntries(next);
162​
163export function applyServerSettingsPatch(
164 current: ServerSettings,
165 patch: ServerSettingsPatch,
166): ServerSettings {
167 const selectionPatch = patch.textGenerationModelSelection;
168 const {
169 automaticGitFetchInterval,
170 providerHealthRefreshInterval,
171 backgroundActivityProfile,
172 backgroundActivity,
173 // Merged per entry below; its `null` removals must not reach deepMerge.
174 usageLimitSources: usageLimitSourcesPatch,
175 usagePriceOverrides: usagePriceOverridesPatch,
176 projectAgentBrowserAccessOverrides: projectAgentBrowserAccessOverridesPatch,
177 projectAutoPullOverrides: projectAutoPullOverridesPatch,
178 ...patchForMerge
179 } = patch;
180 const currentBackgroundActivity = normalizeServerBackgroundActivitySettings(current);
181 const backgroundActivityPatch =
182 backgroundActivityProfile !== undefined
183 ? {
184 schemaVersion: 1 as const,
185 profile:
186 automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
187 ? ("custom" as const)
188 : backgroundActivityProfile,
189 ...(automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
190 ? { baseProfile: backgroundActivityProfile }
191 : {}),
192 overrides: {
193 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
194 ...(providerHealthRefreshInterval !== undefined
195 ? { providerHealthRefreshInterval }
196 : {}),
197 },
198 }
199 : automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
200 ? {
201 schemaVersion: 1 as const,
202 profile: "custom" as const,
203 baseProfile: getBackgroundActivityBaseProfile(currentBackgroundActivity),
204 overrides: {
205 ...(currentBackgroundActivity.profile === "custom"
206 ? currentBackgroundActivity.overrides
207 : {}),
208 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
209 ...(providerHealthRefreshInterval !== undefined
210 ? { providerHealthRefreshInterval }
211 : {}),
212 },
213 }
214 : undefined;
215 const next = deepMerge(current, patchForMerge);
216 const nextWithReplacementsBase = {
217 ...next,
218 ...(backgroundActivity !== undefined
219 ? {
220 backgroundActivity: {
221 ...deepMerge(currentBackgroundActivity, backgroundActivity),
222 ...(backgroundActivity.overrides !== undefined
223 ? { overrides: backgroundActivity.overrides }
224 : {}),
225 },
226 }
227 : { backgroundActivity: currentBackgroundActivity }),
228 ...(backgroundActivity === undefined && backgroundActivityPatch !== undefined
229 ? { backgroundActivity: backgroundActivityPatch }
230 : {}),
231 ...(patch.providerInstances !== undefined
232 ? { providerInstances: patch.providerInstances }
233 : {}),
234 ...(projectAgentBrowserAccessOverridesPatch !== undefined
235 ? {
236 projectAgentBrowserAccessOverrides: mergeSettingsEntries(
237 current.projectAgentBrowserAccessOverrides,
238 projectAgentBrowserAccessOverridesPatch,
239 ),
240 }
241 : {}),
242 ...(projectAutoPullOverridesPatch !== undefined
243 ? {
244 projectAutoPullOverrides: mergeSettingsEntries(
245 current.projectAutoPullOverrides,
246 projectAutoPullOverridesPatch,
247 ),
248 }
249 : {}),
250 ...(patch.defaultModelSelection !== undefined
251 ? { defaultModelSelection: patch.defaultModelSelection }
252 : {}),
253 ...(patch.defaultProjectScripts !== undefined
254 ? { defaultProjectScripts: patch.defaultProjectScripts }
255 : {}),
256 ...(patch.projectScriptOverrides !== undefined
257 ? {
258 projectScriptOverrides: {
259 ...current.projectScriptOverrides,
260 ...patch.projectScriptOverrides,
261 },
262 }
263 : {}),
264 ...(usageLimitSourcesPatch !== undefined
265 ? {
266 usageLimitSources: mergeSettingsEntries(
267 current.usageLimitSources,
268 usageLimitSourcesPatch,
269 ),
270 }
271 : {}),
272 ...(usagePriceOverridesPatch !== undefined
273 ? {
274 usagePriceOverrides: mergeSettingsEntries(
275 current.usagePriceOverrides,
276 usagePriceOverridesPatch,
277 ),
278 }
279 : {}),
280 ...(patch.sourceControlWriterModelSelection !== undefined
281 ? { sourceControlWriterModelSelection: patch.sourceControlWriterModelSelection }
282 : {}),
283 ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
284 ...(providerHealthRefreshInterval !== undefined ? { providerHealthRefreshInterval } : {}),
285 };
286 const normalizedBackgroundActivity = normalizeBackgroundActivitySettings(
287 nextWithReplacementsBase.backgroundActivity,
288 );
289 const resolvedBackgroundActivity = resolveBackgroundActivitySettings(
290 normalizedBackgroundActivity,
291 );
292 const nextWithReplacements = {
293 ...nextWithReplacementsBase,
294 backgroundActivity: normalizedBackgroundActivity,
295 automaticGitFetchInterval: resolvedBackgroundActivity.automaticGitFetchInterval,
296 providerHealthRefreshInterval: resolvedBackgroundActivity.providerHealthRefreshInterval,
297 backgroundActivityProfile: resolvedBackgroundActivity.profile,
298 };
299 if (!selectionPatch) {
300 return nextWithReplacements;
301 }
302​
303 const instanceId = selectionPatch.instanceId ?? current.textGenerationModelSelection.instanceId;
304 const model = selectionPatch.model ?? current.textGenerationModelSelection.model;
305 const options = shouldReplaceTextGenerationModelSelection(selectionPatch)
306 ? selectionPatch.options
307 : mergeModelSelectionOptionsById({
308 current: current.textGenerationModelSelection.options,
309 patch: selectionPatch.options,
310 });
311​
312 return {
313 ...nextWithReplacements,
314 textGenerationModelSelection: createModelSelection(instanceId, model, options),
315 };