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

serverSettings.ts

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