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

serverSettings.ts

1,243 lines46.6 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_SERVER_SETTINGS,
15 ModelSelection,
16 ProjectId,
17 ProjectScript,
18 ProjectSettingsOverrides,
19 type ProviderInstanceConfig,
20 type ProviderInstanceMutation,
21 defaultInstanceIdForDriver,
22 isProviderDriverKind,
23 ProviderDriverKind,
24 ProviderInstanceId,
25 resolveProviderInstanceEnabled,
26 ResponseStreamingMode,
27 ServerSettings,
28 ServerSettingsError,
29 type ServerSettingsPatch,
30} from "@t3tools/contracts";
31import * as Cache from "effect/Cache";
32import * as Cause from "effect/Cause";
33import * as Context from "effect/Context";
34import * as Deferred from "effect/Deferred";
35import * as Duration from "effect/Duration";
36import * as Equal from "effect/Equal";
37import * as Effect from "effect/Effect";
38import * as Exit from "effect/Exit";
39import * as FileSystem from "effect/FileSystem";
40import * as Layer from "effect/Layer";
41import * as Option from "effect/Option";
42import * as Path from "effect/Path";
43import * as PubSub from "effect/PubSub";
44import * as Ref from "effect/Ref";
45import * as Schema from "effect/Schema";
46import * as SchemaTransformation from "effect/SchemaTransformation";
47import * as Semaphore from "effect/Semaphore";
48import * as Scope from "effect/Scope";
49import * as Stream from "effect/Stream";
50import * as SqlClient from "effect/sql/SqlClient";
51import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
52import { resolveSymlinkTarget } from "@t3tools/shared/symlink";
53import * as ServerConfig from "./config.ts";
54import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
55import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
56import {
57 applyServerSettingsPatch,
58 deriveLegacyProjectOverrides,
59 fallbackTextGenerationModelSelection,
60 isModelSelectionProviderEnabled,
61} from "@t3tools/shared/serverSettings";
62import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
63import {
64 readSecretFieldValues,
65 sourceControlHostSecretName,
66} from "./sourceControl/sourceControlHostSecrets.ts";
67​
68import { mapSettingsSecrets, SECRET_REDACTED, type SettingsSecret } from "./settingsSecrets.ts";
69​
70export {
71 resolveReviewGuideModelSelection,
72 resolveSourceControlWriterModelSelection,
73} from "@t3tools/shared/serverSettings";
74​
75const encodeServerSettings = Schema.encodeEffect(ServerSettings);
76const encodeServerSettingsJson = Schema.encodeUnknownEffect(fromJsonStringPretty(ServerSettings));
77const decodeServerSettings = Schema.decodeUnknownEffect(ServerSettings);
78​
79const textEncoder = new TextEncoder();
80const textDecoder = new TextDecoder();
81​
82/**
83 * Fold the legacy in-config `enabled` flag into the envelope-level
84 * `ProviderInstanceConfig.enabled` and strip it from the config blob, so
85 * explicit provider instances carry exactly one enabled flag. Old settings
86 * files can hold both flags with conflicting values; an explicit false on
87 * either side wins so a user's disable is never silently undone. Runs on
88 * every load and update — the file converges on the next write.
89 */
90const foldProviderInstanceEnabledFlags = (settings: ServerSettings): ServerSettings => {
91 let changed = false;
92 const providerInstances: Record<string, ProviderInstanceConfig> = {};
93 for (const [instanceId, instance] of Object.entries(settings.providerInstances)) {
94 const config = instance.config;
95 // Only fold boolean flags: a malformed `enabled` (e.g. `"false"`) must
96 // stay in the blob so driver schema validation flags it instead of the
97 // fold silently repairing the config.
98 if (
99 config === null ||
100 typeof config !== "object" ||
101 Array.isArray(config) ||
102 typeof (config as { readonly enabled?: unknown }).enabled !== "boolean"
103 ) {
104 providerInstances[instanceId] = instance;
105 continue;
106 }
107 const { enabled: configEnabled, ...restConfig } = config as Record<string, unknown> & {
108 readonly enabled: boolean;
109 };
110 const resolved =
111 instance.enabled === false || configEnabled === false
112 ? false
113 : (instance.enabled ?? configEnabled);
114 changed = true;
115 providerInstances[instanceId] = {
116 ...instance,
117 enabled: resolved,
118 config: restConfig,
119 } satisfies ProviderInstanceConfig;
120 }
121 if (!changed) {
122 return settings;
123 }
124 return {
125 ...settings,
126 providerInstances: providerInstances as ServerSettings["providerInstances"],
127 };
128};
129​
130const normalizeServerSettings = (
131 settings: ServerSettings,
132): Effect.Effect<ServerSettings, ServerSettingsError> =>
133 encodeServerSettings(settings).pipe(
134 Effect.flatMap(decodeServerSettings),
135 Effect.map(foldProviderInstanceEnabledFlags),
136 Effect.map((next) => ({ ...next, ...deriveLegacyProjectOverrides(next) })),
137 Effect.mapError(
138 (cause) =>
139 new ServerSettingsError({
140 settingsPath: "<memory>",
141 operation: "normalize",
142 cause,
143 }),
144 ),
145 );
146​
147export function redactServerSettingsForClient(settings: ServerSettings): ServerSettings {
148 return mapSettingsSecrets(settings, (secret) =>
149 secret.sensitive
150 ? { value: "", redacted: secret.redacted || secret.value.length > 0 }
151 : { value: secret.value, redacted: false },
152 );
154​
155export function applyProviderInstanceMutation(
156 settings: ServerSettings,
157 mutation: ProviderInstanceMutation,
158): ServerSettings {
159 const providerInstances = { ...settings.providerInstances };
160 if (mutation.operation === "upsert" || mutation.operation === "create") {
161 providerInstances[mutation.instanceId] = mutation.instance;
162 } else {
163 delete providerInstances[mutation.instanceId];
164 }
165 return { ...settings, providerInstances };
167​
168function ensureProviderInstanceMutationAllowed(
169 settings: ServerSettings,
170 mutation: ProviderInstanceMutation,
171 settingsPath: string,
172): Effect.Effect<void, ServerSettingsError> {
173 if (
174 mutation.operation === "create" &&
175 settings.providerInstances[mutation.instanceId] !== undefined
176 ) {
177 return Effect.fail(
178 new ServerSettingsError({
179 settingsPath,
180 operation: "create-provider-instance",
181 providerInstanceId: mutation.instanceId,
182 }),
183 );
184 }
185 return Effect.void;
187​
188export class ServerSettingsService extends Context.Service<
189 ServerSettingsService,
190 {
191 /** Start the settings runtime and attach file watching. */
192 readonly start: Effect.Effect<void, ServerSettingsError>;
193​
194 /** Await settings runtime readiness. */
195 readonly ready: Effect.Effect<void, ServerSettingsError>;
196​
197 /** Read the current settings. */
198 readonly getSettings: Effect.Effect<ServerSettings, ServerSettingsError>;
199​
200 /** Patch settings and persist. Returns the new full settings object. */
201 readonly updateSettings: (
202 patch: ServerSettingsPatch,
203 ) => Effect.Effect<ServerSettings, ServerSettingsError>;
204​
205 /** Apply a patch and one provider-instance mutation against the same latest settings snapshot. */
206 readonly updateProviderInstance: (
207 mutation: ProviderInstanceMutation,
208 patch?: ServerSettingsPatch,
209 ) => Effect.Effect<ServerSettings, ServerSettingsError>;
210​
211 /** Run an effect against a settings snapshot while settings writes are paused. */
212 readonly withSettingsSnapshot: <A, E, R>(
213 use: (settings: ServerSettings) => Effect.Effect<A, E, R>,
214 ) => Effect.Effect<A, E | ServerSettingsError, R>;
215​
216 /** Stream of settings change events. */
217 readonly streamChanges: Stream.Stream<ServerSettings>;
218​
219 /**
220 * Acquire a settings change subscription synchronously in the current
221 * fiber. Use this before reading a snapshot when changes between the
222 * snapshot and a lazily started stream must not be lost.
223 */
224 readonly subscribeChanges: Effect.Effect<Stream.Stream<ServerSettings>, never, Scope.Scope>;
225 }
226>()("t3/serverSettings/ServerSettingsService") {
227 /** @deprecated Import and use `layerTest` from this module. */
228 static readonly layerTest = (overrides: DeepPartial<ServerSettings> = {}) => layerTest(overrides);
230​
231const makeTest = (overrides: DeepPartial<ServerSettings> = {}) =>
232 Effect.gen(function* () {
233 const { automaticGitFetchInterval, providerHealthRefreshInterval, ...overridesForMerge } =
234 overrides;
235 const merged = deepMerge(DEFAULT_SERVER_SETTINGS, overridesForMerge);
236 const initialSettings = yield* normalizeServerSettings({
237 ...merged,
238 ...(automaticGitFetchInterval !== undefined
239 ? { automaticGitFetchInterval: automaticGitFetchInterval as Duration.Duration }
240 : {}),
241 ...(providerHealthRefreshInterval !== undefined
242 ? { providerHealthRefreshInterval: providerHealthRefreshInterval as Duration.Duration }
243 : {}),
244 });
245 const currentSettingsRef = yield* Ref.make<ServerSettings>(initialSettings);
246 const writeSemaphore = yield* Semaphore.make(1);
247 const getSettings = Ref.get(currentSettingsRef).pipe(Effect.map(resolveTextGenerationProvider));
248​
249 const updateTestSettings = (
250 update: (current: ServerSettings) => Effect.Effect<ServerSettings, ServerSettingsError>,
251 ): Effect.Effect<ServerSettings, ServerSettingsError> =>
252 writeSemaphore.withPermits(1)(
253 Ref.get(currentSettingsRef).pipe(
254 Effect.flatMap(update),
255 Effect.flatMap(normalizeServerSettings),
256 Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
257 Effect.map(resolveTextGenerationProvider),
258 ),
259 );
260​
261 return {
262 start: Effect.void,
263 ready: Effect.void,
264 getSettings,
265 updateSettings: (patch) =>
266 updateTestSettings((currentSettings) =>
267 Effect.succeed(applyServerSettingsPatch(currentSettings, patch)),
268 ),
269 updateProviderInstance: (mutation, patch = {}) =>
270 updateTestSettings((currentSettings) =>
271 Effect.gen(function* () {
272 yield* ensureProviderInstanceMutationAllowed(
273 currentSettings,
274 mutation,
275 "test settings",
276 );
277 const patched = applyServerSettingsPatch(currentSettings, patch);
278 return applyProviderInstanceMutation(patched, mutation);
279 }),
280 ),
281 withSettingsSnapshot: (use) =>
282 writeSemaphore.withPermits(1)(getSettings.pipe(Effect.flatMap(use))),
283 streamChanges: Stream.empty,
284 subscribeChanges: Effect.succeed(Stream.empty),
285 } satisfies ServerSettingsService["Service"];
286 });
287​
288export const layerTest = (overrides: DeepPartial<ServerSettings> = {}) =>
289 Layer.effect(ServerSettingsService, makeTest(overrides));
290​
291// Migrate saved token delivery without accepting it in settings writes or
292// letting one retired value reset the rest of the environment's settings.
293const PersistedResponseStreamingMode = Schema.Union([
294 ResponseStreamingMode,
295 Schema.Literal("token"),
296]).pipe(
297 Schema.decodeTo(
298 ResponseStreamingMode,
299 SchemaTransformation.transform({
300 decode: (mode) => (mode === "token" ? "paragraph" : mode),
301 encode: (mode) => mode,
302 }),
303 ),
304);
305const ServerSettingsJson = fromLenientJson(
306 Schema.Struct({
307 ...ServerSettings.fields,
308 responseStreamingMode: PersistedResponseStreamingMode.pipe(
309 Schema.withDecodingDefault(Effect.succeed("paragraph" as const)),
310 ),
311 projectSettingsOverrides: Schema.Record(
312 ProjectId,
313 Schema.Struct({
314 ...ProjectSettingsOverrides.fields,
315 responseStreamingMode: Schema.optionalKey(PersistedResponseStreamingMode),
316 }),
317 ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
318 }),
319);
320const decodeServerSettingsJsonExit = Schema.decodeUnknownExit(ServerSettingsJson);
321/**
322 * The retired `providers.<kind>` map, read without its old schemas. Before
323 * `providerInstances` existed each built-in driver had one blob there; it
324 * now only feeds `migrateLegacyProviderSettings`.
325 */
326const LegacyProviderSettingsJson = fromLenientJson(
327 Schema.Struct({
328 providers: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),
329 // Retired for `sourceControlHosts`; read only by `migrateLegacySourceControlSettings`.
330 bitbucket: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),
331 github: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),
332 }),
333);
334const decodeLegacyProviderSettingsJsonExit = Schema.decodeUnknownExit(LegacyProviderSettingsJson);
335​
336/** The secret store names the retired `bitbucket` and `github` keys kept their tokens under. */
337const LEGACY_BITBUCKET_SECRET_NAMES: Readonly<Record<string, string>> = {
338 accessToken: "bitbucket-access-token",
339 apiToken: "bitbucket-api-token",
340};
341const legacyGitHubTokenSecretName = (host: string) =>
342 `github-token-${Buffer.from(host.trim().toLowerCase(), "utf8").toString("base64url")}`;
343​
344/**
345 * Folds the retired `bitbucket` and `github` keys into `sourceControlHosts`, unless the new key
346 * already holds that host. Returns the secret store entries to copy to their new names.
347 */
348function migrateLegacySourceControlSettings(
349 settings: ServerSettings,
350 legacy: {
351 readonly bitbucket?: Readonly<Record<string, unknown>> | undefined;
352 readonly github?: Readonly<Record<string, unknown>> | undefined;
353 },
354): {
355 readonly settings: ServerSettings;
356 readonly secretMoves: ReadonlyArray<{ readonly from: string; readonly to: string }>;
357} {
358 const sourceControlHosts = { ...settings.sourceControlHosts };
359 const secretMoves: Array<{ readonly from: string; readonly to: string }> = [];
360 if (legacy.bitbucket !== undefined && sourceControlHosts.bitbucket === undefined) {
361 sourceControlHosts.bitbucket = legacy.bitbucket;
362 for (const [field, from] of Object.entries(LEGACY_BITBUCKET_SECRET_NAMES)) {
363 if (legacy.bitbucket[field] !== SECRET_REDACTED) continue;
364 secretMoves.push({
365 from,
366 to: sourceControlHostSecretName({ kind: "bitbucket", field, serverHost: null }),
367 });
368 }
369 }
370 if (legacy.github !== undefined && sourceControlHosts.github === undefined) {
371 sourceControlHosts.github = legacy.github;
372 for (const [serverHost, value] of readSecretFieldValues(legacy.github.tokens)) {
373 if (serverHost === null || value !== SECRET_REDACTED) continue;
374 secretMoves.push({
375 from: legacyGitHubTokenSecretName(serverHost),
376 to: sourceControlHostSecretName({ kind: "github", field: "tokens", serverHost }),
377 });
378 }
379 }
380 return { settings: { ...settings, sourceControlHosts }, secretMoves };
382​
383// Drivers that start disabled, so a session in the history means the user
384// turned them on before the instance kept an explicit flag.
385const HISTORY_RESTORED_DRIVERS: ReadonlySet<ProviderDriverKind> = new Set(
386 ["cursor", "grok", "opencode"].map((driver) => ProviderDriverKind.make(driver)),
387);
388​
389/**
390 * Move each customized legacy `providers.<kind>` blob into the driver's
391 * default `providerInstances` slot. An explicit instance already in that slot
392 * wins. Blobs that match a fresh install (empty, or only an `enabled` flag
393 * equal to the driver default) carry nothing and are dropped.
394 *
395 * A cursor/grok/opencode slot without an `enabled` flag is enabled when
396 * provider history shows the driver was used, which is how those drivers
397 * were opted into before they had an explicit flag. Callers run this only
398 * while the settings file still has the retired map, so it happens once.
399 */
400function migrateLegacyProviderSettings(
401 settings: ServerSettings,
402 legacyProviders: Readonly<Record<string, unknown>>,
403 providerHistory: ReadonlyArray<{
404 readonly providerName: string;
405 readonly providerInstanceId: string | null;
406 }>,
407): ServerSettings {
408 // History rows are raw SQL text; compare them as strings.
409 const usedProviders = new Set<string>(providerHistory.map(({ providerName }) => providerName));
410 const usedProviderInstances = new Set<string>(
411 providerHistory.map(
412 ({ providerName, providerInstanceId }) => providerInstanceId ?? providerName,
413 ),
414 );
415​
416 const providerInstances: Record<ProviderInstanceId, ProviderInstanceConfig> = {};
417 for (const [instanceId, instance] of Object.entries(settings.providerInstances) as Array<
418 [ProviderInstanceId, ProviderInstanceConfig]
419 >) {
420 providerInstances[instanceId] =
421 instance.enabled === undefined &&
422 HISTORY_RESTORED_DRIVERS.has(instance.driver) &&
423 usedProviderInstances.has(instanceId)
424 ? { ...instance, enabled: true }
425 : instance;
426 }
427​
428 // History restores a never-configured cursor/grok/opencode slot too.
429 const legacyEntries = new Map(Object.entries(legacyProviders));
430 for (const driver of HISTORY_RESTORED_DRIVERS) {
431 if (!legacyEntries.has(driver)) legacyEntries.set(driver, {});
432 }
433 for (const [kind, blob] of legacyEntries) {
434 if (!isProviderDriverKind(kind) || blob === null || typeof blob !== "object") continue;
435 if (Array.isArray(blob)) continue;
436 const driver = kind;
437 const instanceId = defaultInstanceIdForDriver(driver);
438 if (Object.hasOwn(providerInstances, instanceId)) continue;
439​
440 const { enabled: rawEnabled, ...config } = blob as Record<string, unknown>;
441 const explicitEnabled = typeof rawEnabled === "boolean" ? rawEnabled : undefined;
442 const enabled =
443 explicitEnabled ??
444 (HISTORY_RESTORED_DRIVERS.has(driver) && usedProviders.has(driver) ? true : undefined);
445 const driverDefault = resolveProviderInstanceEnabled({ driver, config: {} });
446 if (Object.keys(config).length === 0 && (enabled === undefined || enabled === driverDefault)) {
447 continue;
448 }
449 providerInstances[instanceId] = {
450 driver,
451 ...(enabled === undefined ? {} : { enabled }),
452 config,
453 } satisfies ProviderInstanceConfig;
454 }
455​
456 return {
457 ...settings,
458 providerInstances,
459 };
461​
462const ACP_REGISTRY_DRIVER = ProviderDriverKind.make("acpRegistry");
463​
464/** ACP Registry instances reject every application text-generation operation. */
465function selectionSupportsTextGeneration(
466 settings: ServerSettings,
467 selection: ModelSelection,
468): boolean {
469 return settings.providerInstances[selection.instanceId]?.driver !== ACP_REGISTRY_DRIVER;
471​
472function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings {
473 return isModelSelectionProviderEnabled(settings, settings.textGenerationModelSelection) &&
474 selectionSupportsTextGeneration(settings, settings.textGenerationModelSelection)
475 ? settings
476 : fallbackTextGenerationProvider(settings);
478​
479function fallbackTextGenerationProvider(settings: ServerSettings): ServerSettings {
480 // A slot without an explicit instance uses its driver's default enabled state.
481 const fallback = fallbackTextGenerationModelSelection(
482 settings.providerInstances,
483 (instanceId, driver) =>
484 resolveProviderInstanceEnabled(
485 settings.providerInstances[instanceId] ?? { driver, config: {} },
486 ),
487 );
488 return fallback === null ? settings : { ...settings, textGenerationModelSelection: fallback };
490​
491// Values under these keys are compared as a whole — never stripped field-by-field.
492const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set([
493 "backgroundActivity",
494 "automaticGitFetchInterval",
495 "providerHealthRefreshInterval",
496 "sourceControlWriterModelSelection",
497 "reviewGuideModelSelection",
498 "textGenerationModelSelection",
499 "pullRequestMergeMethod",
500]);
501​
502function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {
503 if (Array.isArray(current) || Array.isArray(defaults)) {
504 return Equal.equals(current, defaults) ? undefined : current;
505 }
506​
507 if (
508 current !== null &&
509 defaults !== null &&
510 typeof current === "object" &&
511 typeof defaults === "object"
512 ) {
513 const currentRecord = current as Record<string, unknown>;
514 const defaultsRecord = defaults as Record<string, unknown>;
515 const next: Record<string, unknown> = {};
516​
517 for (const key of Object.keys(currentRecord)) {
518 if (ATOMIC_SETTINGS_KEYS.has(key)) {
519 if (!Equal.equals(currentRecord[key], defaultsRecord[key])) {
520 next[key] = currentRecord[key];
521 }
522 } else {
523 const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]);
524 if (stripped !== undefined) {
525 next[key] = stripped;
526 }
527 }
528 }
529​
530 return Object.keys(next).length > 0 ? next : undefined;
531 }
532​
533 return Object.is(current, defaults) ? undefined : current;
535​
536const decodeProjectScriptsJson = Schema.decodeUnknownOption(
537 Schema.fromJsonString(Schema.Array(ProjectScript)),
538);
539const decodeModelSelectionJson = Schema.decodeUnknownOption(
540 Schema.fromJsonString(Schema.NullOr(ModelSelection)),
541);
542​
543interface LegacyProjectSettingsRow {
544 readonly projectId: string;
545 readonly defaultModelSelection: string | null;
546 readonly defaultThreadEnvMode: string | null;
547 readonly autoPull: number;
548 readonly scripts: string;
550​
551/**
552 * One-time fold of the legacy per-project fields into `projectSettingsOverrides`:
553 * the three `project*Overrides` maps and the settings columns on the project
554 * aggregate. Keys already present in the generic record win. Marked with
555 * `projectSettingsFolded` so a later reset in the UI survives restarts.
556 */
557function foldLegacyProjectSettings(
558 settings: ServerSettings,
559 rows: ReadonlyArray<LegacyProjectSettingsRow>,
560): ServerSettings {
561 if (settings.projectSettingsFolded) return settings;
562 // Nothing to fold yet (fresh install): leave the marker off so the file
563 // stays sparse, and check again on the next load.
564 if (
565 rows.length === 0 &&
566 Object.keys(settings.projectAgentBrowserAccessOverrides).length === 0 &&
567 Object.keys(settings.projectAutoPullOverrides).length === 0 &&
568 Object.keys(settings.projectScriptOverrides).length === 0
569 ) {
570 return settings;
571 }
572 const entries: Record<string, ProjectSettingsOverrides> = {
573 ...settings.projectSettingsOverrides,
574 };
575 const set = <K extends keyof ProjectSettingsOverrides>(
576 projectId: string,
577 key: K,
578 value: ProjectSettingsOverrides[K] | undefined,
579 ) => {
580 if (value === undefined) return;
581 const entry = entries[projectId] ?? {};
582 if (Object.hasOwn(entry, key)) return;
583 entries[projectId] = { ...entry, [key]: value };
584 };
585 for (const [projectId, value] of Object.entries(settings.projectAgentBrowserAccessOverrides)) {
586 set(projectId, "enableAgentBrowserAccess", value);
587 }
588 for (const [projectId, value] of Object.entries(settings.projectAutoPullOverrides)) {
589 set(projectId, "defaultAutoPull", value);
590 }
591 // A stored null meant "reset to machine defaults", which is now plain
592 // inheritance; the project's own aggregate scripts must not resurface.
593 const resetScripts = new Set<string>();
594 for (const [projectId, value] of Object.entries(settings.projectScriptOverrides)) {
595 if (value === null) resetScripts.add(projectId);
596 else set(projectId, "defaultProjectScripts", value);
597 }
598 for (const row of rows) {
599 const model = decodeModelSelectionJson(row.defaultModelSelection ?? "null");
600 if (Option.isSome(model) && model.value !== null) {
601 set(row.projectId, "defaultModelSelection", model.value);
602 }
603 if (row.defaultThreadEnvMode === "local" || row.defaultThreadEnvMode === "worktree") {
604 set(row.projectId, "defaultThreadEnvMode", row.defaultThreadEnvMode);
605 }
606 if (row.autoPull === 1) set(row.projectId, "defaultAutoPull", true);
607 const scripts = decodeProjectScriptsJson(row.scripts);
608 if (Option.isSome(scripts) && scripts.value.length > 0 && !resetScripts.has(row.projectId)) {
609 set(row.projectId, "defaultProjectScripts", scripts.value);
610 }
611 }
612 const projectSettingsOverrides = Object.fromEntries(
613 Object.entries(entries).filter(([, entry]) => Object.keys(entry).length > 0),
614 );
615 return {
616 ...settings,
617 projectSettingsOverrides,
618 projectSettingsFolded: true,
619 ...deriveLegacyProjectOverrides({ projectSettingsOverrides }),
620 };
622​
623const make = Effect.gen(function* () {
624 const { settingsPath } = yield* ServerConfig.ServerConfig;
625 const fs = yield* FileSystem.FileSystem;
626 const pathService = yield* Path.Path;
627 const secretStore = yield* ServerSecretStore.ServerSecretStore;
628 const sql = yield* SqlClient.SqlClient;
629 const writeSemaphore = yield* Semaphore.make(1);
630 const cacheKey = "settings" as const;
631 const changesPubSub = yield* PubSub.unbounded<ServerSettings>();
632 const startedRef = yield* Ref.make(false);
633 const startedDeferred = yield* Deferred.make<void, ServerSettingsError>();
634 const watcherScope = yield* Scope.make("sequential");
635 yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
636​
637 const emitChange = (settings: ServerSettings) =>
638 PubSub.publish(changesPubSub, settings).pipe(Effect.asVoid);
639​
640 const readConfigExists = fs.exists(settingsPath).pipe(
641 Effect.mapError(
642 (cause) =>
643 new ServerSettingsError({
644 settingsPath,
645 operation: "check-exists",
646 cause,
647 }),
648 ),
649 );
650​
651 const readRawConfig = fs.readFileString(settingsPath).pipe(
652 Effect.mapError(
653 (cause) =>
654 new ServerSettingsError({
655 settingsPath,
656 operation: "read-file",
657 cause,
658 }),
659 ),
660 );
661​
662 const writeSettingsAtomically = Effect.fnUntraced(
663 function* (settings: ServerSettings) {
664 const sparseSettingsJson = yield* encodeServerSettingsJson(
665 stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {},
666 );
667​
668 return yield* writeFileStringAtomically({
669 filePath: settingsPath,
670 contents: `${sparseSettingsJson}\n`,
671 }).pipe(
672 Effect.provideService(FileSystem.FileSystem, fs),
673 Effect.provideService(Path.Path, pathService),
674 );
675 },
676 Effect.mapError(
677 (cause) =>
678 new ServerSettingsError({
679 settingsPath,
680 operation: "write-file",
681 cause,
682 }),
683 ),
684 );
685​
686 /**
687 * Migrate plaintext schema-declared credentials on load. Failed moves stay usable from
688 * the file and are retried next time; client redaction does not depend on migration.
689 */
690 const moveInlineSettingsSecrets = (settings: ServerSettings) =>
691 Effect.gen(function* () {
692 const pending: SettingsSecret[] = [];
693 mapSettingsSecrets(settings, (secret) => {
694 if (secret.kind === "field" && !secret.redacted && secret.value.length > 0) {
695 pending.push(secret);
696 }
697 return secret;
698 });
699 const moved = new Set<string>();
700 for (const secret of pending) {
701 const stored = yield* secretStore
702 .set(secret.secretName, textEncoder.encode(secret.value))
703 .pipe(
704 Effect.as(true),
705 Effect.catch(() =>
706 Effect.logWarning("failed to move a settings secret into the secret store").pipe(
707 Effect.as(false),
708 ),
709 ),
710 );
711 if (stored) moved.add(secret.secretName);
712 }
713 if (moved.size === 0) return settings;
714 return mapSettingsSecrets(settings, (secret) =>
715 moved.has(secret.secretName) ? { value: "", redacted: true } : secret,
716 );
717 });
718​
719 const loadSettingsFromDisk = Effect.gen(function* () {
720 let settings = DEFAULT_SERVER_SETTINGS;
721 let legacyProviders: Readonly<Record<string, unknown>> | undefined;
722 let legacySourceControl: Parameters<typeof migrateLegacySourceControlSettings>[1] = {};
723 // A file that failed to decode must stay on disk for the user to repair;
724 // the fold below only writes when it started from the file's real contents.
725 let settingsFileTrusted = true;
726​
727 if (yield* readConfigExists) {
728 const raw = yield* readRawConfig;
729 const decoded = decodeServerSettingsJsonExit(raw);
730 const legacySettings = decodeLegacyProviderSettingsJsonExit(raw);
731 if (legacySettings._tag === "Success") {
732 legacyProviders = legacySettings.value.providers;
733 legacySourceControl = {
734 bitbucket: legacySettings.value.bitbucket,
735 github: legacySettings.value.github,
736 };
737 }
738 if (decoded._tag === "Failure" || legacySettings._tag === "Failure") {
739 const failure = decoded._tag === "Failure" ? decoded : legacySettings;
740 settingsFileTrusted = false;
741 // The file may hold an opt-out we can no longer read; never resume threads on a guess.
742 settings = { ...DEFAULT_SERVER_SETTINGS, continueThreadsAfterServerUpdate: false };
743 if (failure._tag === "Failure") {
744 yield* Effect.logWarning("failed to parse settings.json, using defaults", {
745 path: settingsPath,
746 issues: Cause.pretty(failure.cause),
747 cause: failure.cause,
748 });
749 }
750 } else {
751 settings = decoded.value;
752 }
753 }
754​
755 const providerHistory = yield* sql<{
756 readonly providerName: string;
757 readonly providerInstanceId: string | null;
758 }>`
759 SELECT DISTINCT
760 provider_name AS "providerName",
761 provider_instance_id AS "providerInstanceId"
762 FROM projection_thread_sessions
763 WHERE provider_name IN ('cursor', 'grok', 'opencode')
764 UNION
765 SELECT DISTINCT
766 provider_name AS "providerName",
767 provider_instance_id AS "providerInstanceId"
768 FROM provider_session_runtime
769 WHERE provider_name IN ('cursor', 'grok', 'opencode')
770 `.pipe(
771 Effect.mapError(
772 (cause) =>
773 new ServerSettingsError({
774 settingsPath,
775 operation: "read-provider-history",
776 cause,
777 }),
778 ),
779 );
780​
781 const legacyProjectRows =
782 settings.projectSettingsFolded || !settingsFileTrusted
783 ? []
784 : yield* sql<LegacyProjectSettingsRow>`
785 SELECT
786 project_id AS "projectId",
787 default_model_selection_json AS "defaultModelSelection",
788 default_thread_env_mode AS "defaultThreadEnvMode",
789 auto_pull AS "autoPull",
790 scripts_json AS "scripts"
791 FROM projection_projects
792 WHERE deleted_at IS NULL
793 `.pipe(
794 Effect.mapError(
795 (cause) =>
796 new ServerSettingsError({
797 settingsPath,
798 operation: "read-project-settings",
799 cause,
800 }),
801 ),
802 );
803​
804 const loaded = foldProviderInstanceEnabledFlags(
805 legacyProviders === undefined
806 ? settings
807 : migrateLegacyProviderSettings(settings, legacyProviders, providerHistory),
808 );
809 const folded = settingsFileTrusted
810 ? foldLegacyProjectSettings(loaded, legacyProjectRows)
811 : loaded;
812 // Copied, not moved: the old entry is removed only after the new file is written. A token
813 // that cannot be read or copied leaves the retired keys in place, so the migration runs again
814 // on the next load instead of dropping it.
815 const legacySecretsCopied = yield* Effect.forEach(
816 settingsFileTrusted
817 ? migrateLegacySourceControlSettings(folded, legacySourceControl).secretMoves
818 : [],
819 (move) =>
820 secretStore.get(move.from).pipe(
821 Effect.flatMap((secret) =>
822 Option.isNone(secret) ? Effect.void : secretStore.set(move.to, secret.value),
823 ),
824 Effect.as(true),
825 Effect.catch(() =>
826 Effect.logWarning("failed to copy a source control secret to its new name", {
827 secretName: move.to,
828 }).pipe(Effect.as(false)),
829 ),
830 ),
831 ).pipe(Effect.map((copied) => copied.every(Boolean)));
832 const hasLegacySourceControl =
833 settingsFileTrusted &&
834 legacySecretsCopied &&
835 (legacySourceControl.bitbucket !== undefined || legacySourceControl.github !== undefined);
836 const sourceControlMigration = hasLegacySourceControl
837 ? migrateLegacySourceControlSettings(folded, legacySourceControl)
838 : { settings: folded, secretMoves: [] };
839 // Only rewrite a file that decoded cleanly; an untrusted one stays for the user to repair.
840 const migrated = settingsFileTrusted
841 ? yield* moveInlineSettingsSecrets(sourceControlMigration.settings)
842 : folded;
843 // A file still carrying the retired `providers`, `bitbucket`, or `github` keys is rewritten
844 // once so the migrated values persist and the old keys disappear.
845 if (
846 migrated !== loaded ||
847 (settingsFileTrusted && legacyProviders !== undefined) ||
848 hasLegacySourceControl
849 ) {
850 yield* writeSettingsAtomically(migrated);
851 for (const move of sourceControlMigration.secretMoves) {
852 yield* secretStore.remove(move.from).pipe(Effect.ignore);
853 }
854 }
855 return migrated;
856 });
857​
858 // A failed read is not kept: the next read retries instead of replaying the failure.
859 const settingsCache = yield* Cache.makeWith<typeof cacheKey, ServerSettings, ServerSettingsError>(
860 () => loadSettingsFromDisk,
861 {
862 capacity: 1,
863 timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero),
864 },
865 );
866​
867 const getSettingsFromCache = Cache.get(settingsCache, cacheKey);
868​
869 const materializeSettingsSecrets = (
870 settings: ServerSettings,
871 ): Effect.Effect<ServerSettings, ServerSettingsError> =>
872 Effect.gen(function* () {
873 const storedSecrets = new Map<string, string>();
874 const pending = new Map<string, SettingsSecret>();
875 mapSettingsSecrets(settings, (secret) => {
876 if (secret.sensitive && secret.redacted) pending.set(secret.secretName, secret);
877 return secret;
878 });
879 for (const secret of pending.values()) {
880 const value = yield* secretStore.get(secret.secretName).pipe(
881 Effect.mapError(
882 (cause) =>
883 new ServerSettingsError({
884 settingsPath,
885 operation: "read-secret",
886 providerInstanceId: secret.providerInstanceId,
887 environmentVariable: secret.environmentVariable,
888 cause,
889 }),
890 ),
891 );
892 storedSecrets.set(
893 secret.secretName,
894 Option.isSome(value) ? textDecoder.decode(value.value) : "",
895 );
896 }
897 return mapSettingsSecrets(settings, (secret) => ({
898 value:
899 secret.sensitive && secret.redacted
900 ? (storedSecrets.get(secret.secretName) ?? "")
901 : secret.value,
902 redacted: secret.sensitive && secret.kind === "environment" && secret.redacted,
903 }));
904 });
905​
906 const materializeChanges = (changes: Stream.Stream<ServerSettings>) =>
907 changes.pipe(
908 Stream.mapEffect((settings) =>
909 materializeSettingsSecrets(settings).pipe(
910 Effect.catch((error: ServerSettingsError) =>
911 Effect.logWarning("failed to materialize settings secrets", {
912 operation: error.operation,
913 providerInstanceId: error.providerInstanceId,
914 environmentVariable: error.environmentVariable,
915 cause: error.cause,
916 }).pipe(Effect.as(settings)),
917 ),
918 ),
919 ),
920 Stream.map(resolveTextGenerationProvider),
921 );
922​
923 type SecretChange = {
924 readonly secretName: string;
925 readonly providerInstanceId?: string;
926 readonly environmentVariable?: string;
927 } & (
928 | { readonly kind: "write"; readonly value: Uint8Array }
929 | { readonly kind: "remove"; readonly operation: "remove-secret" | "remove-stale-secret" }
930 );
931​
932 const persistSettingsSecrets = (current: ServerSettings, next: ServerSettings) =>
933 Effect.sync(() => {
934 const previous = new Map<string, SettingsSecret>();
935 mapSettingsSecrets(current, (secret) => {
936 // Duplicate environment names follow the provider's last-value-wins behavior.
937 previous.set(secret.secretName, secret);
938 return secret;
939 });
940 const changes: SecretChange[] = [];
941 const nextSecretNames = new Set<string>();
942 const settings = mapSettingsSecrets(next, (secret) => {
943 const metadata = {
944 secretName: secret.secretName,
945 ...(secret.providerInstanceId !== undefined
946 ? { providerInstanceId: secret.providerInstanceId }
947 : {}),
948 ...(secret.environmentVariable !== undefined
949 ? { environmentVariable: secret.environmentVariable }
950 : {}),
951 };
952 if (!secret.sensitive) {
953 changes.push({ ...metadata, kind: "remove", operation: "remove-secret" });
954 return { value: secret.value, redacted: false };
955 }
956 const old = previous.get(secret.secretName);
957 const inlineValue =
958 old?.sensitive && !old.redacted && old.value.length > 0 ? old.value : undefined;
959 const value = secret.redacted ? inlineValue : secret.value;
960 if (value === undefined) {
961 nextSecretNames.add(secret.secretName);
962 return { value: "", redacted: true };
963 }
964 if (value.length === 0) {
965 changes.push({ ...metadata, kind: "remove", operation: "remove-secret" });
966 return { value: "", redacted: false };
967 }
968 nextSecretNames.add(secret.secretName);
969 changes.push({ ...metadata, kind: "write", value: textEncoder.encode(value) });
970 return { value: "", redacted: true };
971 });
972 for (const secret of previous.values()) {
973 if (!secret.sensitive || nextSecretNames.has(secret.secretName)) continue;
974 if (changes.some((change) => change.secretName === secret.secretName)) continue;
975 changes.push({
976 kind: "remove",
977 secretName: secret.secretName,
978 operation: "remove-stale-secret",
979 ...(secret.providerInstanceId !== undefined
980 ? { providerInstanceId: secret.providerInstanceId }
981 : {}),
982 ...(secret.environmentVariable !== undefined
983 ? { environmentVariable: secret.environmentVariable }
984 : {}),
985 });
986 }
987 return { settings, changes };
988 });
989​
990 const rollbackSettingsSecretWrites = (
991 writes: ReadonlyArray<{
992 readonly secretName: string;
993 readonly previousValue: Option.Option<Uint8Array>;
994 readonly providerInstanceId?: string;
995 readonly environmentVariable?: string;
996 }>,
997 ) =>
998 Effect.forEach(
999 writes.toReversed(),
1000 (write) =>
1001 (Option.isSome(write.previousValue)
1002 ? secretStore.set(write.secretName, write.previousValue.value)
1003 : secretStore.remove(write.secretName)
1004 ).pipe(
1005 Effect.catch((cause) =>
1006 Effect.logWarning("failed to roll back settings secret", {
1007 providerInstanceId: write.providerInstanceId,
1008 environmentVariable: write.environmentVariable,
1009 cause,
1010 }),
1011 ),
1012 ),
1013 { discard: true },
1014 );
1015​
1016 const applySettingsSecretChanges = (changes: ReadonlyArray<SecretChange>) => {
1017 const applied: Array<{
1018 readonly secretName: string;
1019 readonly previousValue: Option.Option<Uint8Array>;
1020 readonly providerInstanceId?: string;
1021 readonly environmentVariable?: string;
1022 }> = [];
1023 const rollback = Effect.suspend(() => rollbackSettingsSecretWrites(applied));
1024 return Effect.forEach(
1025 changes,
1026 (change) =>
1027 Effect.gen(function* () {
1028 const previousValue = yield* secretStore.get(change.secretName).pipe(
1029 Effect.mapError(
1030 (cause) =>
1031 new ServerSettingsError({
1032 settingsPath,
1033 operation: "read-secret",
1034 providerInstanceId: change.providerInstanceId,
1035 environmentVariable: change.environmentVariable,
1036 cause,
1037 }),
1038 ),
1039 );
1040 // A store operation may mutate before reporting an error (for example chmod after rename).
1041 applied.push({ ...change, previousValue });
1042 yield* (
1043 change.kind === "write"
1044 ? secretStore.set(change.secretName, change.value)
1045 : secretStore.remove(change.secretName)
1046 ).pipe(
1047 Effect.mapError(
1048 (cause) =>
1049 new ServerSettingsError({
1050 settingsPath,
1051 operation: change.kind === "write" ? "write-secret" : change.operation,
1052 providerInstanceId: change.providerInstanceId,
1053 environmentVariable: change.environmentVariable,
1054 cause,
1055 }),
1056 ),
1057 );
1058 }),
1059 { discard: true },
1060 ).pipe(
1061 Effect.tapError(() => rollback),
1062 Effect.as(rollback),
1063 );
1064 };
1065​
1066 const updateAndPersistSettings = (
1067 update: (current: ServerSettings) => Effect.Effect<ServerSettings, ServerSettingsError>,
1068 ): Effect.Effect<ServerSettings, ServerSettingsError> =>
1069 writeSemaphore.withPermits(1)(
1070 Effect.gen(function* () {
1071 const current = yield* getSettingsFromCache;
1072 const updated = yield* update(current);
1073 const persisted = yield* persistSettingsSecrets(current, updated);
1074 const next = yield* normalizeServerSettings(persisted.settings);
1075 const materialized = yield* Effect.uninterruptibleMask(() =>
1076 Effect.gen(function* () {
1077 const rollbackSecretChanges = yield* applySettingsSecretChanges(persisted.changes);
1078 const materializedExit = yield* Effect.exit(materializeSettingsSecrets(next));
1079 if (Exit.isFailure(materializedExit)) {
1080 yield* rollbackSecretChanges;
1081 return yield* Effect.failCause(materializedExit.cause);
1083 const writeExit = yield* Effect.exit(writeSettingsAtomically(next));
1084 if (Exit.isFailure(writeExit)) {
1085 yield* rollbackSecretChanges;
1086 return yield* Effect.failCause(writeExit.cause);
1088 return materializedExit.value;
1089 }),
1090 );
1091 yield* Cache.set(settingsCache, cacheKey, next);
1092 yield* emitChange(next);
1093 return resolveTextGenerationProvider(materialized);
1094 }),
1095 );
1096​
1097 const withSettingsSnapshot: ServerSettingsService["Service"]["withSettingsSnapshot"] = (use) =>
1098 writeSemaphore.withPermits(1)(
1099 getSettingsFromCache.pipe(
1100 Effect.flatMap(materializeSettingsSecrets),
1101 Effect.map(resolveTextGenerationProvider),
1102 Effect.flatMap(use),
1103 ),
1104 );
1105​
1106 const revalidateAndEmit = writeSemaphore.withPermits(1)(
1107 Effect.gen(function* () {
1108 yield* Cache.invalidate(settingsCache, cacheKey);
1109 const settings = yield* getSettingsFromCache;
1110 yield* emitChange(settings);
1111 }),
1112 );
1113​
1114 const watchFileChanges = (filePath: string) => {
1115 const directory = pathService.dirname(filePath);
1116 const fileName = pathService.basename(filePath);
1117 const resolvedFilePath = pathService.resolve(filePath);
1118 return fs
1119 .watch(directory)
1120 .pipe(
1121 Stream.filter(
1122 (event) =>
1123 event.path === fileName ||
1124 event.path === filePath ||
1125 pathService.resolve(directory, event.path) === resolvedFilePath,
1126 ),
1127 );
1128 };
1129​
1130 const startWatcher = Effect.gen(function* () {
1131 const settingsDir = pathService.dirname(settingsPath);
1132​
1133 yield* fs.makeDirectory(settingsDir, { recursive: true }).pipe(
1134 Effect.mapError(
1135 (cause) =>
1136 new ServerSettingsError({
1137 settingsPath,
1138 operation: "prepare-directory",
1139 cause,
1140 }),
1141 ),
1142 );
1143​
1144 const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
1145​
1146 // A symlinked settings file is rewritten in its destination's directory,
1147 // which a watch on the link's directory never sees. The link is resolved
1148 // again whenever it changes, so repointing it moves the watch along.
1149 const watchLinkTarget = Effect.gen(function* () {
1150 const linkTargetPath = yield* resolveSymlinkTarget(settingsPath).pipe(
1151 Effect.provideService(FileSystem.FileSystem, fs),
1152 Effect.provideService(Path.Path, pathService),
1153 );
1154 if (linkTargetPath === pathService.resolve(settingsPath)) {
1155 return Option.none<string>();
1157 yield* fs
1158 .makeDirectory(pathService.dirname(linkTargetPath), { recursive: true })
1159 .pipe(Effect.ignore({ log: true }));
1160 return Option.some(linkTargetPath);
1161 }).pipe(Effect.orElseSucceed(() => Option.none<string>()));
1162​
1163 const initialLinkTarget = yield* watchLinkTarget;
1164 const linkTargetEvents = Stream.make(initialLinkTarget).pipe(
1165 Stream.concat(watchFileChanges(settingsPath).pipe(Stream.mapEffect(() => watchLinkTarget))),
1166 Stream.changes,
1167 Stream.switchMap(
1168 Option.match({
1169 onNone: () => Stream.empty,
1170 onSome: (linkTargetPath) =>
1171 watchFileChanges(linkTargetPath).pipe(Stream.ignore({ log: true })),
1172 }),
1173 ),
1174 );
1175​
1176 // Debounce watch events so the file is fully written before we read it.
1177 // Editors emit multiple events per save (truncate, write, rename) and
1178 // `fs.watch` can fire before the content has been flushed to disk.
1179 const debouncedSettingsEvents = Stream.merge(
1180 watchFileChanges(settingsPath),
1181 linkTargetEvents,
1182 ).pipe(Stream.debounce(Duration.millis(100)));
1183​
1184 yield* Stream.runForEach(debouncedSettingsEvents, () => revalidateAndEmitSafely).pipe(
1185 Effect.ignoreCause({ log: true }),
1186 Effect.forkIn(watcherScope),
1187 Effect.asVoid,
1188 );
1189 });
1190​
1191 const start = Effect.gen(function* () {
1192 const shouldStart = yield* Ref.modify(startedRef, (started) => [!started, true]);
1193 if (!shouldStart) {
1194 return yield* Deferred.await(startedDeferred);
1196​
1197 const startup = Effect.gen(function* () {
1198 yield* startWatcher;
1199 yield* Cache.invalidate(settingsCache, cacheKey);
1200 yield* getSettingsFromCache;
1201 });
1202​
1203 const startupExit = yield* Effect.exit(startup);
1204 if (startupExit._tag === "Failure") {
1205 yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);
1206 return yield* Effect.failCause(startupExit.cause);
1208​
1209 yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
1210 });
1211​
1212 return {
1213 start,
1214 ready: Deferred.await(startedDeferred),
1215 getSettings: getSettingsFromCache.pipe(
1216 Effect.flatMap(materializeSettingsSecrets),
1217 Effect.map(resolveTextGenerationProvider),
1218 ),
1219 updateSettings: (patch) =>
1220 updateAndPersistSettings((current) =>
1221 Effect.succeed(applyServerSettingsPatch(current, patch)),
1222 ),
1223 updateProviderInstance: (mutation, patch = {}) =>
1224 updateAndPersistSettings((current) =>
1225 Effect.gen(function* () {
1226 yield* ensureProviderInstanceMutationAllowed(current, mutation, settingsPath);
1227 const patched = applyServerSettingsPatch(current, patch);
1228 return applyProviderInstanceMutation(patched, mutation);
1229 }),
1230 ),
1231 withSettingsSnapshot,
1232 get streamChanges() {
1233 return materializeChanges(Stream.fromPubSub(changesPubSub));
1234 },
1235 get subscribeChanges() {
1236 return PubSub.subscribe(changesPubSub).pipe(
1237 Effect.map((subscription) => materializeChanges(Stream.fromSubscription(subscription))),
1238 );
1239 },
1240 } satisfies ServerSettingsService["Service"];
1241});
1242​
1243export const layer = Layer.effect(ServerSettingsService, make);