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