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