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

serverSettings.ts

849 lines30.2 KB

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