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

serverSettings.ts

1,229 lines44.4 KB

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