Open History to see the last commit
1/**
2 * ServerSettings - Server-authoritative settings service.
3 *
4 * Owns persistence, validation, and change notification of settings that affect
5 * server-side behavior (binary paths, streaming mode, env mode, custom models,
6 * text generation model selection).
7 *
8 * Follows the same pattern as `keybindings.ts`: JSON file + Cache + PubSub +
9 * Semaphore + FileSystem.watch for concurrency and external edit detection.
10 *
11 * @module ServerSettings
12 */
13import {
14 DEFAULT_TEXT_GENERATION_MODEL,
15 DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER,
16 DEFAULT_MODEL_BY_PROVIDER,
17 DEFAULT_SERVER_SETTINGS,
18 type ModelSelection,
19 type ProviderInstanceConfig,
20 type ProviderInstanceEnvironmentVariable,
21 ProviderDriverKind,
22 ProviderInstanceId,
23 ServerSettings,
24 ServerSettingsError,
25 type ServerSettingsPatch,
26} from "@t3tools/contracts";
27import * as Cache from "effect/Cache";
28import * as Cause from "effect/Cause";
29import * as Context from "effect/Context";
30import * as Deferred from "effect/Deferred";
31import * as Duration from "effect/Duration";
32import * as Equal from "effect/Equal";
33import * as Effect from "effect/Effect";
34import * as Exit from "effect/Exit";
35import * as FileSystem from "effect/FileSystem";
36import * as Layer from "effect/Layer";
37import * as Option from "effect/Option";
38import * as Path from "effect/Path";
39import * as PubSub from "effect/PubSub";
40import * as Ref from "effect/Ref";
41import * as Schema from "effect/Schema";
42import * as Semaphore from "effect/Semaphore";
43import * as Scope from "effect/Scope";
44import * as Stream from "effect/Stream";
45import { writeFileStringAtomically } from "./atomicWrite.ts";
46import * as ServerConfig from "./config.ts";
47import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
48import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
49import {
50 applyServerSettingsPatch,
51 isModelSelectionProviderEnabled,
52} from "@t3tools/shared/serverSettings";
53import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
54
55export { resolveSourceControlWriterModelSelection } from "@t3tools/shared/serverSettings";
56
57const encodeServerSettings = Schema.encodeEffect(ServerSettings);
58const encodeServerSettingsJson = Schema.encodeUnknownEffect(fromJsonStringPretty(ServerSettings));
59const decodeServerSettings = Schema.decodeUnknownEffect(ServerSettings);
60
61const textEncoder = new TextEncoder();
62const textDecoder = new TextDecoder();
63
64/**
65 * Fold the legacy in-config `enabled` flag into the envelope-level
66 * `ProviderInstanceConfig.enabled` and strip it from the config blob, so
67 * explicit provider instances carry exactly one enabled flag. Old settings
68 * files can hold both flags with conflicting values; an explicit false on
69 * either side wins so a user's disable is never silently undone. Runs on
70 * every load and update — the file converges on the next write.
71 */
72const foldProviderInstanceEnabledFlags = (settings: ServerSettings): ServerSettings => {
73 let changed = false;
74 const providerInstances: Record<string, ProviderInstanceConfig> = {};
75 for (const [instanceId, instance] of Object.entries(settings.providerInstances)) {
76 const config = instance.config;
77 // Only fold boolean flags: a malformed `enabled` (e.g. `"false"`) must
78 // stay in the blob so driver schema validation flags it instead of the
79 // fold silently repairing the config.
80 if (
81 config === null ||
82 typeof config !== "object" ||
83 Array.isArray(config) ||
84 typeof (config as { readonly enabled?: unknown }).enabled !== "boolean"
85 ) {
86 providerInstances[instanceId] = instance;
87 continue;
88 }
89 const { enabled: configEnabled, ...restConfig } = config as Record<string, unknown> & {
90 readonly enabled: boolean;
91 };
92 const resolved =
93 instance.enabled === false || configEnabled === false
94 ? false
95 : (instance.enabled ?? configEnabled);
96 changed = true;
97 providerInstances[instanceId] = {
98 ...instance,
99 enabled: resolved,
100 config: restConfig,
101 } satisfies ProviderInstanceConfig;
102 }
103 if (!changed) {
104 return settings;
105 }
106 return {
107 ...settings,
108 providerInstances: providerInstances as ServerSettings["providerInstances"],
109 };
110};
111
112const normalizeServerSettings = (
113 settings: ServerSettings,
114): Effect.Effect<ServerSettings, ServerSettingsError> =>
115 encodeServerSettings(settings).pipe(
116 Effect.flatMap(decodeServerSettings),
117 Effect.map(foldProviderInstanceEnabledFlags),
118 Effect.mapError(
119 (cause) =>
120 new ServerSettingsError({
121 settingsPath: "<memory>",
122 operation: "normalize",
123 cause,
124 }),
125 ),
126 );
127
128function providerEnvironmentSecretName(input: {
129 readonly instanceId: string;
130 readonly name: string;
131}): string {
132 return `provider-env-${Buffer.from(input.instanceId, "utf8").toString("base64url")}-${Buffer.from(input.name, "utf8").toString("base64url")}`;
133}
134
135function redactProviderEnvironmentVariable(
136 variable: ProviderInstanceEnvironmentVariable,
137): ProviderInstanceEnvironmentVariable {
138 if (!variable.sensitive) {
139 const { valueRedacted: _omit, ...rest } = variable;
140 return rest;
141 }
142 return {
143 ...variable,
144 value: "",
145 ...(variable.value.length > 0 || variable.valueRedacted ? { valueRedacted: true } : {}),
146 };
147}
148
149export function redactServerSettingsForClient(settings: ServerSettings): ServerSettings {
150 const providerInstances = Object.fromEntries(
151 Object.entries(settings.providerInstances).map(([instanceId, instance]) => [
152 instanceId,
153 instance.environment
154 ? {
155 ...instance,
156 environment: instance.environment.map(redactProviderEnvironmentVariable),
157 }
158 : instance,
159 ]),
160 );
161 return { ...settings, providerInstances };
162}
163
164export class ServerSettingsService extends Context.Service<
165 ServerSettingsService,
166 {
167 /** Start the settings runtime and attach file watching. */
168 readonly start: Effect.Effect<void, ServerSettingsError>;
169
170 /** Await settings runtime readiness. */
171 readonly ready: Effect.Effect<void, ServerSettingsError>;
172
173 /** Read the current settings. */
174 readonly getSettings: Effect.Effect<ServerSettings, ServerSettingsError>;
175
176 /** Patch settings and persist. Returns the new full settings object. */
177 readonly updateSettings: (
178 patch: ServerSettingsPatch,
179 ) => Effect.Effect<ServerSettings, ServerSettingsError>;
180
181 /** Stream of settings change events. */
182 readonly streamChanges: Stream.Stream<ServerSettings>;
183
184 /**
185 * Acquire a settings change subscription synchronously in the current
186 * fiber. Use this before reading a snapshot when changes between the
187 * snapshot and a lazily started stream must not be lost.
188 */
189 readonly subscribeChanges: Effect.Effect<Stream.Stream<ServerSettings>, never, Scope.Scope>;
190 }
191>()("t3/serverSettings/ServerSettingsService") {
192 /** @deprecated Import and use `layerTest` from this module. */
193 static readonly layerTest = (overrides: DeepPartial<ServerSettings> = {}) => layerTest(overrides);
194}
195
196const makeTest = (overrides: DeepPartial<ServerSettings> = {}) =>
197 Effect.gen(function* () {
198 const { automaticGitFetchInterval, providerHealthRefreshInterval, ...overridesForMerge } =
199 overrides;
200 const merged = deepMerge(DEFAULT_SERVER_SETTINGS, overridesForMerge);
201 const initialSettings = yield* normalizeServerSettings({
202 ...merged,
203 ...(automaticGitFetchInterval !== undefined
204 ? { automaticGitFetchInterval: automaticGitFetchInterval as Duration.Duration }
205 : {}),
206 ...(providerHealthRefreshInterval !== undefined
207 ? { providerHealthRefreshInterval: providerHealthRefreshInterval as Duration.Duration }
208 : {}),
209 });
210 const currentSettingsRef = yield* Ref.make<ServerSettings>(initialSettings);
211
212 return {
213 start: Effect.void,
214 ready: Effect.void,
215 getSettings: Ref.get(currentSettingsRef).pipe(Effect.map(resolveTextGenerationProvider)),
216 updateSettings: (patch) =>
217 Ref.get(currentSettingsRef).pipe(
218 Effect.map((currentSettings) => applyServerSettingsPatch(currentSettings, patch)),
219 Effect.flatMap(normalizeServerSettings),
220 Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
221 Effect.map(resolveTextGenerationProvider),
222 ),
223 streamChanges: Stream.empty,
224 subscribeChanges: Effect.succeed(Stream.empty),
225 } satisfies ServerSettingsService["Service"];
226 });
227
228export const layerTest = (overrides: DeepPartial<ServerSettings> = {}) =>
229 Layer.effect(ServerSettingsService, makeTest(overrides));
230
231const ServerSettingsJson = fromLenientJson(ServerSettings);
232const decodeServerSettingsJsonExit = Schema.decodeUnknownExit(ServerSettingsJson);
233
234function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings {
235 return isModelSelectionProviderEnabled(settings, settings.textGenerationModelSelection)
236 ? settings
237 : fallbackTextGenerationProvider(settings);
238}
239
240function fallbackTextGenerationProvider(settings: ServerSettings): ServerSettings {
241 const fallbackEntry = Object.entries(settings.providers).find(([, provider]) => provider.enabled);
242 const fallback = fallbackEntry ? ProviderDriverKind.make(fallbackEntry[0]) : undefined;
243 if (!fallback) {
244 return settings;
245 }
246
247 return {
248 ...settings,
249 textGenerationModelSelection: {
250 instanceId: ProviderInstanceId.make(fallback),
251 model:
252 DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback] ??
253 DEFAULT_MODEL_BY_PROVIDER[fallback] ??
254 DEFAULT_TEXT_GENERATION_MODEL,
255 } satisfies ModelSelection,
256 };
257}
258
259// Values under these keys are compared as a whole — never stripped field-by-field.
260const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set([
261 "backgroundActivity",
262 "automaticGitFetchInterval",
263 "providerHealthRefreshInterval",
264 "sourceControlWriterModelSelection",
265 "textGenerationModelSelection",
266]);
267
268function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {
269 if (Array.isArray(current) || Array.isArray(defaults)) {
270 return Equal.equals(current, defaults) ? undefined : current;
271 }
272
273 if (
274 current !== null &&
275 defaults !== null &&
276 typeof current === "object" &&
277 typeof defaults === "object"
278 ) {
279 const currentRecord = current as Record<string, unknown>;
280 const defaultsRecord = defaults as Record<string, unknown>;
281 const next: Record<string, unknown> = {};
282
283 for (const key of Object.keys(currentRecord)) {
284 if (ATOMIC_SETTINGS_KEYS.has(key)) {
285 if (!Equal.equals(currentRecord[key], defaultsRecord[key])) {
286 next[key] = currentRecord[key];
287 }
288 } else {
289 const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]);
290 if (stripped !== undefined) {
291 next[key] = stripped;
292 }
293 }
294 }
295
296 return Object.keys(next).length > 0 ? next : undefined;
297 }
298
299 return Object.is(current, defaults) ? undefined : current;
300}
301
302const make = Effect.gen(function* () {
303 const { settingsPath } = yield* ServerConfig.ServerConfig;
304 const fs = yield* FileSystem.FileSystem;
305 const pathService = yield* Path.Path;
306 const secretStore = yield* ServerSecretStore.ServerSecretStore;
307 const writeSemaphore = yield* Semaphore.make(1);
308 const cacheKey = "settings" as const;
309 const changesPubSub = yield* PubSub.unbounded<ServerSettings>();
310 const startedRef = yield* Ref.make(false);
311 const startedDeferred = yield* Deferred.make<void, ServerSettingsError>();
312 const watcherScope = yield* Scope.make("sequential");
313 yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
314
315 const emitChange = (settings: ServerSettings) =>
316 PubSub.publish(changesPubSub, settings).pipe(Effect.asVoid);
317
318 const readConfigExists = fs.exists(settingsPath).pipe(
319 Effect.mapError(
320 (cause) =>
321 new ServerSettingsError({
322 settingsPath,
323 operation: "check-exists",
324 cause,
325 }),
326 ),
327 );
328
329 const readRawConfig = fs.readFileString(settingsPath).pipe(
330 Effect.mapError(
331 (cause) =>
332 new ServerSettingsError({
333 settingsPath,
334 operation: "read-file",
335 cause,
336 }),
337 ),
338 );
339
340 const loadSettingsFromDisk = Effect.gen(function* () {
341 if (!(yield* readConfigExists)) {
342 return DEFAULT_SERVER_SETTINGS;
343 }
344
345 const raw = yield* readRawConfig;
346 const decoded = decodeServerSettingsJsonExit(raw);
347 if (decoded._tag === "Failure") {
348 yield* Effect.logWarning("failed to parse settings.json, using defaults", {
349 path: settingsPath,
350 issues: Cause.pretty(decoded.cause),
351 cause: decoded.cause,
352 });
353 return DEFAULT_SERVER_SETTINGS;
354 }
355 return foldProviderInstanceEnabledFlags(decoded.value);
356 });
357
358 const settingsCache = yield* Cache.make<typeof cacheKey, ServerSettings, ServerSettingsError>({
359 capacity: 1,
360 lookup: () => loadSettingsFromDisk,
361 });
362
363 const getSettingsFromCache = Cache.get(settingsCache, cacheKey);
364
365 const materializeProviderEnvironmentSecrets = (
366 settings: ServerSettings,
367 ): Effect.Effect<ServerSettings, ServerSettingsError> =>
368 Effect.gen(function* () {
369 const providerInstances: Record<string, ProviderInstanceConfig> = {
370 ...settings.providerInstances,
371 };
372 for (const [instanceId, instance] of Object.entries(settings.providerInstances)) {
373 if (!instance.environment) continue;
374 const environment: ProviderInstanceEnvironmentVariable[] = [];
375 for (const variable of instance.environment) {
376 if (!variable.sensitive || !variable.valueRedacted) {
377 environment.push(variable);
378 continue;
379 }
380 const secret = yield* secretStore
381 .get(providerEnvironmentSecretName({ instanceId, name: variable.name }))
382 .pipe(
383 Effect.mapError(
384 (cause) =>
385 new ServerSettingsError({
386 settingsPath,
387 operation: "read-secret",
388 providerInstanceId: instanceId,
389 environmentVariable: variable.name,
390 cause,
391 }),
392 ),
393 );
394 environment.push({
395 ...variable,
396 value: Option.isSome(secret) ? textDecoder.decode(secret.value) : "",
397 });
398 }
399 providerInstances[instanceId] = {
400 ...instance,
401 environment,
402 } satisfies ProviderInstanceConfig;
403 }
404 return {
405 ...settings,
406 providerInstances: providerInstances as ServerSettings["providerInstances"],
407 };
408 });
409
410 const materializeChanges = (changes: Stream.Stream<ServerSettings>) =>
411 changes.pipe(
412 Stream.mapEffect((settings) =>
413 materializeProviderEnvironmentSecrets(settings).pipe(
414 Effect.catch((error: ServerSettingsError) =>
415 Effect.logWarning("failed to materialize provider environment secrets", {
416 operation: error.operation,
417 providerInstanceId: error.providerInstanceId,
418 environmentVariable: error.environmentVariable,
419 cause: error.cause,
420 }).pipe(Effect.as(settings)),
421 ),
422 ),
423 ),
424 Stream.map(resolveTextGenerationProvider),
425 );
426
427 const persistProviderEnvironmentSecrets = (
428 current: ServerSettings,
429 next: ServerSettings,
430 ): Effect.Effect<ServerSettings, ServerSettingsError> =>
431 Effect.gen(function* () {
432 const providerInstances: Record<string, ProviderInstanceConfig> = {
433 ...next.providerInstances,
434 };
435
436 const nextSecretKeys = new Set<string>();
437 for (const [instanceId, instance] of Object.entries(next.providerInstances)) {
438 if (!instance.environment) continue;
439 const environment: ProviderInstanceEnvironmentVariable[] = [];
440 for (const variable of instance.environment) {
441 const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name });
442 if (!variable.sensitive) {
443 yield* secretStore.remove(secretName).pipe(
444 Effect.mapError(
445 (cause) =>
446 new ServerSettingsError({
447 settingsPath,
448 operation: "remove-secret",
449 providerInstanceId: instanceId,
450 environmentVariable: variable.name,
451 cause,
452 }),
453 ),
454 );
455 environment.push(redactProviderEnvironmentVariable(variable));
456 continue;
457 }
458
459 nextSecretKeys.add(secretName);
460 if (!variable.valueRedacted) {
461 if (variable.value.length > 0) {
462 yield* secretStore.set(secretName, textEncoder.encode(variable.value)).pipe(
463 Effect.mapError(
464 (cause) =>
465 new ServerSettingsError({
466 settingsPath,
467 operation: "write-secret",
468 providerInstanceId: instanceId,
469 environmentVariable: variable.name,
470 cause,
471 }),
472 ),
473 );
474 environment.push({ ...variable, value: "", valueRedacted: true });
475 } else {
476 yield* secretStore.remove(secretName).pipe(
477 Effect.mapError(
478 (cause) =>
479 new ServerSettingsError({
480 settingsPath,
481 operation: "remove-secret",
482 providerInstanceId: instanceId,
483 environmentVariable: variable.name,
484 cause,
485 }),
486 ),
487 );
488 const { valueRedacted: _omit, ...rest } = variable;
489 environment.push(rest);
490 }
491 continue;
492 }
493
494 environment.push(redactProviderEnvironmentVariable(variable));
495 }
496 providerInstances[instanceId] = {
497 ...instance,
498 environment,
499 } satisfies ProviderInstanceConfig;
500 }
501
502 for (const [instanceId, instance] of Object.entries(current.providerInstances)) {
503 for (const variable of instance.environment ?? []) {
504 if (!variable.sensitive) continue;
505 const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name });
506 if (nextSecretKeys.has(secretName)) continue;
507 yield* secretStore.remove(secretName).pipe(
508 Effect.mapError(
509 (cause) =>
510 new ServerSettingsError({
511 settingsPath,
512 operation: "remove-stale-secret",
513 providerInstanceId: instanceId,
514 environmentVariable: variable.name,
515 cause,
516 }),
517 ),
518 );
519 }
520 }
521
522 return {
523 ...next,
524 providerInstances: providerInstances as ServerSettings["providerInstances"],
525 };
526 });
527
528 const writeSettingsAtomically = Effect.fnUntraced(
529 function* (settings: ServerSettings) {
530 const sparseSettingsJson = yield* encodeServerSettingsJson(
531 stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {},
532 );
533
534 return yield* writeFileStringAtomically({
535 filePath: settingsPath,
536 contents: `${sparseSettingsJson}\n`,
537 }).pipe(
538 Effect.provideService(FileSystem.FileSystem, fs),
539 Effect.provideService(Path.Path, pathService),
540 );
541 },
542 Effect.mapError(
543 (cause) =>
544 new ServerSettingsError({
545 settingsPath,
546 operation: "write-file",
547 cause,
548 }),
549 ),
550 );
551
552 const revalidateAndEmit = writeSemaphore.withPermits(1)(
553 Effect.gen(function* () {
554 yield* Cache.invalidate(settingsCache, cacheKey);
555 const settings = yield* getSettingsFromCache;
556 yield* emitChange(settings);
557 }),
558 );
559
560 const startWatcher = Effect.gen(function* () {
561 const settingsDir = pathService.dirname(settingsPath);
562 const settingsFile = pathService.basename(settingsPath);
563 const settingsPathResolved = pathService.resolve(settingsPath);
564
565 yield* fs.makeDirectory(settingsDir, { recursive: true }).pipe(
566 Effect.mapError(
567 (cause) =>
568 new ServerSettingsError({
569 settingsPath,
570 operation: "prepare-directory",
571 cause,
572 }),
573 ),
574 );
575
576 const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
577
578 // Debounce watch events so the file is fully written before we read it.
579 // Editors emit multiple events per save (truncate, write, rename) and
580 // `fs.watch` can fire before the content has been flushed to disk.
581 const debouncedSettingsEvents = fs.watch(settingsDir).pipe(
582 Stream.filter((event) => {
583 return (
584 event.path === settingsFile ||
585 event.path === settingsPath ||
586 pathService.resolve(settingsDir, event.path) === settingsPathResolved
587 );
588 }),
589 Stream.debounce(Duration.millis(100)),
590 );
591
592 yield* Stream.runForEach(debouncedSettingsEvents, () => revalidateAndEmitSafely).pipe(
593 Effect.ignoreCause({ log: true }),
594 Effect.forkIn(watcherScope),
595 Effect.asVoid,
596 );
597 });
598
599 const start = Effect.gen(function* () {
600 const shouldStart = yield* Ref.modify(startedRef, (started) => [!started, true]);
601 if (!shouldStart) {
602 return yield* Deferred.await(startedDeferred);
603 }
604
605 const startup = Effect.gen(function* () {
606 yield* startWatcher;
607 yield* Cache.invalidate(settingsCache, cacheKey);
608 yield* getSettingsFromCache;
609 });
610
611 const startupExit = yield* Effect.exit(startup);
612 if (startupExit._tag === "Failure") {
613 yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);
614 return yield* Effect.failCause(startupExit.cause);
615 }
616
617 yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
618 });
619
620 return {
621 start,
622 ready: Deferred.await(startedDeferred),
623 getSettings: getSettingsFromCache.pipe(
624 Effect.flatMap(materializeProviderEnvironmentSecrets),
625 Effect.map(resolveTextGenerationProvider),
626 ),
627 updateSettings: (patch) =>
628 writeSemaphore.withPermits(1)(
629 Effect.gen(function* () {
630 const current = yield* getSettingsFromCache;
631 const nextPersisted = yield* persistProviderEnvironmentSecrets(
632 current,
633 applyServerSettingsPatch(current, patch),
634 );
635 const next = yield* normalizeServerSettings(nextPersisted);
636 yield* writeSettingsAtomically(next);
637 yield* Cache.set(settingsCache, cacheKey, next);
638 yield* emitChange(next);
639 const materialized = yield* materializeProviderEnvironmentSecrets(next);
640 return resolveTextGenerationProvider(materialized);
641 }),
642 ),
643 get streamChanges() {
644 return materializeChanges(Stream.fromPubSub(changesPubSub));
645 },
646 get subscribeChanges() {
647 return PubSub.subscribe(changesPubSub).pipe(
648 Effect.map((subscription) => materializeChanges(Stream.fromSubscription(subscription))),
649 );
650 },
651 } satisfies ServerSettingsService["Service"];
652});
653
654export const layer = Layer.effect(ServerSettingsService, make);