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