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

serverSettings.ts

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