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