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