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

serverSettings.ts

1,198 lines43.3 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 type SecretChange = {
849 readonly secretName: string;
850 readonly providerInstanceId?: string;
851 readonly environmentVariable?: string;
852 } & (
853 | { readonly kind: "write"; readonly value: Uint8Array }
854 | { readonly kind: "remove"; readonly operation: "remove-secret" | "remove-stale-secret" }
855 );
856​
857 const persistProviderEnvironmentSecrets = (current: ServerSettings, next: ServerSettings) =>
858 Effect.sync(() => {
859 const providerInstances: Record<string, ProviderInstanceConfig> = {
860 ...next.providerInstances,
861 };
862 const changes: SecretChange[] = [];
863​
864 const nextSecretKeys = new Set<string>();
865 for (const [instanceId, instance] of Object.entries(next.providerInstances)) {
866 if (!instance.environment) continue;
867 const environment: ProviderInstanceEnvironmentVariable[] = [];
868 for (const variable of instance.environment) {
869 const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name });
870 if (!variable.sensitive) {
871 changes.push({
872 kind: "remove",
873 secretName,
874 operation: "remove-secret",
875 providerInstanceId: instanceId,
876 environmentVariable: variable.name,
877 });
878 environment.push(redactProviderEnvironmentVariable(variable));
879 continue;
880 }
881​
882 nextSecretKeys.add(secretName);
883 // Match the provider environment's last-value-wins behavior for duplicate names.
884 const previous = variable.valueRedacted
885 ? current.providerInstances[ProviderInstanceId.make(instanceId)]?.environment?.findLast(
886 (entry) => entry.name === variable.name,
887 )
888 : undefined;
889 const inlineValue =
890 previous?.sensitive && !previous.valueRedacted && previous.value.length > 0
891 ? previous.value
892 : undefined;
893 const value = inlineValue ?? variable.value;
894 if (!variable.valueRedacted || inlineValue !== undefined) {
895 if (value.length > 0) {
896 changes.push({
897 kind: "write",
898 secretName,
899 value: textEncoder.encode(value),
900 providerInstanceId: instanceId,
901 environmentVariable: variable.name,
902 });
903 environment.push({ ...variable, value: "", valueRedacted: true });
904 } else {
905 changes.push({
906 kind: "remove",
907 secretName,
908 operation: "remove-secret",
909 providerInstanceId: instanceId,
910 environmentVariable: variable.name,
911 });
912 const { valueRedacted: _omit, ...rest } = variable;
913 environment.push(rest);
914 }
915 continue;
916 }
917​
918 environment.push(redactProviderEnvironmentVariable(variable));
919 }
920 providerInstances[instanceId] = {
921 ...instance,
922 environment,
923 } satisfies ProviderInstanceConfig;
924 }
925​
926 for (const [instanceId, instance] of Object.entries(current.providerInstances)) {
927 for (const variable of instance.environment ?? []) {
928 if (!variable.sensitive) continue;
929 const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name });
930 if (nextSecretKeys.has(secretName)) continue;
931 changes.push({
932 kind: "remove",
933 secretName,
934 operation: "remove-stale-secret",
935 providerInstanceId: instanceId,
936 environmentVariable: variable.name,
937 });
938 }
939 }
940​
941 const usageLimitSources: Record<string, UsageLimitSourceConfig> = {};
942 for (const [sourceId, source] of Object.entries(next.usageLimitSources)) {
943 const secretName = usageLimitSourceSecretName(sourceId);
944 if (source.managementKey === USAGE_LIMIT_SOURCE_KEY_REDACTED) {
945 usageLimitSources[sourceId] = source;
946 continue;
947 }
948 if (source.managementKey.length === 0) {
949 changes.push({ kind: "remove", secretName, operation: "remove-secret" });
950 usageLimitSources[sourceId] = source;
951 continue;
952 }
953 changes.push({
954 kind: "write",
955 secretName,
956 value: textEncoder.encode(source.managementKey),
957 });
958 usageLimitSources[sourceId] = { ...source, managementKey: USAGE_LIMIT_SOURCE_KEY_REDACTED };
959 }
960 for (const sourceId of Object.keys(current.usageLimitSources)) {
961 if (sourceId in next.usageLimitSources) continue;
962 changes.push({
963 kind: "remove",
964 secretName: usageLimitSourceSecretName(sourceId),
965 operation: "remove-stale-secret",
966 });
967 }
968​
969 return {
970 settings: {
971 ...next,
972 providerInstances: providerInstances as ServerSettings["providerInstances"],
973 usageLimitSources: usageLimitSources as ServerSettings["usageLimitSources"],
974 },
975 changes,
976 };
977 });
978​
979 const rollbackProviderEnvironmentSecretWrites = (
980 writes: ReadonlyArray<{
981 readonly secretName: string;
982 readonly previousValue: Option.Option<Uint8Array>;
983 readonly providerInstanceId?: string;
984 readonly environmentVariable?: string;
985 }>,
986 ) =>
987 Effect.forEach(
988 writes.toReversed(),
989 (write) =>
990 (Option.isSome(write.previousValue)
991 ? secretStore.set(write.secretName, write.previousValue.value)
992 : secretStore.remove(write.secretName)
993 ).pipe(
994 Effect.catch((cause) =>
995 Effect.logWarning("failed to roll back provider environment secret", {
996 providerInstanceId: write.providerInstanceId,
997 environmentVariable: write.environmentVariable,
998 cause,
999 }),
1000 ),
1001 ),
1002 { discard: true },
1003 );
1004​
1005 const applyProviderEnvironmentSecretChanges = (changes: ReadonlyArray<SecretChange>) => {
1006 const applied: Array<{
1007 readonly secretName: string;
1008 readonly previousValue: Option.Option<Uint8Array>;
1009 readonly providerInstanceId?: string;
1010 readonly environmentVariable?: string;
1011 }> = [];
1012 const rollback = Effect.suspend(() => rollbackProviderEnvironmentSecretWrites(applied));
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 // A store operation may mutate before reporting an error (for example chmod after rename).
1030 applied.push({ ...change, previousValue });
1031 yield* (
1032 change.kind === "write"
1033 ? secretStore.set(change.secretName, change.value)
1034 : secretStore.remove(change.secretName)
1035 ).pipe(
1036 Effect.mapError(
1037 (cause) =>
1038 new ServerSettingsError({
1039 settingsPath,
1040 operation: change.kind === "write" ? "write-secret" : change.operation,
1041 providerInstanceId: change.providerInstanceId,
1042 environmentVariable: change.environmentVariable,
1043 cause,
1044 }),
1045 ),
1046 );
1047 }),
1048 { discard: true },
1049 ).pipe(
1050 Effect.tapError(() => rollback),
1051 Effect.as(rollback),
1052 );
1053 };
1054​
1055 const updateAndPersistSettings = (
1056 update: (current: ServerSettings) => Effect.Effect<ServerSettings, ServerSettingsError>,
1057 ): Effect.Effect<ServerSettings, ServerSettingsError> =>
1058 writeSemaphore.withPermits(1)(
1059 Effect.gen(function* () {
1060 const current = yield* getSettingsFromCache;
1061 const updated = yield* update(current);
1062 const persisted = yield* persistProviderEnvironmentSecrets(current, updated);
1063 const next = yield* normalizeServerSettings(persisted.settings);
1064 const materialized = yield* Effect.uninterruptibleMask(() =>
1065 Effect.gen(function* () {
1066 const rollbackSecretChanges = yield* applyProviderEnvironmentSecretChanges(
1067 persisted.changes,
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);
1076 const writeExit = yield* Effect.exit(writeSettingsAtomically(next));
1077 if (Exit.isFailure(writeExit)) {
1078 yield* rollbackSecretChanges;
1079 return yield* Effect.failCause(writeExit.cause);
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);
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);
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);