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

serverSettings.ts

1,318 lines48.1 KB

1/**
2 * ServerSettings - Server-authoritative settings service.
3 *
4 * Owns persistence, validation, and change notification of settings that affect
5 * server-side behavior (binary paths, streaming mode, env mode, custom models,
6 * text generation model selection).
7 *
8 * Follows the same pattern as `keybindings.ts`: JSON file + Cache + PubSub +
9 * Semaphore + FileSystem.watch for concurrency and external edit detection.
10 *
11 * @module ServerSettings
12 */
13import {
14 DEFAULT_TEXT_GENERATION_MODEL,
15 DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER,
16 DEFAULT_MODEL_BY_PROVIDER,
17 DEFAULT_SERVER_SETTINGS,
18 ModelSelection,
19 ProjectId,
20 ProjectScript,
21 ProjectSettingsOverrides,
22 type ProviderInstanceConfig,
23 type ProviderInstanceEnvironmentVariable,
24 type UsageLimitSourceConfig,
25 type ProviderInstanceMutation,
26 ProviderDriverKind,
27 ProviderInstanceId,
28 resolveProviderInstanceEnabled,
29 ResponseStreamingMode,
30 ServerSettings,
31 ServerSettingsError,
32 type ServerSettingsPatch,
33} from "@t3tools/contracts";
34import * as Cache from "effect/Cache";
35import * as Cause from "effect/Cause";
36import * as Context from "effect/Context";
37import * as Deferred from "effect/Deferred";
38import * as Duration from "effect/Duration";
39import * as Equal from "effect/Equal";
40import * as Effect from "effect/Effect";
41import * as Exit from "effect/Exit";
42import * as FileSystem from "effect/FileSystem";
43import * as Layer from "effect/Layer";
44import * as Option from "effect/Option";
45import * as Path from "effect/Path";
46import * as PubSub from "effect/PubSub";
47import * as Ref from "effect/Ref";
48import * as Schema from "effect/Schema";
49import * as SchemaTransformation from "effect/SchemaTransformation";
50import * as Semaphore from "effect/Semaphore";
51import * as Scope from "effect/Scope";
52import * as Stream from "effect/Stream";
53import * as SqlClient from "effect/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")}`;
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")}`;
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 };
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 };
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 };
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;
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);
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 };
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;
446​
447function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings {
448 return isModelSelectionProviderEnabled(settings, settings.textGenerationModelSelection) &&
449 selectionSupportsTextGeneration(settings, settings.textGenerationModelSelection)
450 ? settings
451 : fallbackTextGenerationProvider(settings);
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 };
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;
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;
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 };
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 // A failed read is not kept: the next read retries instead of replaying the failure.
806 const settingsCache = yield* Cache.makeWith<typeof cacheKey, ServerSettings, ServerSettingsError>(
807 () => loadSettingsFromDisk,
808 {
809 capacity: 1,
810 timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero),
811 },
812 );
813​
814 const getSettingsFromCache = Cache.get(settingsCache, cacheKey);
815​
816 const materializeProviderEnvironmentSecrets = (
817 settings: ServerSettings,
818 ): Effect.Effect<ServerSettings, ServerSettingsError> =>
819 Effect.gen(function* () {
820 const providerInstances: Record<string, ProviderInstanceConfig> = {
821 ...settings.providerInstances,
822 };
823 for (const [instanceId, instance] of Object.entries(settings.providerInstances)) {
824 if (!instance.environment) continue;
825 const environment: ProviderInstanceEnvironmentVariable[] = [];
826 for (const variable of instance.environment) {
827 if (!variable.sensitive || !variable.valueRedacted) {
828 environment.push(variable);
829 continue;
830 }
831 const secret = yield* secretStore
832 .get(providerEnvironmentSecretName({ instanceId, name: variable.name }))
833 .pipe(
834 Effect.mapError(
835 (cause) =>
836 new ServerSettingsError({
837 settingsPath,
838 operation: "read-secret",
839 providerInstanceId: instanceId,
840 environmentVariable: variable.name,
841 cause,
842 }),
843 ),
844 );
845 environment.push({
846 ...variable,
847 value: Option.isSome(secret) ? textDecoder.decode(secret.value) : "",
848 });
849 }
850 providerInstances[instanceId] = {
851 ...instance,
852 environment,
853 } satisfies ProviderInstanceConfig;
854 }
855 const usageLimitSources: Record<string, UsageLimitSourceConfig> = {};
856 for (const [sourceId, source] of Object.entries(settings.usageLimitSources)) {
857 if (source.managementKey !== SECRET_REDACTED) {
858 usageLimitSources[sourceId] = source;
859 continue;
860 }
861 const secret = yield* secretStore
862 .get(usageLimitSourceSecretName(sourceId))
863 .pipe(
864 Effect.mapError(
865 (cause) => new ServerSettingsError({ settingsPath, operation: "read-secret", cause }),
866 ),
867 );
868 usageLimitSources[sourceId] = {
869 ...source,
870 managementKey: Option.isSome(secret) ? textDecoder.decode(secret.value) : "",
871 };
872 }
873 const bitbucket = { ...settings.bitbucket };
874 for (const field of BITBUCKET_SECRET_FIELDS) {
875 if (bitbucket[field] !== SECRET_REDACTED) continue;
876 const secret = yield* secretStore
877 .get(BITBUCKET_SECRET_NAMES[field])
878 .pipe(
879 Effect.mapError(
880 (cause) => new ServerSettingsError({ settingsPath, operation: "read-secret", cause }),
881 ),
882 );
883 bitbucket[field] = Option.isSome(secret) ? textDecoder.decode(secret.value) : "";
884 }
885 return {
886 ...settings,
887 providerInstances: providerInstances as ServerSettings["providerInstances"],
888 usageLimitSources: usageLimitSources as ServerSettings["usageLimitSources"],
889 bitbucket,
890 };
891 });
892​
893 const materializeChanges = (changes: Stream.Stream<ServerSettings>) =>
894 changes.pipe(
895 Stream.mapEffect((settings) =>
896 materializeProviderEnvironmentSecrets(settings).pipe(
897 Effect.catch((error: ServerSettingsError) =>
898 Effect.logWarning("failed to materialize provider environment secrets", {
899 operation: error.operation,
900 providerInstanceId: error.providerInstanceId,
901 environmentVariable: error.environmentVariable,
902 cause: error.cause,
903 }).pipe(Effect.as(settings)),
904 ),
905 ),
906 ),
907 Stream.map(resolveTextGenerationProvider),
908 );
909​
910 type SecretChange = {
911 readonly secretName: string;
912 readonly providerInstanceId?: string;
913 readonly environmentVariable?: string;
914 } & (
915 | { readonly kind: "write"; readonly value: Uint8Array }
916 | { readonly kind: "remove"; readonly operation: "remove-secret" | "remove-stale-secret" }
917 );
918​
919 const persistProviderEnvironmentSecrets = (current: ServerSettings, next: ServerSettings) =>
920 Effect.sync(() => {
921 const providerInstances: Record<string, ProviderInstanceConfig> = {
922 ...next.providerInstances,
923 };
924 const changes: SecretChange[] = [];
925​
926 const nextSecretKeys = new Set<string>();
927 for (const [instanceId, instance] of Object.entries(next.providerInstances)) {
928 if (!instance.environment) continue;
929 const environment: ProviderInstanceEnvironmentVariable[] = [];
930 for (const variable of instance.environment) {
931 const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name });
932 if (!variable.sensitive) {
933 changes.push({
934 kind: "remove",
935 secretName,
936 operation: "remove-secret",
937 providerInstanceId: instanceId,
938 environmentVariable: variable.name,
939 });
940 environment.push(redactProviderEnvironmentVariable(variable));
941 continue;
942 }
943​
944 nextSecretKeys.add(secretName);
945 // Match the provider environment's last-value-wins behavior for duplicate names.
946 const previous = variable.valueRedacted
947 ? current.providerInstances[ProviderInstanceId.make(instanceId)]?.environment?.findLast(
948 (entry) => entry.name === variable.name,
949 )
950 : undefined;
951 const inlineValue =
952 previous?.sensitive && !previous.valueRedacted && previous.value.length > 0
953 ? previous.value
954 : undefined;
955 const value = inlineValue ?? variable.value;
956 if (!variable.valueRedacted || inlineValue !== undefined) {
957 if (value.length > 0) {
958 changes.push({
959 kind: "write",
960 secretName,
961 value: textEncoder.encode(value),
962 providerInstanceId: instanceId,
963 environmentVariable: variable.name,
964 });
965 environment.push({ ...variable, value: "", valueRedacted: true });
966 } else {
967 changes.push({
968 kind: "remove",
969 secretName,
970 operation: "remove-secret",
971 providerInstanceId: instanceId,
972 environmentVariable: variable.name,
973 });
974 const { valueRedacted: _omit, ...rest } = variable;
975 environment.push(rest);
976 }
977 continue;
978 }
979​
980 environment.push(redactProviderEnvironmentVariable(variable));
981 }
982 providerInstances[instanceId] = {
983 ...instance,
984 environment,
985 } satisfies ProviderInstanceConfig;
986 }
987​
988 for (const [instanceId, instance] of Object.entries(current.providerInstances)) {
989 for (const variable of instance.environment ?? []) {
990 if (!variable.sensitive) continue;
991 const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name });
992 if (nextSecretKeys.has(secretName)) continue;
993 changes.push({
994 kind: "remove",
995 secretName,
996 operation: "remove-stale-secret",
997 providerInstanceId: instanceId,
998 environmentVariable: variable.name,
999 });
1002​
1003 const usageLimitSources: Record<string, UsageLimitSourceConfig> = {};
1004 for (const [sourceId, source] of Object.entries(next.usageLimitSources)) {
1005 const secretName = usageLimitSourceSecretName(sourceId);
1006 if (source.managementKey === SECRET_REDACTED) {
1007 usageLimitSources[sourceId] = source;
1008 continue;
1010 if (source.managementKey.length === 0) {
1011 changes.push({ kind: "remove", secretName, operation: "remove-secret" });
1012 usageLimitSources[sourceId] = source;
1013 continue;
1015 changes.push({
1016 kind: "write",
1017 secretName,
1018 value: textEncoder.encode(source.managementKey),
1019 });
1020 usageLimitSources[sourceId] = { ...source, managementKey: SECRET_REDACTED };
1022 for (const sourceId of Object.keys(current.usageLimitSources)) {
1023 if (sourceId in next.usageLimitSources) continue;
1024 changes.push({
1025 kind: "remove",
1026 secretName: usageLimitSourceSecretName(sourceId),
1027 operation: "remove-stale-secret",
1028 });
1030​
1031 const bitbucket = { ...next.bitbucket };
1032 for (const field of BITBUCKET_SECRET_FIELDS) {
1033 let value = bitbucket[field];
1034 if (value === SECRET_REDACTED) {
1035 // The marker keeps what is saved. A plaintext value hand-edited into settings.json
1036 // is not in the secret store yet, so move it there instead of dropping it.
1037 const inline = current.bitbucket[field];
1038 if (inline === SECRET_REDACTED || inline.length === 0) continue;
1039 value = inline;
1041 const secretName = BITBUCKET_SECRET_NAMES[field];
1042 if (value.length === 0) {
1043 changes.push({ kind: "remove", secretName, operation: "remove-secret" });
1044 continue;
1046 changes.push({ kind: "write", secretName, value: textEncoder.encode(value) });
1047 bitbucket[field] = SECRET_REDACTED;
1049​
1050 return {
1051 settings: {
1052 ...next,
1053 providerInstances: providerInstances as ServerSettings["providerInstances"],
1054 usageLimitSources: usageLimitSources as ServerSettings["usageLimitSources"],
1055 bitbucket,
1056 },
1057 changes,
1058 };
1059 });
1060​
1061 const rollbackProviderEnvironmentSecretWrites = (
1062 writes: ReadonlyArray<{
1063 readonly secretName: string;
1064 readonly previousValue: Option.Option<Uint8Array>;
1065 readonly providerInstanceId?: string;
1066 readonly environmentVariable?: string;
1067 }>,
1068 ) =>
1069 Effect.forEach(
1070 writes.toReversed(),
1071 (write) =>
1072 (Option.isSome(write.previousValue)
1073 ? secretStore.set(write.secretName, write.previousValue.value)
1074 : secretStore.remove(write.secretName)
1075 ).pipe(
1076 Effect.catch((cause) =>
1077 Effect.logWarning("failed to roll back provider environment secret", {
1078 providerInstanceId: write.providerInstanceId,
1079 environmentVariable: write.environmentVariable,
1080 cause,
1081 }),
1082 ),
1083 ),
1084 { discard: true },
1085 );
1086​
1087 const applyProviderEnvironmentSecretChanges = (changes: ReadonlyArray<SecretChange>) => {
1088 const applied: Array<{
1089 readonly secretName: string;
1090 readonly previousValue: Option.Option<Uint8Array>;
1091 readonly providerInstanceId?: string;
1092 readonly environmentVariable?: string;
1093 }> = [];
1094 const rollback = Effect.suspend(() => rollbackProviderEnvironmentSecretWrites(applied));
1095 return Effect.forEach(
1096 changes,
1097 (change) =>
1098 Effect.gen(function* () {
1099 const previousValue = yield* secretStore.get(change.secretName).pipe(
1100 Effect.mapError(
1101 (cause) =>
1102 new ServerSettingsError({
1103 settingsPath,
1104 operation: "read-secret",
1105 providerInstanceId: change.providerInstanceId,
1106 environmentVariable: change.environmentVariable,
1107 cause,
1108 }),
1109 ),
1110 );
1111 // A store operation may mutate before reporting an error (for example chmod after rename).
1112 applied.push({ ...change, previousValue });
1113 yield* (
1114 change.kind === "write"
1115 ? secretStore.set(change.secretName, change.value)
1116 : secretStore.remove(change.secretName)
1117 ).pipe(
1118 Effect.mapError(
1119 (cause) =>
1120 new ServerSettingsError({
1121 settingsPath,
1122 operation: change.kind === "write" ? "write-secret" : change.operation,
1123 providerInstanceId: change.providerInstanceId,
1124 environmentVariable: change.environmentVariable,
1125 cause,
1126 }),
1127 ),
1128 );
1129 }),
1130 { discard: true },
1131 ).pipe(
1132 Effect.tapError(() => rollback),
1133 Effect.as(rollback),
1134 );
1135 };
1136​
1137 const updateAndPersistSettings = (
1138 update: (current: ServerSettings) => Effect.Effect<ServerSettings, ServerSettingsError>,
1139 ): Effect.Effect<ServerSettings, ServerSettingsError> =>
1140 writeSemaphore.withPermits(1)(
1141 Effect.gen(function* () {
1142 const current = yield* getSettingsFromCache;
1143 const updated = yield* update(current);
1144 const persisted = yield* persistProviderEnvironmentSecrets(current, updated);
1145 const next = yield* normalizeServerSettings(persisted.settings);
1146 const materialized = yield* Effect.uninterruptibleMask(() =>
1147 Effect.gen(function* () {
1148 const rollbackSecretChanges = yield* applyProviderEnvironmentSecretChanges(
1149 persisted.changes,
1150 );
1151 const materializedExit = yield* Effect.exit(
1152 materializeProviderEnvironmentSecrets(next),
1153 );
1154 if (Exit.isFailure(materializedExit)) {
1155 yield* rollbackSecretChanges;
1156 return yield* Effect.failCause(materializedExit.cause);
1158 const writeExit = yield* Effect.exit(writeSettingsAtomically(next));
1159 if (Exit.isFailure(writeExit)) {
1160 yield* rollbackSecretChanges;
1161 return yield* Effect.failCause(writeExit.cause);
1163 return materializedExit.value;
1164 }),
1165 );
1166 yield* Cache.set(settingsCache, cacheKey, next);
1167 yield* emitChange(next);
1168 return resolveTextGenerationProvider(materialized);
1169 }),
1170 );
1171​
1172 const withSettingsSnapshot: ServerSettingsService["Service"]["withSettingsSnapshot"] = (use) =>
1173 writeSemaphore.withPermits(1)(
1174 getSettingsFromCache.pipe(
1175 Effect.flatMap(materializeProviderEnvironmentSecrets),
1176 Effect.map(resolveTextGenerationProvider),
1177 Effect.flatMap(use),
1178 ),
1179 );
1180​
1181 const revalidateAndEmit = writeSemaphore.withPermits(1)(
1182 Effect.gen(function* () {
1183 yield* Cache.invalidate(settingsCache, cacheKey);
1184 const settings = yield* getSettingsFromCache;
1185 yield* emitChange(settings);
1186 }),
1187 );
1188​
1189 const watchFileChanges = (filePath: string) => {
1190 const directory = pathService.dirname(filePath);
1191 const fileName = pathService.basename(filePath);
1192 const resolvedFilePath = pathService.resolve(filePath);
1193 return fs
1194 .watch(directory)
1195 .pipe(
1196 Stream.filter(
1197 (event) =>
1198 event.path === fileName ||
1199 event.path === filePath ||
1200 pathService.resolve(directory, event.path) === resolvedFilePath,
1201 ),
1202 );
1203 };
1204​
1205 const startWatcher = Effect.gen(function* () {
1206 const settingsDir = pathService.dirname(settingsPath);
1207​
1208 yield* fs.makeDirectory(settingsDir, { recursive: true }).pipe(
1209 Effect.mapError(
1210 (cause) =>
1211 new ServerSettingsError({
1212 settingsPath,
1213 operation: "prepare-directory",
1214 cause,
1215 }),
1216 ),
1217 );
1218​
1219 const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
1220​
1221 // A symlinked settings file is rewritten in its destination's directory,
1222 // which a watch on the link's directory never sees. The link is resolved
1223 // again whenever it changes, so repointing it moves the watch along.
1224 const watchLinkTarget = Effect.gen(function* () {
1225 const linkTargetPath = yield* resolveSymlinkTarget(settingsPath).pipe(
1226 Effect.provideService(FileSystem.FileSystem, fs),
1227 Effect.provideService(Path.Path, pathService),
1228 );
1229 if (linkTargetPath === pathService.resolve(settingsPath)) {
1230 return Option.none<string>();
1232 yield* fs
1233 .makeDirectory(pathService.dirname(linkTargetPath), { recursive: true })
1234 .pipe(Effect.ignore({ log: true }));
1235 return Option.some(linkTargetPath);
1236 }).pipe(Effect.orElseSucceed(() => Option.none<string>()));
1237​
1238 const initialLinkTarget = yield* watchLinkTarget;
1239 const linkTargetEvents = Stream.make(initialLinkTarget).pipe(
1240 Stream.concat(watchFileChanges(settingsPath).pipe(Stream.mapEffect(() => watchLinkTarget))),
1241 Stream.changes,
1242 Stream.switchMap(
1243 Option.match({
1244 onNone: () => Stream.empty,
1245 onSome: (linkTargetPath) =>
1246 watchFileChanges(linkTargetPath).pipe(Stream.ignore({ log: true })),
1247 }),
1248 ),
1249 );
1250​
1251 // Debounce watch events so the file is fully written before we read it.
1252 // Editors emit multiple events per save (truncate, write, rename) and
1253 // `fs.watch` can fire before the content has been flushed to disk.
1254 const debouncedSettingsEvents = Stream.merge(
1255 watchFileChanges(settingsPath),
1256 linkTargetEvents,
1257 ).pipe(Stream.debounce(Duration.millis(100)));
1258​
1259 yield* Stream.runForEach(debouncedSettingsEvents, () => revalidateAndEmitSafely).pipe(
1260 Effect.ignoreCause({ log: true }),
1261 Effect.forkIn(watcherScope),
1262 Effect.asVoid,
1263 );
1264 });
1265​
1266 const start = Effect.gen(function* () {
1267 const shouldStart = yield* Ref.modify(startedRef, (started) => [!started, true]);
1268 if (!shouldStart) {
1269 return yield* Deferred.await(startedDeferred);
1271​
1272 const startup = Effect.gen(function* () {
1273 yield* startWatcher;
1274 yield* Cache.invalidate(settingsCache, cacheKey);
1275 yield* getSettingsFromCache;
1276 });
1277​
1278 const startupExit = yield* Effect.exit(startup);
1279 if (startupExit._tag === "Failure") {
1280 yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);
1281 return yield* Effect.failCause(startupExit.cause);
1283​
1284 yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
1285 });
1286​
1287 return {
1288 start,
1289 ready: Deferred.await(startedDeferred),
1290 getSettings: getSettingsFromCache.pipe(
1291 Effect.flatMap(materializeProviderEnvironmentSecrets),
1292 Effect.map(resolveTextGenerationProvider),
1293 ),
1294 updateSettings: (patch) =>
1295 updateAndPersistSettings((current) =>
1296 Effect.succeed(applyServerSettingsPatch(current, patch)),
1297 ),
1298 updateProviderInstance: (mutation, patch = {}) =>
1299 updateAndPersistSettings((current) =>
1300 Effect.gen(function* () {
1301 yield* ensureProviderInstanceMutationAllowed(current, mutation, settingsPath);
1302 const patched = applyServerSettingsPatch(current, patch);
1303 return applyProviderInstanceMutation(patched, mutation);
1304 }),
1305 ),
1306 withSettingsSnapshot,
1307 get streamChanges() {
1308 return materializeChanges(Stream.fromPubSub(changesPubSub));
1309 },
1310 get subscribeChanges() {
1311 return PubSub.subscribe(changesPubSub).pipe(
1312 Effect.map((subscription) => materializeChanges(Stream.fromSubscription(subscription))),
1313 );
1314 },
1315 } satisfies ServerSettingsService["Service"];
1316});
1317​
1318export const layer = Layer.effect(ServerSettingsService, make);