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