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

serverSettings.ts

769 lines27.1 KB

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