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

serverSettings.ts

1,072 lines38.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 type ProviderInstanceMutation,
23 ProviderDriverKind,
24 ProviderInstanceId,
25 resolveProviderInstanceEnabled,
26 ServerSettings,
27 ServerSettingsError,
28 type ServerSettingsPatch,
29} from "@t3tools/contracts";
30import * as Cache from "effect/Cache";
31import * as Cause from "effect/Cause";
32import * as Context from "effect/Context";
33import * as Deferred from "effect/Deferred";
34import * as Duration from "effect/Duration";
35import * as Equal from "effect/Equal";
36import * as Effect from "effect/Effect";
37import * as Exit from "effect/Exit";
38import * as FileSystem from "effect/FileSystem";
39import * as Layer from "effect/Layer";
40import * as Option from "effect/Option";
41import * as Path from "effect/Path";
42import * as PubSub from "effect/PubSub";
43import * as Ref from "effect/Ref";
44import * as Schema from "effect/Schema";
45import * as Semaphore from "effect/Semaphore";
46import * as Scope from "effect/Scope";
47import * as Stream from "effect/Stream";
48import * as SqlClient from "effect/unstable/sql/SqlClient";
49import { writeFileStringAtomically } from "./atomicWrite.ts";
50import * as ServerConfig from "./config.ts";
51import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
52import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
53import {
54 applyServerSettingsPatch,
55 isModelSelectionProviderEnabled,
56} from "@t3tools/shared/serverSettings";
57import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
58​
59export { resolveSourceControlWriterModelSelection } from "@t3tools/shared/serverSettings";
60​
61const encodeServerSettings = Schema.encodeEffect(ServerSettings);
62const encodeServerSettingsJson = Schema.encodeUnknownEffect(fromJsonStringPretty(ServerSettings));
63const decodeServerSettings = Schema.decodeUnknownEffect(ServerSettings);
64​
65const textEncoder = new TextEncoder();
66const textDecoder = new TextDecoder();
67​
68/**
69 * Fold the legacy in-config `enabled` flag into the envelope-level
70 * `ProviderInstanceConfig.enabled` and strip it from the config blob, so
71 * explicit provider instances carry exactly one enabled flag. Old settings
72 * files can hold both flags with conflicting values; an explicit false on
73 * either side wins so a user's disable is never silently undone. Runs on
74 * every load and update — the file converges on the next write.
75 */
76const foldProviderInstanceEnabledFlags = (settings: ServerSettings): ServerSettings => {
77 let changed = false;
78 const providerInstances: Record<string, ProviderInstanceConfig> = {};
79 for (const [instanceId, instance] of Object.entries(settings.providerInstances)) {
80 const config = instance.config;
81 // Only fold boolean flags: a malformed `enabled` (e.g. `"false"`) must
82 // stay in the blob so driver schema validation flags it instead of the
83 // fold silently repairing the config.
84 if (
85 config === null ||
86 typeof config !== "object" ||
87 Array.isArray(config) ||
88 typeof (config as { readonly enabled?: unknown }).enabled !== "boolean"
89 ) {
90 providerInstances[instanceId] = instance;
91 continue;
92 }
93 const { enabled: configEnabled, ...restConfig } = config as Record<string, unknown> & {
94 readonly enabled: boolean;
95 };
96 const resolved =
97 instance.enabled === false || configEnabled === false
98 ? false
99 : (instance.enabled ?? configEnabled);
100 changed = true;
101 providerInstances[instanceId] = {
102 ...instance,
103 enabled: resolved,
104 config: restConfig,
105 } satisfies ProviderInstanceConfig;
106 }
107 if (!changed) {
108 return settings;
109 }
110 return {
111 ...settings,
112 providerInstances: providerInstances as ServerSettings["providerInstances"],
113 };
114};
115​
116const normalizeServerSettings = (
117 settings: ServerSettings,
118): Effect.Effect<ServerSettings, ServerSettingsError> =>
119 encodeServerSettings(settings).pipe(
120 Effect.flatMap(decodeServerSettings),
121 Effect.map(foldProviderInstanceEnabledFlags),
122 Effect.mapError(
123 (cause) =>
124 new ServerSettingsError({
125 settingsPath: "<memory>",
126 operation: "normalize",
127 cause,
128 }),
129 ),
130 );
131​
132function providerEnvironmentSecretName(input: {
133 readonly instanceId: string;
134 readonly name: string;
135}): string {
136 return `provider-env-${Buffer.from(input.instanceId, "utf8").toString("base64url")}-${Buffer.from(input.name, "utf8").toString("base64url")}`;
138​
139/**
140 * On disk the hub key is replaced by this marker and the real value lives in
141 * the secret store, mirroring provider environment secrets. A client that
142 * sends the marker back means "keep what you have".
143 */
144const USAGE_LIMIT_SOURCE_KEY_REDACTED = "\u2022\u2022\u2022\u2022\u2022\u2022";
145​
146function usageLimitSourceSecretName(sourceId: string): string {
147 return `usage-limit-source-${Buffer.from(sourceId, "utf8").toString("base64url")}`;
149​
150function redactProviderEnvironmentVariable(
151 variable: ProviderInstanceEnvironmentVariable,
152): ProviderInstanceEnvironmentVariable {
153 if (!variable.sensitive) {
154 const { valueRedacted: _omit, ...rest } = variable;
155 return rest;
156 }
157 return {
158 ...variable,
159 value: "",
160 ...(variable.value.length > 0 || variable.valueRedacted ? { valueRedacted: true } : {}),
161 };
163​
164export function redactServerSettingsForClient(settings: ServerSettings): ServerSettings {
165 const providerInstances = Object.fromEntries(
166 Object.entries(settings.providerInstances).map(([instanceId, instance]) => [
167 instanceId,
168 instance.environment
169 ? {
170 ...instance,
171 environment: instance.environment.map(redactProviderEnvironmentVariable),
172 }
173 : instance,
174 ]),
175 );
176 // The hub key is a bearer secret; clients only need to know one is set.
177 const usageLimitSources = Object.fromEntries(
178 Object.entries(settings.usageLimitSources).map(([id, source]) => [
179 id,
180 {
181 ...source,
182 managementKey: source.managementKey.length > 0 ? USAGE_LIMIT_SOURCE_KEY_REDACTED : "",
183 },
184 ]),
185 );
186 return { ...settings, providerInstances, usageLimitSources };
188​
189export function applyProviderInstanceMutation(
190 settings: ServerSettings,
191 mutation: ProviderInstanceMutation,
192): ServerSettings {
193 const providerInstances = { ...settings.providerInstances };
194 if (mutation.operation === "upsert" || mutation.operation === "create") {
195 providerInstances[mutation.instanceId] = mutation.instance;
196 } else {
197 delete providerInstances[mutation.instanceId];
198 }
199 return { ...settings, providerInstances };
201​
202function ensureProviderInstanceMutationAllowed(
203 settings: ServerSettings,
204 mutation: ProviderInstanceMutation,
205 settingsPath: string,
206): Effect.Effect<void, ServerSettingsError> {
207 if (
208 mutation.operation === "create" &&
209 settings.providerInstances[mutation.instanceId] !== undefined
210 ) {
211 return Effect.fail(
212 new ServerSettingsError({
213 settingsPath,
214 operation: "create-provider-instance",
215 providerInstanceId: mutation.instanceId,
216 }),
217 );
218 }
219 return Effect.void;
221​
222export class ServerSettingsService extends Context.Service<
223 ServerSettingsService,
224 {
225 /** Start the settings runtime and attach file watching. */
226 readonly start: Effect.Effect<void, ServerSettingsError>;
227​
228 /** Await settings runtime readiness. */
229 readonly ready: Effect.Effect<void, ServerSettingsError>;
230​
231 /** Read the current settings. */
232 readonly getSettings: Effect.Effect<ServerSettings, ServerSettingsError>;
233​
234 /** Patch settings and persist. Returns the new full settings object. */
235 readonly updateSettings: (
236 patch: ServerSettingsPatch,
237 ) => Effect.Effect<ServerSettings, ServerSettingsError>;
238​
239 /** Apply a patch and one provider-instance mutation against the same latest settings snapshot. */
240 readonly updateProviderInstance: (
241 mutation: ProviderInstanceMutation,
242 patch?: ServerSettingsPatch,
243 ) => Effect.Effect<ServerSettings, ServerSettingsError>;
244​
245 /** Run an effect against a settings snapshot while settings writes are paused. */
246 readonly withSettingsSnapshot: <A, E, R>(
247 use: (settings: ServerSettings) => Effect.Effect<A, E, R>,
248 ) => Effect.Effect<A, E | ServerSettingsError, R>;
249​
250 /** Stream of settings change events. */
251 readonly streamChanges: Stream.Stream<ServerSettings>;
252​
253 /**
254 * Acquire a settings change subscription synchronously in the current
255 * fiber. Use this before reading a snapshot when changes between the
256 * snapshot and a lazily started stream must not be lost.
257 */
258 readonly subscribeChanges: Effect.Effect<Stream.Stream<ServerSettings>, never, Scope.Scope>;
259 }
260>()("t3/serverSettings/ServerSettingsService") {
261 /** @deprecated Import and use `layerTest` from this module. */
262 static readonly layerTest = (overrides: DeepPartial<ServerSettings> = {}) => layerTest(overrides);
264​
265const makeTest = (overrides: DeepPartial<ServerSettings> = {}) =>
266 Effect.gen(function* () {
267 const { automaticGitFetchInterval, providerHealthRefreshInterval, ...overridesForMerge } =
268 overrides;
269 const merged = deepMerge(DEFAULT_SERVER_SETTINGS, overridesForMerge);
270 const initialSettings = yield* normalizeServerSettings({
271 ...merged,
272 ...(automaticGitFetchInterval !== undefined
273 ? { automaticGitFetchInterval: automaticGitFetchInterval as Duration.Duration }
274 : {}),
275 ...(providerHealthRefreshInterval !== undefined
276 ? { providerHealthRefreshInterval: providerHealthRefreshInterval as Duration.Duration }
277 : {}),
278 });
279 const currentSettingsRef = yield* Ref.make<ServerSettings>(initialSettings);
280 const writeSemaphore = yield* Semaphore.make(1);
281 const getSettings = Ref.get(currentSettingsRef).pipe(Effect.map(resolveTextGenerationProvider));
282​
283 const updateTestSettings = (
284 update: (current: ServerSettings) => Effect.Effect<ServerSettings, ServerSettingsError>,
285 ): Effect.Effect<ServerSettings, ServerSettingsError> =>
286 writeSemaphore.withPermits(1)(
287 Ref.get(currentSettingsRef).pipe(
288 Effect.flatMap(update),
289 Effect.flatMap(normalizeServerSettings),
290 Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
291 Effect.map(resolveTextGenerationProvider),
292 ),
293 );
294​
295 return {
296 start: Effect.void,
297 ready: Effect.void,
298 getSettings,
299 updateSettings: (patch) =>
300 updateTestSettings((currentSettings) =>
301 Effect.succeed(applyServerSettingsPatch(currentSettings, patch)),
302 ),
303 updateProviderInstance: (mutation, patch = {}) =>
304 updateTestSettings((currentSettings) =>
305 Effect.gen(function* () {
306 yield* ensureProviderInstanceMutationAllowed(
307 currentSettings,
308 mutation,
309 "test settings",
310 );
311 const patched = applyServerSettingsPatch(currentSettings, patch);
312 return applyProviderInstanceMutation(patched, mutation);
313 }),
314 ),
315 withSettingsSnapshot: (use) =>
316 writeSemaphore.withPermits(1)(getSettings.pipe(Effect.flatMap(use))),
317 streamChanges: Stream.empty,
318 subscribeChanges: Effect.succeed(Stream.empty),
319 } satisfies ServerSettingsService["Service"];
320 });
321​
322export const layerTest = (overrides: DeepPartial<ServerSettings> = {}) =>
323 Layer.effect(ServerSettingsService, makeTest(overrides));
324​
325const ServerSettingsJson = fromLenientJson(ServerSettings);
326const decodeServerSettingsJsonExit = Schema.decodeUnknownExit(ServerSettingsJson);
327const PersistedOptionalProviderSettings = Schema.Struct({
328 providers: Schema.optionalKey(
329 Schema.Struct({
330 cursor: Schema.optionalKey(Schema.Struct({ enabled: Schema.optionalKey(Schema.Boolean) })),
331 grok: Schema.optionalKey(Schema.Struct({ enabled: Schema.optionalKey(Schema.Boolean) })),
332 opencode: Schema.optionalKey(Schema.Struct({ enabled: Schema.optionalKey(Schema.Boolean) })),
333 }),
334 ),
335});
336const decodePersistedOptionalProviderSettingsJsonExit = Schema.decodeUnknownExit(
337 fromLenientJson(PersistedOptionalProviderSettings),
338);
339​
340function restoreUsedProviders(
341 settings: ServerSettings,
342 persisted: typeof PersistedOptionalProviderSettings.Type,
343 providerHistory: ReadonlyArray<{
344 readonly providerName: string;
345 readonly providerInstanceId: string | null;
346 }>,
347): ServerSettings {
348 const usedProviders = new Set(providerHistory.map(({ providerName }) => providerName));
349 const usedProviderInstances = new Set(
350 providerHistory.map(
351 ({ providerName, providerInstanceId }) => providerInstanceId ?? providerName,
352 ),
353 );
354 const providerInstances = Object.fromEntries(
355 Object.entries(settings.providerInstances).map(([instanceId, instance]) => [
356 instanceId,
357 instance.enabled === undefined &&
358 (instance.driver === "cursor" ||
359 instance.driver === "grok" ||
360 instance.driver === "opencode") &&
361 usedProviderInstances.has(instanceId)
362 ? { ...instance, enabled: true }
363 : instance,
364 ]),
365 );
366​
367 return {
368 ...settings,
369 providers: {
370 ...settings.providers,
371 cursor: {
372 ...settings.providers.cursor,
373 enabled: persisted.providers?.cursor?.enabled ?? usedProviders.has("cursor"),
374 },
375 grok: {
376 ...settings.providers.grok,
377 enabled: persisted.providers?.grok?.enabled ?? usedProviders.has("grok"),
378 },
379 opencode: {
380 ...settings.providers.opencode,
381 enabled: persisted.providers?.opencode?.enabled ?? usedProviders.has("opencode"),
382 },
383 },
384 providerInstances,
385 };
387​
388const ACP_REGISTRY_DRIVER = ProviderDriverKind.make("acpRegistry");
389​
390/** ACP Registry instances reject every application text-generation operation. */
391function selectionSupportsTextGeneration(
392 settings: ServerSettings,
393 selection: ModelSelection,
394): boolean {
395 return settings.providerInstances[selection.instanceId]?.driver !== ACP_REGISTRY_DRIVER;
397​
398function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings {
399 return isModelSelectionProviderEnabled(settings, settings.textGenerationModelSelection) &&
400 selectionSupportsTextGeneration(settings, settings.textGenerationModelSelection)
401 ? settings
402 : fallbackTextGenerationProvider(settings);
404​
405function fallbackTextGenerationProvider(settings: ServerSettings): ServerSettings {
406 // Same precedence as isModelSelectionProviderEnabled: an explicit provider
407 // instance wins over the legacy providers map, which decodes to defaults
408 // (codex enabled) when the Providers UI has only written providerInstances.
409 const fallbackEntry = Object.entries(settings.providers).find(([driver, provider]) => {
410 const instance = settings.providerInstances[ProviderInstanceId.make(driver)];
411 return instance === undefined ? provider.enabled : resolveProviderInstanceEnabled(instance);
412 });
413 const fallback = fallbackEntry ? ProviderDriverKind.make(fallbackEntry[0]) : undefined;
414 if (!fallback) {
415 return settings;
416 }
417​
418 return {
419 ...settings,
420 textGenerationModelSelection: {
421 instanceId: ProviderInstanceId.make(fallback),
422 model:
423 DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback] ??
424 DEFAULT_MODEL_BY_PROVIDER[fallback] ??
425 DEFAULT_TEXT_GENERATION_MODEL,
426 } satisfies ModelSelection,
427 };
429​
430// Values under these keys are compared as a whole — never stripped field-by-field.
431const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set([
432 "backgroundActivity",
433 "automaticGitFetchInterval",
434 "providerHealthRefreshInterval",
435 "sourceControlWriterModelSelection",
436 "textGenerationModelSelection",
437]);
438​
439// Preserve both enabled states because provider history cannot recover a new opt-in.
440const PERSISTED_SERVER_SETTINGS_DEFAULTS = {
441 ...DEFAULT_SERVER_SETTINGS,
442 providers: {
443 ...DEFAULT_SERVER_SETTINGS.providers,
444 cursor: { ...DEFAULT_SERVER_SETTINGS.providers.cursor, enabled: undefined },
445 grok: { ...DEFAULT_SERVER_SETTINGS.providers.grok, enabled: undefined },
446 opencode: { ...DEFAULT_SERVER_SETTINGS.providers.opencode, enabled: undefined },
447 },
448};
449​
450function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {
451 if (Array.isArray(current) || Array.isArray(defaults)) {
452 return Equal.equals(current, defaults) ? undefined : current;
453 }
454​
455 if (
456 current !== null &&
457 defaults !== null &&
458 typeof current === "object" &&
459 typeof defaults === "object"
460 ) {
461 const currentRecord = current as Record<string, unknown>;
462 const defaultsRecord = defaults as Record<string, unknown>;
463 const next: Record<string, unknown> = {};
464​
465 for (const key of Object.keys(currentRecord)) {
466 if (ATOMIC_SETTINGS_KEYS.has(key)) {
467 if (!Equal.equals(currentRecord[key], defaultsRecord[key])) {
468 next[key] = currentRecord[key];
469 }
470 } else {
471 const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]);
472 if (stripped !== undefined) {
473 next[key] = stripped;
474 }
475 }
476 }
477​
478 return Object.keys(next).length > 0 ? next : undefined;
479 }
480​
481 return Object.is(current, defaults) ? undefined : current;
483​
484const make = Effect.gen(function* () {
485 const { settingsPath } = yield* ServerConfig.ServerConfig;
486 const fs = yield* FileSystem.FileSystem;
487 const pathService = yield* Path.Path;
488 const secretStore = yield* ServerSecretStore.ServerSecretStore;
489 const sql = yield* SqlClient.SqlClient;
490 const writeSemaphore = yield* Semaphore.make(1);
491 const cacheKey = "settings" as const;
492 const changesPubSub = yield* PubSub.unbounded<ServerSettings>();
493 const startedRef = yield* Ref.make(false);
494 const startedDeferred = yield* Deferred.make<void, ServerSettingsError>();
495 const watcherScope = yield* Scope.make("sequential");
496 yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
497​
498 const emitChange = (settings: ServerSettings) =>
499 PubSub.publish(changesPubSub, settings).pipe(Effect.asVoid);
500​
501 const readConfigExists = fs.exists(settingsPath).pipe(
502 Effect.mapError(
503 (cause) =>
504 new ServerSettingsError({
505 settingsPath,
506 operation: "check-exists",
507 cause,
508 }),
509 ),
510 );
511​
512 const readRawConfig = fs.readFileString(settingsPath).pipe(
513 Effect.mapError(
514 (cause) =>
515 new ServerSettingsError({
516 settingsPath,
517 operation: "read-file",
518 cause,
519 }),
520 ),
521 );
522​
523 const loadSettingsFromDisk = Effect.gen(function* () {
524 let settings = DEFAULT_SERVER_SETTINGS;
525 let persisted: typeof PersistedOptionalProviderSettings.Type = {};
526​
527 if (yield* readConfigExists) {
528 const raw = yield* readRawConfig;
529 const decoded = decodeServerSettingsJsonExit(raw);
530 const persistedSettings = decodePersistedOptionalProviderSettingsJsonExit(raw);
531 if (persistedSettings._tag === "Success") {
532 persisted = persistedSettings.value;
533 }
534 if (decoded._tag === "Failure" || persistedSettings._tag === "Failure") {
535 const failure = decoded._tag === "Failure" ? decoded : persistedSettings;
536 if (failure._tag === "Failure") {
537 yield* Effect.logWarning("failed to parse settings.json, using defaults", {
538 path: settingsPath,
539 issues: Cause.pretty(failure.cause),
540 cause: failure.cause,
541 });
542 }
543 } else {
544 settings = decoded.value;
545 }
546 }
547​
548 const providerHistory = yield* sql<{
549 readonly providerName: string;
550 readonly providerInstanceId: string | null;
551 }>`
552 SELECT DISTINCT
553 provider_name AS "providerName",
554 provider_instance_id AS "providerInstanceId"
555 FROM projection_thread_sessions
556 WHERE provider_name IN ('cursor', 'grok', 'opencode')
557 UNION
558 SELECT DISTINCT
559 provider_name AS "providerName",
560 provider_instance_id AS "providerInstanceId"
561 FROM provider_session_runtime
562 WHERE provider_name IN ('cursor', 'grok', 'opencode')
563 `.pipe(
564 Effect.mapError(
565 (cause) =>
566 new ServerSettingsError({
567 settingsPath,
568 operation: "read-provider-history",
569 cause,
570 }),
571 ),
572 );
573​
574 return foldProviderInstanceEnabledFlags(
575 restoreUsedProviders(settings, persisted, providerHistory),
576 );
577 });
578​
579 const settingsCache = yield* Cache.make<typeof cacheKey, ServerSettings, ServerSettingsError>({
580 capacity: 1,
581 lookup: () => loadSettingsFromDisk,
582 });
583​
584 const getSettingsFromCache = Cache.get(settingsCache, cacheKey);
585​
586 const materializeProviderEnvironmentSecrets = (
587 settings: ServerSettings,
588 ): Effect.Effect<ServerSettings, ServerSettingsError> =>
589 Effect.gen(function* () {
590 const providerInstances: Record<string, ProviderInstanceConfig> = {
591 ...settings.providerInstances,
592 };
593 for (const [instanceId, instance] of Object.entries(settings.providerInstances)) {
594 if (!instance.environment) continue;
595 const environment: ProviderInstanceEnvironmentVariable[] = [];
596 for (const variable of instance.environment) {
597 if (!variable.sensitive || !variable.valueRedacted) {
598 environment.push(variable);
599 continue;
600 }
601 const secret = yield* secretStore
602 .get(providerEnvironmentSecretName({ instanceId, name: variable.name }))
603 .pipe(
604 Effect.mapError(
605 (cause) =>
606 new ServerSettingsError({
607 settingsPath,
608 operation: "read-secret",
609 providerInstanceId: instanceId,
610 environmentVariable: variable.name,
611 cause,
612 }),
613 ),
614 );
615 environment.push({
616 ...variable,
617 value: Option.isSome(secret) ? textDecoder.decode(secret.value) : "",
618 });
619 }
620 providerInstances[instanceId] = {
621 ...instance,
622 environment,
623 } satisfies ProviderInstanceConfig;
624 }
625 const usageLimitSources: Record<string, UsageLimitSourceConfig> = {};
626 for (const [sourceId, source] of Object.entries(settings.usageLimitSources)) {
627 if (source.managementKey !== USAGE_LIMIT_SOURCE_KEY_REDACTED) {
628 usageLimitSources[sourceId] = source;
629 continue;
630 }
631 const secret = yield* secretStore
632 .get(usageLimitSourceSecretName(sourceId))
633 .pipe(
634 Effect.mapError(
635 (cause) => new ServerSettingsError({ settingsPath, operation: "read-secret", cause }),
636 ),
637 );
638 usageLimitSources[sourceId] = {
639 ...source,
640 managementKey: Option.isSome(secret) ? textDecoder.decode(secret.value) : "",
641 };
642 }
643 return {
644 ...settings,
645 providerInstances: providerInstances as ServerSettings["providerInstances"],
646 usageLimitSources: usageLimitSources as ServerSettings["usageLimitSources"],
647 };
648 });
649​
650 const materializeChanges = (changes: Stream.Stream<ServerSettings>) =>
651 changes.pipe(
652 Stream.mapEffect((settings) =>
653 materializeProviderEnvironmentSecrets(settings).pipe(
654 Effect.catch((error: ServerSettingsError) =>
655 Effect.logWarning("failed to materialize provider environment secrets", {
656 operation: error.operation,
657 providerInstanceId: error.providerInstanceId,
658 environmentVariable: error.environmentVariable,
659 cause: error.cause,
660 }).pipe(Effect.as(settings)),
661 ),
662 ),
663 ),
664 Stream.map(resolveTextGenerationProvider),
665 );
666​
667 const persistProviderEnvironmentSecrets = (
668 current: ServerSettings,
669 next: ServerSettings,
670 ): Effect.Effect<
671 {
672 readonly settings: ServerSettings;
673 readonly secretWrites: ReadonlyArray<{
674 readonly secretName: string;
675 readonly value: Uint8Array;
676 readonly providerInstanceId?: string;
677 readonly environmentVariable?: string;
678 }>;
679 readonly staleSecretRemovals: ReadonlyArray<{
680 readonly secretName: string;
681 readonly operation: "remove-secret" | "remove-stale-secret";
682 readonly providerInstanceId?: string;
683 readonly environmentVariable?: string;
684 }>;
685 },
686 ServerSettingsError
687 > =>
688 Effect.sync(() => {
689 const providerInstances: Record<string, ProviderInstanceConfig> = {
690 ...next.providerInstances,
691 };
692 const secretWrites: Array<{
693 readonly secretName: string;
694 readonly value: Uint8Array;
695 readonly providerInstanceId?: string;
696 readonly environmentVariable?: string;
697 }> = [];
698 const staleSecretRemovals: Array<{
699 readonly secretName: string;
700 readonly operation: "remove-secret" | "remove-stale-secret";
701 readonly providerInstanceId?: string;
702 readonly environmentVariable?: string;
703 }> = [];
704​
705 const nextSecretKeys = new Set<string>();
706 for (const [instanceId, instance] of Object.entries(next.providerInstances)) {
707 if (!instance.environment) continue;
708 const environment: ProviderInstanceEnvironmentVariable[] = [];
709 for (const variable of instance.environment) {
710 const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name });
711 if (!variable.sensitive) {
712 staleSecretRemovals.push({
713 secretName,
714 operation: "remove-secret",
715 providerInstanceId: instanceId,
716 environmentVariable: variable.name,
717 });
718 environment.push(redactProviderEnvironmentVariable(variable));
719 continue;
720 }
721​
722 nextSecretKeys.add(secretName);
723 // Match the provider environment's last-value-wins behavior for duplicate names.
724 const previous = variable.valueRedacted
725 ? current.providerInstances[ProviderInstanceId.make(instanceId)]?.environment?.findLast(
726 (entry) => entry.name === variable.name,
727 )
728 : undefined;
729 const inlineValue =
730 previous?.sensitive && !previous.valueRedacted && previous.value.length > 0
731 ? previous.value
732 : undefined;
733 const value = inlineValue ?? variable.value;
734 if (!variable.valueRedacted || inlineValue !== undefined) {
735 if (value.length > 0) {
736 secretWrites.push({
737 secretName,
738 value: textEncoder.encode(value),
739 providerInstanceId: instanceId,
740 environmentVariable: variable.name,
741 });
742 environment.push({ ...variable, value: "", valueRedacted: true });
743 } else {
744 staleSecretRemovals.push({
745 secretName,
746 operation: "remove-secret",
747 providerInstanceId: instanceId,
748 environmentVariable: variable.name,
749 });
750 const { valueRedacted: _omit, ...rest } = variable;
751 environment.push(rest);
752 }
753 continue;
754 }
755​
756 environment.push(redactProviderEnvironmentVariable(variable));
757 }
758 providerInstances[instanceId] = {
759 ...instance,
760 environment,
761 } satisfies ProviderInstanceConfig;
762 }
763​
764 for (const [instanceId, instance] of Object.entries(current.providerInstances)) {
765 for (const variable of instance.environment ?? []) {
766 if (!variable.sensitive) continue;
767 const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name });
768 if (nextSecretKeys.has(secretName)) continue;
769 staleSecretRemovals.push({
770 secretName,
771 operation: "remove-stale-secret",
772 providerInstanceId: instanceId,
773 environmentVariable: variable.name,
774 });
775 }
776 }
777​
778 const usageLimitSources: Record<string, UsageLimitSourceConfig> = {};
779 for (const [sourceId, source] of Object.entries(next.usageLimitSources)) {
780 const secretName = usageLimitSourceSecretName(sourceId);
781 if (source.managementKey === USAGE_LIMIT_SOURCE_KEY_REDACTED) {
782 usageLimitSources[sourceId] = source;
783 continue;
784 }
785 if (source.managementKey.length === 0) {
786 staleSecretRemovals.push({ secretName, operation: "remove-secret" });
787 usageLimitSources[sourceId] = source;
788 continue;
789 }
790 secretWrites.push({ secretName, value: textEncoder.encode(source.managementKey) });
791 usageLimitSources[sourceId] = { ...source, managementKey: USAGE_LIMIT_SOURCE_KEY_REDACTED };
792 }
793 for (const sourceId of Object.keys(current.usageLimitSources)) {
794 if (sourceId in next.usageLimitSources) continue;
795 staleSecretRemovals.push({
796 secretName: usageLimitSourceSecretName(sourceId),
797 operation: "remove-stale-secret",
798 });
799 }
800​
801 return {
802 settings: {
803 ...next,
804 providerInstances: providerInstances as ServerSettings["providerInstances"],
805 usageLimitSources: usageLimitSources as ServerSettings["usageLimitSources"],
806 },
807 secretWrites,
808 staleSecretRemovals,
809 };
810 });
811​
812 const rollbackProviderEnvironmentSecretWrites = (
813 writes: ReadonlyArray<{
814 readonly secretName: string;
815 readonly previousValue: Option.Option<Uint8Array>;
816 readonly providerInstanceId?: string;
817 readonly environmentVariable?: string;
818 }>,
819 ) =>
820 Effect.forEach(
821 writes.toReversed(),
822 (write) =>
823 (Option.isSome(write.previousValue)
824 ? secretStore.set(write.secretName, write.previousValue.value)
825 : secretStore.remove(write.secretName)
826 ).pipe(
827 Effect.catch((cause) =>
828 Effect.logWarning("failed to roll back provider environment secret", {
829 providerInstanceId: write.providerInstanceId,
830 environmentVariable: write.environmentVariable,
831 cause,
832 }),
833 ),
834 ),
835 { discard: true },
836 );
837​
838 const applyProviderEnvironmentSecretChanges = (
839 writes: ReadonlyArray<{
840 readonly secretName: string;
841 readonly value: Uint8Array;
842 readonly providerInstanceId?: string;
843 readonly environmentVariable?: string;
844 }>,
845 removals: ReadonlyArray<{
846 readonly secretName: string;
847 readonly operation: "remove-secret" | "remove-stale-secret";
848 readonly providerInstanceId?: string;
849 readonly environmentVariable?: string;
850 }>,
851 ) => {
852 const applied: Array<{
853 readonly secretName: string;
854 readonly previousValue: Option.Option<Uint8Array>;
855 readonly providerInstanceId?: string;
856 readonly environmentVariable?: string;
857 }> = [];
858 const rollback = Effect.suspend(() => rollbackProviderEnvironmentSecretWrites(applied));
859 const changes = [
860 ...writes.map((write) => ({ ...write, kind: "write" as const })),
861 ...removals.map((removal) => ({ ...removal, kind: "remove" as const })),
862 ];
863 return Effect.forEach(
864 changes,
865 (change) =>
866 Effect.gen(function* () {
867 const previousValue = yield* secretStore.get(change.secretName).pipe(
868 Effect.mapError(
869 (cause) =>
870 new ServerSettingsError({
871 settingsPath,
872 operation: "read-secret",
873 providerInstanceId: change.providerInstanceId,
874 environmentVariable: change.environmentVariable,
875 cause,
876 }),
877 ),
878 );
879 yield* (
880 change.kind === "write"
881 ? secretStore.set(change.secretName, change.value)
882 : secretStore.remove(change.secretName)
883 ).pipe(
884 Effect.mapError(
885 (cause) =>
886 new ServerSettingsError({
887 settingsPath,
888 operation: change.kind === "write" ? "write-secret" : change.operation,
889 providerInstanceId: change.providerInstanceId,
890 environmentVariable: change.environmentVariable,
891 cause,
892 }),
893 ),
894 );
895 applied.push({ ...change, previousValue });
896 }),
897 { discard: true },
898 ).pipe(
899 Effect.tapError(() => rollback),
900 Effect.as(rollback),
901 );
902 };
903​
904 const writeSettingsAtomically = Effect.fnUntraced(
905 function* (settings: ServerSettings) {
906 const sparseSettingsJson = yield* encodeServerSettingsJson(
907 stripDefaultServerSettings(settings, PERSISTED_SERVER_SETTINGS_DEFAULTS) ?? {},
908 );
909​
910 return yield* writeFileStringAtomically({
911 filePath: settingsPath,
912 contents: `${sparseSettingsJson}\n`,
913 }).pipe(
914 Effect.provideService(FileSystem.FileSystem, fs),
915 Effect.provideService(Path.Path, pathService),
916 );
917 },
918 Effect.mapError(
919 (cause) =>
920 new ServerSettingsError({
921 settingsPath,
922 operation: "write-file",
923 cause,
924 }),
925 ),
926 );
927​
928 const updateAndPersistSettings = (
929 update: (current: ServerSettings) => Effect.Effect<ServerSettings, ServerSettingsError>,
930 ): Effect.Effect<ServerSettings, ServerSettingsError> =>
931 writeSemaphore.withPermits(1)(
932 Effect.gen(function* () {
933 const current = yield* getSettingsFromCache;
934 const updated = yield* update(current);
935 const persisted = yield* persistProviderEnvironmentSecrets(current, updated);
936 const next = yield* normalizeServerSettings(persisted.settings);
937 const materialized = yield* Effect.uninterruptibleMask(() =>
938 Effect.gen(function* () {
939 const rollbackSecretChanges = yield* applyProviderEnvironmentSecretChanges(
940 persisted.secretWrites,
941 persisted.staleSecretRemovals,
942 );
943 const materializedExit = yield* Effect.exit(
944 materializeProviderEnvironmentSecrets(next),
945 );
946 if (Exit.isFailure(materializedExit)) {
947 yield* rollbackSecretChanges;
948 return yield* Effect.failCause(materializedExit.cause);
949 }
950 const writeExit = yield* Effect.exit(writeSettingsAtomically(next));
951 if (Exit.isFailure(writeExit)) {
952 yield* rollbackSecretChanges;
953 return yield* Effect.failCause(writeExit.cause);
954 }
955 return materializedExit.value;
956 }),
957 );
958 yield* Cache.set(settingsCache, cacheKey, next);
959 yield* emitChange(next);
960 return resolveTextGenerationProvider(materialized);
961 }),
962 );
963​
964 const withSettingsSnapshot: ServerSettingsService["Service"]["withSettingsSnapshot"] = (use) =>
965 writeSemaphore.withPermits(1)(
966 getSettingsFromCache.pipe(
967 Effect.flatMap(materializeProviderEnvironmentSecrets),
968 Effect.map(resolveTextGenerationProvider),
969 Effect.flatMap(use),
970 ),
971 );
972​
973 const revalidateAndEmit = writeSemaphore.withPermits(1)(
974 Effect.gen(function* () {
975 yield* Cache.invalidate(settingsCache, cacheKey);
976 const settings = yield* getSettingsFromCache;
977 yield* emitChange(settings);
978 }),
979 );
980​
981 const startWatcher = Effect.gen(function* () {
982 const settingsDir = pathService.dirname(settingsPath);
983 const settingsFile = pathService.basename(settingsPath);
984 const settingsPathResolved = pathService.resolve(settingsPath);
985​
986 yield* fs.makeDirectory(settingsDir, { recursive: true }).pipe(
987 Effect.mapError(
988 (cause) =>
989 new ServerSettingsError({
990 settingsPath,
991 operation: "prepare-directory",
992 cause,
993 }),
994 ),
995 );
996​
997 const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
998​
999 // Debounce watch events so the file is fully written before we read it.
1000 // Editors emit multiple events per save (truncate, write, rename) and
1001 // `fs.watch` can fire before the content has been flushed to disk.
1002 const debouncedSettingsEvents = fs.watch(settingsDir).pipe(
1003 Stream.filter((event) => {
1004 return (
1005 event.path === settingsFile ||
1006 event.path === settingsPath ||
1007 pathService.resolve(settingsDir, event.path) === settingsPathResolved
1008 );
1009 }),
1010 Stream.debounce(Duration.millis(100)),
1011 );
1012​
1013 yield* Stream.runForEach(debouncedSettingsEvents, () => revalidateAndEmitSafely).pipe(
1014 Effect.ignoreCause({ log: true }),
1015 Effect.forkIn(watcherScope),
1016 Effect.asVoid,
1017 );
1018 });
1019​
1020 const start = Effect.gen(function* () {
1021 const shouldStart = yield* Ref.modify(startedRef, (started) => [!started, true]);
1022 if (!shouldStart) {
1023 return yield* Deferred.await(startedDeferred);
1025​
1026 const startup = Effect.gen(function* () {
1027 yield* startWatcher;
1028 yield* Cache.invalidate(settingsCache, cacheKey);
1029 yield* getSettingsFromCache;
1030 });
1031​
1032 const startupExit = yield* Effect.exit(startup);
1033 if (startupExit._tag === "Failure") {
1034 yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);
1035 return yield* Effect.failCause(startupExit.cause);
1037​
1038 yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
1039 });
1040​
1041 return {
1042 start,
1043 ready: Deferred.await(startedDeferred),
1044 getSettings: getSettingsFromCache.pipe(
1045 Effect.flatMap(materializeProviderEnvironmentSecrets),
1046 Effect.map(resolveTextGenerationProvider),
1047 ),
1048 updateSettings: (patch) =>
1049 updateAndPersistSettings((current) =>
1050 Effect.succeed(applyServerSettingsPatch(current, patch)),
1051 ),
1052 updateProviderInstance: (mutation, patch = {}) =>
1053 updateAndPersistSettings((current) =>
1054 Effect.gen(function* () {
1055 yield* ensureProviderInstanceMutationAllowed(current, mutation, settingsPath);
1056 const patched = applyServerSettingsPatch(current, patch);
1057 return applyProviderInstanceMutation(patched, mutation);
1058 }),
1059 ),
1060 withSettingsSnapshot,
1061 get streamChanges() {
1062 return materializeChanges(Stream.fromPubSub(changesPubSub));
1063 },
1064 get subscribeChanges() {
1065 return PubSub.subscribe(changesPubSub).pipe(
1066 Effect.map((subscription) => materializeChanges(Stream.fromSubscription(subscription))),
1067 );
1068 },
1069 } satisfies ServerSettingsService["Service"];
1070});
1071​
1072export const layer = Layer.effect(ServerSettingsService, make);