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

serverSettings.ts

1,175 lines42.7 KB

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