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