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

serverSettings.ts

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