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

serverSettings.ts

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