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

serverSettings.ts

874 lines31.6 KB

1/**
2 * ServerSettings - Server-authoritative settings service.
3 *
4 * Owns persistence, validation, and change notification of settings that affect
5 * server-side behavior (binary paths, streaming mode, env mode, custom models,
6 * text generation model selection).
7 *
8 * Follows the same pattern as `keybindings.ts`: JSON file + Cache + PubSub +
9 * Semaphore + FileSystem.watch for concurrency and external edit detection.
10 *
11 * @module ServerSettings
12 */
13import {
14 DEFAULT_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")}`;
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​
145export function usageLimitSourceSecretName(sourceId: string): string {
146 return `usage-limit-source-${Buffer.from(sourceId, "utf8").toString("base64url")}`;
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 };
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 };
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);
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 devin: Schema.optionalKey(Schema.Struct({ enabled: Schema.optionalKey(Schema.Boolean) })),
262 grok: Schema.optionalKey(Schema.Struct({ enabled: Schema.optionalKey(Schema.Boolean) })),
263 opencode: Schema.optionalKey(Schema.Struct({ enabled: Schema.optionalKey(Schema.Boolean) })),
264 }),
265 ),
266});
267const decodePersistedOptionalProviderSettingsJsonExit = Schema.decodeUnknownExit(
268 fromLenientJson(PersistedOptionalProviderSettings),
269);
270​
271function restoreUsedProviders(
272 settings: ServerSettings,
273 persisted: typeof PersistedOptionalProviderSettings.Type,
274 providerHistory: ReadonlyArray<{
275 readonly providerName: string;
276 readonly providerInstanceId: string | null;
277 }>,
278): ServerSettings {
279 const usedProviders = new Set(providerHistory.map(({ providerName }) => providerName));
280 const usedProviderInstances = new Set(
281 providerHistory.map(
282 ({ providerName, providerInstanceId }) => providerInstanceId ?? providerName,
283 ),
284 );
285 const providerInstances = Object.fromEntries(
286 Object.entries(settings.providerInstances).map(([instanceId, instance]) => [
287 instanceId,
288 instance.enabled === undefined &&
289 (instance.driver === "cursor" ||
290 instance.driver === "devin" ||
291 instance.driver === "grok" ||
292 instance.driver === "opencode") &&
293 usedProviderInstances.has(instanceId)
294 ? { ...instance, enabled: true }
295 : instance,
296 ]),
297 );
298​
299 return {
300 ...settings,
301 providers: {
302 ...settings.providers,
303 cursor: {
304 ...settings.providers.cursor,
305 enabled: persisted.providers?.cursor?.enabled ?? usedProviders.has("cursor"),
306 },
307 devin: {
308 ...settings.providers.devin,
309 enabled: persisted.providers?.devin?.enabled ?? usedProviders.has("devin"),
310 },
311 grok: {
312 ...settings.providers.grok,
313 enabled: persisted.providers?.grok?.enabled ?? usedProviders.has("grok"),
314 },
315 opencode: {
316 ...settings.providers.opencode,
317 enabled: persisted.providers?.opencode?.enabled ?? usedProviders.has("opencode"),
318 },
319 },
320 providerInstances,
321 };
323​
324function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings {
325 return isModelSelectionProviderEnabled(settings, settings.textGenerationModelSelection)
326 ? settings
327 : fallbackTextGenerationProvider(settings);
329​
330function fallbackTextGenerationProvider(settings: ServerSettings): ServerSettings {
331 // Same precedence as isModelSelectionProviderEnabled: an explicit provider
332 // instance wins over the legacy providers map, which decodes to defaults
333 // (codex enabled) when the Providers UI has only written providerInstances.
334 const fallbackEntry = Object.entries(settings.providers).find(([driver, provider]) => {
335 const instance = settings.providerInstances[ProviderInstanceId.make(driver)];
336 return instance === undefined ? provider.enabled : resolveProviderInstanceEnabled(instance);
337 });
338 const fallback = fallbackEntry ? ProviderDriverKind.make(fallbackEntry[0]) : undefined;
339 if (!fallback) {
340 return settings;
341 }
342​
343 return {
344 ...settings,
345 textGenerationModelSelection: {
346 instanceId: ProviderInstanceId.make(fallback),
347 model:
348 DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback] ??
349 DEFAULT_MODEL_BY_PROVIDER[fallback] ??
350 DEFAULT_TEXT_GENERATION_MODEL,
351 } satisfies ModelSelection,
352 };
354​
355// Values under these keys are compared as a whole — never stripped field-by-field.
356const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set([
357 "backgroundActivity",
358 "automaticGitFetchInterval",
359 "providerHealthRefreshInterval",
360 "sourceControlWriterModelSelection",
361 "textGenerationModelSelection",
362]);
363​
364// Preserve both enabled states because provider history cannot recover a new opt-in.
365const PERSISTED_SERVER_SETTINGS_DEFAULTS = {
366 ...DEFAULT_SERVER_SETTINGS,
367 providers: {
368 ...DEFAULT_SERVER_SETTINGS.providers,
369 cursor: { ...DEFAULT_SERVER_SETTINGS.providers.cursor, enabled: undefined },
370 devin: { ...DEFAULT_SERVER_SETTINGS.providers.devin, enabled: undefined },
371 grok: { ...DEFAULT_SERVER_SETTINGS.providers.grok, enabled: undefined },
372 opencode: { ...DEFAULT_SERVER_SETTINGS.providers.opencode, enabled: undefined },
373 },
374};
375​
376function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {
377 if (Array.isArray(current) || Array.isArray(defaults)) {
378 return Equal.equals(current, defaults) ? undefined : current;
379 }
380​
381 if (
382 current !== null &&
383 defaults !== null &&
384 typeof current === "object" &&
385 typeof defaults === "object"
386 ) {
387 const currentRecord = current as Record<string, unknown>;
388 const defaultsRecord = defaults as Record<string, unknown>;
389 const next: Record<string, unknown> = {};
390​
391 for (const key of Object.keys(currentRecord)) {
392 if (ATOMIC_SETTINGS_KEYS.has(key)) {
393 if (!Equal.equals(currentRecord[key], defaultsRecord[key])) {
394 next[key] = currentRecord[key];
395 }
396 } else {
397 const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]);
398 if (stripped !== undefined) {
399 next[key] = stripped;
400 }
401 }
402 }
403​
404 return Object.keys(next).length > 0 ? next : undefined;
405 }
406​
407 return Object.is(current, defaults) ? undefined : current;
409​
410const make = Effect.gen(function* () {
411 const { settingsPath } = yield* ServerConfig.ServerConfig;
412 const fs = yield* FileSystem.FileSystem;
413 const pathService = yield* Path.Path;
414 const secretStore = yield* ServerSecretStore.ServerSecretStore;
415 const sql = yield* SqlClient.SqlClient;
416 const writeSemaphore = yield* Semaphore.make(1);
417 const cacheKey = "settings" as const;
418 const changesPubSub = yield* PubSub.unbounded<ServerSettings>();
419 const startedRef = yield* Ref.make(false);
420 const startedDeferred = yield* Deferred.make<void, ServerSettingsError>();
421 const watcherScope = yield* Scope.make("sequential");
422 yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
423​
424 const emitChange = (settings: ServerSettings) =>
425 PubSub.publish(changesPubSub, settings).pipe(Effect.asVoid);
426​
427 const readConfigExists = fs.exists(settingsPath).pipe(
428 Effect.mapError(
429 (cause) =>
430 new ServerSettingsError({
431 settingsPath,
432 operation: "check-exists",
433 cause,
434 }),
435 ),
436 );
437​
438 const readRawConfig = fs.readFileString(settingsPath).pipe(
439 Effect.mapError(
440 (cause) =>
441 new ServerSettingsError({
442 settingsPath,
443 operation: "read-file",
444 cause,
445 }),
446 ),
447 );
448​
449 const loadSettingsFromDisk = Effect.gen(function* () {
450 let settings = DEFAULT_SERVER_SETTINGS;
451 let persisted: typeof PersistedOptionalProviderSettings.Type = {};
452​
453 if (yield* readConfigExists) {
454 const raw = yield* readRawConfig;
455 const decoded = decodeServerSettingsJsonExit(raw);
456 const persistedSettings = decodePersistedOptionalProviderSettingsJsonExit(raw);
457 if (persistedSettings._tag === "Success") {
458 persisted = persistedSettings.value;
459 }
460 if (decoded._tag === "Failure" || persistedSettings._tag === "Failure") {
461 const failure = decoded._tag === "Failure" ? decoded : persistedSettings;
462 if (failure._tag === "Failure") {
463 yield* Effect.logWarning("failed to parse settings.json, using defaults", {
464 path: settingsPath,
465 issues: Cause.pretty(failure.cause),
466 cause: failure.cause,
467 });
468 }
469 } else {
470 settings = decoded.value;
471 }
472 }
473​
474 const providerHistory = yield* sql<{
475 readonly providerName: string;
476 readonly providerInstanceId: string | null;
477 }>`
478 SELECT DISTINCT
479 provider_name AS "providerName",
480 provider_instance_id AS "providerInstanceId"
481 FROM projection_thread_sessions
482 WHERE provider_name IN ('cursor', 'devin', 'grok', 'opencode')
483 UNION
484 SELECT DISTINCT
485 provider_name AS "providerName",
486 provider_instance_id AS "providerInstanceId"
487 FROM provider_session_runtime
488 WHERE provider_name IN ('cursor', 'devin', 'grok', 'opencode')
489 `.pipe(
490 Effect.mapError(
491 (cause) =>
492 new ServerSettingsError({
493 settingsPath,
494 operation: "read-provider-history",
495 cause,
496 }),
497 ),
498 );
499​
500 return foldProviderInstanceEnabledFlags(
501 restoreUsedProviders(settings, persisted, providerHistory),
502 );
503 });
504​
505 const settingsCache = yield* Cache.make<typeof cacheKey, ServerSettings, ServerSettingsError>({
506 capacity: 1,
507 lookup: () => loadSettingsFromDisk,
508 });
509​
510 const getSettingsFromCache = Cache.get(settingsCache, cacheKey);
511​
512 const materializeProviderEnvironmentSecrets = (
513 settings: ServerSettings,
514 ): Effect.Effect<ServerSettings, ServerSettingsError> =>
515 Effect.gen(function* () {
516 const providerInstances: Record<string, ProviderInstanceConfig> = {
517 ...settings.providerInstances,
518 };
519 for (const [instanceId, instance] of Object.entries(settings.providerInstances)) {
520 if (!instance.environment) continue;
521 const environment: ProviderInstanceEnvironmentVariable[] = [];
522 for (const variable of instance.environment) {
523 if (!variable.sensitive || !variable.valueRedacted) {
524 environment.push(variable);
525 continue;
526 }
527 const secret = yield* secretStore
528 .get(providerEnvironmentSecretName({ instanceId, name: variable.name }))
529 .pipe(
530 Effect.mapError(
531 (cause) =>
532 new ServerSettingsError({
533 settingsPath,
534 operation: "read-secret",
535 providerInstanceId: instanceId,
536 environmentVariable: variable.name,
537 cause,
538 }),
539 ),
540 );
541 environment.push({
542 ...variable,
543 value: Option.isSome(secret) ? textDecoder.decode(secret.value) : "",
544 });
545 }
546 providerInstances[instanceId] = {
547 ...instance,
548 environment,
549 } satisfies ProviderInstanceConfig;
550 }
551 const usageLimitSources: Record<string, UsageLimitSourceConfig> = {};
552 for (const [sourceId, source] of Object.entries(settings.usageLimitSources)) {
553 if (source.managementKey !== USAGE_LIMIT_SOURCE_KEY_REDACTED) {
554 usageLimitSources[sourceId] = source;
555 continue;
556 }
557 const secret = yield* secretStore
558 .get(usageLimitSourceSecretName(sourceId))
559 .pipe(
560 Effect.mapError(
561 (cause) => new ServerSettingsError({ settingsPath, operation: "read-secret", cause }),
562 ),
563 );
564 usageLimitSources[sourceId] = {
565 ...source,
566 managementKey: Option.isSome(secret) ? textDecoder.decode(secret.value) : "",
567 };
568 }
569 return {
570 ...settings,
571 providerInstances: providerInstances as ServerSettings["providerInstances"],
572 usageLimitSources: usageLimitSources as ServerSettings["usageLimitSources"],
573 };
574 });
575​
576 const materializeChanges = (changes: Stream.Stream<ServerSettings>) =>
577 changes.pipe(
578 Stream.mapEffect((settings) =>
579 materializeProviderEnvironmentSecrets(settings).pipe(
580 Effect.catch((error: ServerSettingsError) =>
581 Effect.logWarning("failed to materialize provider environment secrets", {
582 operation: error.operation,
583 providerInstanceId: error.providerInstanceId,
584 environmentVariable: error.environmentVariable,
585 cause: error.cause,
586 }).pipe(Effect.as(settings)),
587 ),
588 ),
589 ),
590 Stream.map(resolveTextGenerationProvider),
591 );
592​
593 const persistProviderEnvironmentSecrets = (
594 current: ServerSettings,
595 next: ServerSettings,
596 ): Effect.Effect<ServerSettings, ServerSettingsError> =>
597 Effect.gen(function* () {
598 const providerInstances: Record<string, ProviderInstanceConfig> = {
599 ...next.providerInstances,
600 };
601​
602 const nextSecretKeys = new Set<string>();
603 for (const [instanceId, instance] of Object.entries(next.providerInstances)) {
604 if (!instance.environment) continue;
605 const environment: ProviderInstanceEnvironmentVariable[] = [];
606 for (const variable of instance.environment) {
607 const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name });
608 if (!variable.sensitive) {
609 yield* secretStore.remove(secretName).pipe(
610 Effect.mapError(
611 (cause) =>
612 new ServerSettingsError({
613 settingsPath,
614 operation: "remove-secret",
615 providerInstanceId: instanceId,
616 environmentVariable: variable.name,
617 cause,
618 }),
619 ),
620 );
621 environment.push(redactProviderEnvironmentVariable(variable));
622 continue;
623 }
624​
625 nextSecretKeys.add(secretName);
626 // Match the provider environment's last-value-wins behavior for duplicate names.
627 const previous = variable.valueRedacted
628 ? current.providerInstances[ProviderInstanceId.make(instanceId)]?.environment?.findLast(
629 (entry) => entry.name === variable.name,
630 )
631 : undefined;
632 const inlineValue =
633 previous?.sensitive && !previous.valueRedacted && previous.value.length > 0
634 ? previous.value
635 : undefined;
636 const value = inlineValue ?? variable.value;
637 if (!variable.valueRedacted || inlineValue !== undefined) {
638 if (value.length > 0) {
639 yield* secretStore.set(secretName, textEncoder.encode(value)).pipe(
640 Effect.mapError(
641 (cause) =>
642 new ServerSettingsError({
643 settingsPath,
644 operation: "write-secret",
645 providerInstanceId: instanceId,
646 environmentVariable: variable.name,
647 cause,
648 }),
649 ),
650 );
651 environment.push({ ...variable, value: "", valueRedacted: true });
652 } else {
653 yield* secretStore.remove(secretName).pipe(
654 Effect.mapError(
655 (cause) =>
656 new ServerSettingsError({
657 settingsPath,
658 operation: "remove-secret",
659 providerInstanceId: instanceId,
660 environmentVariable: variable.name,
661 cause,
662 }),
663 ),
664 );
665 const { valueRedacted: _omit, ...rest } = variable;
666 environment.push(rest);
667 }
668 continue;
669 }
670​
671 environment.push(redactProviderEnvironmentVariable(variable));
672 }
673 providerInstances[instanceId] = {
674 ...instance,
675 environment,
676 } satisfies ProviderInstanceConfig;
677 }
678​
679 for (const [instanceId, instance] of Object.entries(current.providerInstances)) {
680 for (const variable of instance.environment ?? []) {
681 if (!variable.sensitive) continue;
682 const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name });
683 if (nextSecretKeys.has(secretName)) continue;
684 yield* secretStore.remove(secretName).pipe(
685 Effect.mapError(
686 (cause) =>
687 new ServerSettingsError({
688 settingsPath,
689 operation: "remove-stale-secret",
690 providerInstanceId: instanceId,
691 environmentVariable: variable.name,
692 cause,
693 }),
694 ),
695 );
696 }
697 }
698​
699 const usageLimitSources: Record<string, UsageLimitSourceConfig> = {};
700 for (const [sourceId, source] of Object.entries(next.usageLimitSources)) {
701 const secretName = usageLimitSourceSecretName(sourceId);
702 if (source.managementKey === USAGE_LIMIT_SOURCE_KEY_REDACTED) {
703 // Unchanged from the client's point of view; the store already has it.
704 usageLimitSources[sourceId] = source;
705 continue;
706 }
707 if (source.managementKey.length === 0) {
708 yield* secretStore
709 .remove(secretName)
710 .pipe(
711 Effect.mapError(
712 (cause) =>
713 new ServerSettingsError({ settingsPath, operation: "remove-secret", cause }),
714 ),
715 );
716 usageLimitSources[sourceId] = source;
717 continue;
718 }
719 yield* secretStore
720 .set(secretName, textEncoder.encode(source.managementKey))
721 .pipe(
722 Effect.mapError(
723 (cause) =>
724 new ServerSettingsError({ settingsPath, operation: "write-secret", cause }),
725 ),
726 );
727 usageLimitSources[sourceId] = { ...source, managementKey: USAGE_LIMIT_SOURCE_KEY_REDACTED };
728 }
729 for (const sourceId of Object.keys(current.usageLimitSources)) {
730 if (sourceId in next.usageLimitSources) continue;
731 yield* secretStore
732 .remove(usageLimitSourceSecretName(sourceId))
733 .pipe(
734 Effect.mapError(
735 (cause) =>
736 new ServerSettingsError({ settingsPath, operation: "remove-stale-secret", cause }),
737 ),
738 );
739 }
740​
741 return {
742 ...next,
743 providerInstances: providerInstances as ServerSettings["providerInstances"],
744 usageLimitSources: usageLimitSources as ServerSettings["usageLimitSources"],
745 };
746 });
747​
748 const writeSettingsAtomically = Effect.fnUntraced(
749 function* (settings: ServerSettings) {
750 const sparseSettingsJson = yield* encodeServerSettingsJson(
751 stripDefaultServerSettings(settings, PERSISTED_SERVER_SETTINGS_DEFAULTS) ?? {},
752 );
753​
754 return yield* writeFileStringAtomically({
755 filePath: settingsPath,
756 contents: `${sparseSettingsJson}\n`,
757 }).pipe(
758 Effect.provideService(FileSystem.FileSystem, fs),
759 Effect.provideService(Path.Path, pathService),
760 );
761 },
762 Effect.mapError(
763 (cause) =>
764 new ServerSettingsError({
765 settingsPath,
766 operation: "write-file",
767 cause,
768 }),
769 ),
770 );
771​
772 const revalidateAndEmit = writeSemaphore.withPermits(1)(
773 Effect.gen(function* () {
774 yield* Cache.invalidate(settingsCache, cacheKey);
775 const settings = yield* getSettingsFromCache;
776 yield* emitChange(settings);
777 }),
778 );
779​
780 const startWatcher = Effect.gen(function* () {
781 const settingsDir = pathService.dirname(settingsPath);
782 const settingsFile = pathService.basename(settingsPath);
783 const settingsPathResolved = pathService.resolve(settingsPath);
784​
785 yield* fs.makeDirectory(settingsDir, { recursive: true }).pipe(
786 Effect.mapError(
787 (cause) =>
788 new ServerSettingsError({
789 settingsPath,
790 operation: "prepare-directory",
791 cause,
792 }),
793 ),
794 );
795​
796 const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
797​
798 // Debounce watch events so the file is fully written before we read it.
799 // Editors emit multiple events per save (truncate, write, rename) and
800 // `fs.watch` can fire before the content has been flushed to disk.
801 const debouncedSettingsEvents = fs.watch(settingsDir).pipe(
802 Stream.filter((event) => {
803 return (
804 event.path === settingsFile ||
805 event.path === settingsPath ||
806 pathService.resolve(settingsDir, event.path) === settingsPathResolved
807 );
808 }),
809 Stream.debounce(Duration.millis(100)),
810 );
811​
812 yield* Stream.runForEach(debouncedSettingsEvents, () => revalidateAndEmitSafely).pipe(
813 Effect.ignoreCause({ log: true }),
814 Effect.forkIn(watcherScope),
815 Effect.asVoid,
816 );
817 });
818​
819 const start = Effect.gen(function* () {
820 const shouldStart = yield* Ref.modify(startedRef, (started) => [!started, true]);
821 if (!shouldStart) {
822 return yield* Deferred.await(startedDeferred);
823 }
824​
825 const startup = Effect.gen(function* () {
826 yield* startWatcher;
827 yield* Cache.invalidate(settingsCache, cacheKey);
828 yield* getSettingsFromCache;
829 });
830​
831 const startupExit = yield* Effect.exit(startup);
832 if (startupExit._tag === "Failure") {
833 yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);
834 return yield* Effect.failCause(startupExit.cause);
835 }
836​
837 yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
838 });
839​
840 return {
841 start,
842 ready: Deferred.await(startedDeferred),
843 getSettings: getSettingsFromCache.pipe(
844 Effect.flatMap(materializeProviderEnvironmentSecrets),
845 Effect.map(resolveTextGenerationProvider),
846 ),
847 updateSettings: (patch) =>
848 writeSemaphore.withPermits(1)(
849 Effect.gen(function* () {
850 const current = yield* getSettingsFromCache;
851 const nextPersisted = yield* persistProviderEnvironmentSecrets(
852 current,
853 applyServerSettingsPatch(current, patch),
854 );
855 const next = yield* normalizeServerSettings(nextPersisted);
856 yield* writeSettingsAtomically(next);
857 yield* Cache.set(settingsCache, cacheKey, next);
858 yield* emitChange(next);
859 const materialized = yield* materializeProviderEnvironmentSecrets(next);
860 return resolveTextGenerationProvider(materialized);
861 }),
862 ),
863 get streamChanges() {
864 return materializeChanges(Stream.fromPubSub(changesPubSub));
865 },
866 get subscribeChanges() {
867 return PubSub.subscribe(changesPubSub).pipe(
868 Effect.map((subscription) => materializeChanges(Stream.fromSubscription(subscription))),
869 );
870 },
871 } satisfies ServerSettingsService["Service"];
872});
873​
874export const layer = Layer.effect(ServerSettingsService, make);