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_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
15 DEFAULT_SERVER_SETTINGS,
16 type ModelSelection,
17 type ProviderKind,
18 ServerSettings,
19 ServerSettingsError,
20 type ServerSettingsPatch,
21} from "@t3tools/contracts";
22import {
23 Cache,
24 Deferred,
25 Duration,
26 Effect,
27 Exit,
28 FileSystem,
29 Layer,
30 Path,
31 Equal,
32 PubSub,
33 Ref,
34 Schema,
35 SchemaIssue,
36 Scope,
37 Context,
38 Stream,
39 Cause,
40} from "effect";
41import * as Semaphore from "effect/Semaphore";
42import { writeFileStringAtomically } from "./atomicWrite.ts";
43import { ServerConfig } from "./config.ts";
44import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
45import { fromLenientJson } from "@t3tools/shared/schemaJson";
46import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
47
48export interface ServerSettingsShape {
49 /** Start the settings runtime and attach file watching. */
50 readonly start: Effect.Effect<void, ServerSettingsError>;
51
52 /** Await settings runtime readiness. */
53 readonly ready: Effect.Effect<void, ServerSettingsError>;
54
55 /** Read the current settings. */
56 readonly getSettings: Effect.Effect<ServerSettings, ServerSettingsError>;
57
58 /** Patch settings and persist. Returns the new full settings object. */
59 readonly updateSettings: (
60 patch: ServerSettingsPatch,
61 ) => Effect.Effect<ServerSettings, ServerSettingsError>;
62
63 /** Stream of settings change events. */
64 readonly streamChanges: Stream.Stream<ServerSettings>;
65}
66
67export class ServerSettingsService extends Context.Service<
68 ServerSettingsService,
69 ServerSettingsShape
70>()("t3/serverSettings/ServerSettingsService") {
71 static readonly layerTest = (overrides: DeepPartial<ServerSettings> = {}) =>
72 Layer.effect(
73 ServerSettingsService,
74 Effect.gen(function* () {
75 const currentSettingsRef = yield* Ref.make<ServerSettings>(
76 deepMerge(DEFAULT_SERVER_SETTINGS, overrides),
77 );
78
79 return {
80 start: Effect.void,
81 ready: Effect.void,
82 getSettings: Ref.get(currentSettingsRef),
83 updateSettings: (patch) =>
84 Ref.get(currentSettingsRef).pipe(
85 Effect.flatMap((currentSettings) =>
86 Schema.decodeEffect(ServerSettings)(
87 applyServerSettingsPatch(currentSettings, patch),
88 ).pipe(
89 Effect.mapError(
90 (cause) =>
91 new ServerSettingsError({
92 settingsPath: "<memory>",
93 detail: `failed to normalize server settings: ${SchemaIssue.makeFormatterDefault()(cause.issue)}`,
94 cause,
95 }),
96 ),
97 ),
98 ),
99 Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
100 ),
101 streamChanges: Stream.empty,
102 } satisfies ServerSettingsShape;
103 }),
104 );
105}
106
107const ServerSettingsJson = fromLenientJson(ServerSettings);
108
109const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent", "opencode", "cursor"];
110
111/**
112 * Ensure the `textGenerationModelSelection` points to an enabled provider.
113 * If the selected provider is disabled, fall back to the first enabled
114 * provider with its default model. This is applied at read-time so the
115 * persisted preference is preserved for when a provider is re-enabled.
116 */
117function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings {
118 const selection = settings.textGenerationModelSelection;
119 if (settings.providers[selection.provider].enabled) {
120 return settings;
121 }
122
123 const fallback = PROVIDER_ORDER.find((p) => settings.providers[p].enabled);
124 if (!fallback) {
125 // No providers enabled — return as-is; callers will report the error.
126 return settings;
127 }
128
129 return {
130 ...settings,
131 textGenerationModelSelection: {
132 provider: fallback,
133 model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback],
134 } as ModelSelection,
135 };
136}
137
138// Values under these keys are compared as a whole — never stripped field-by-field.
139const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set(["textGenerationModelSelection"]);
140
141function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {
142 if (Array.isArray(current) || Array.isArray(defaults)) {
143 return Equal.equals(current, defaults) ? undefined : current;
144 }
145
146 if (
147 current !== null &&
148 defaults !== null &&
149 typeof current === "object" &&
150 typeof defaults === "object"
151 ) {
152 const currentRecord = current as Record<string, unknown>;
153 const defaultsRecord = defaults as Record<string, unknown>;
154 const next: Record<string, unknown> = {};
155
156 for (const key of Object.keys(currentRecord)) {
157 if (ATOMIC_SETTINGS_KEYS.has(key)) {
158 if (!Equal.equals(currentRecord[key], defaultsRecord[key])) {
159 next[key] = currentRecord[key];
160 }
161 } else {
162 const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]);
163 if (stripped !== undefined) {
164 next[key] = stripped;
165 }
166 }
167 }
168
169 return Object.keys(next).length > 0 ? next : undefined;
170 }
171
172 return Object.is(current, defaults) ? undefined : current;
173}
174
175const makeServerSettings = Effect.gen(function* () {
176 const { settingsPath } = yield* ServerConfig;
177 const fs = yield* FileSystem.FileSystem;
178 const pathService = yield* Path.Path;
179 const writeSemaphore = yield* Semaphore.make(1);
180 const cacheKey = "settings" as const;
181 const changesPubSub = yield* PubSub.unbounded<ServerSettings>();
182 const startedRef = yield* Ref.make(false);
183 const startedDeferred = yield* Deferred.make<void, ServerSettingsError>();
184 const watcherScope = yield* Scope.make("sequential");
185 yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
186
187 const emitChange = (settings: ServerSettings) =>
188 PubSub.publish(changesPubSub, settings).pipe(Effect.asVoid);
189
190 const readConfigExists = fs.exists(settingsPath).pipe(
191 Effect.mapError(
192 (cause) =>
193 new ServerSettingsError({
194 settingsPath,
195 detail: "failed to check settings file existence",
196 cause,
197 }),
198 ),
199 );
200
201 const readRawConfig = fs.readFileString(settingsPath).pipe(
202 Effect.mapError(
203 (cause) =>
204 new ServerSettingsError({
205 settingsPath,
206 detail: "failed to read settings file",
207 cause,
208 }),
209 ),
210 );
211
212 const loadSettingsFromDisk = Effect.gen(function* () {
213 if (!(yield* readConfigExists)) {
214 return DEFAULT_SERVER_SETTINGS;
215 }
216
217 const raw = yield* readRawConfig;
218 const decoded = Schema.decodeUnknownExit(ServerSettingsJson)(raw);
219 if (decoded._tag === "Failure") {
220 yield* Effect.logWarning("failed to parse settings.json, using defaults", {
221 path: settingsPath,
222 issues: Cause.pretty(decoded.cause),
223 });
224 return DEFAULT_SERVER_SETTINGS;
225 }
226 return decoded.value;
227 });
228
229 const settingsCache = yield* Cache.make<typeof cacheKey, ServerSettings, ServerSettingsError>({
230 capacity: 1,
231 lookup: () => loadSettingsFromDisk,
232 });
233
234 const getSettingsFromCache = Cache.get(settingsCache, cacheKey);
235
236 const writeSettingsAtomically = (settings: ServerSettings) => {
237 const sparseSettings = stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {};
238
239 return writeFileStringAtomically({
240 filePath: settingsPath,
241 contents: `${JSON.stringify(sparseSettings, null, 2)}\n`,
242 }).pipe(
243 Effect.provideService(FileSystem.FileSystem, fs),
244 Effect.provideService(Path.Path, pathService),
245 Effect.mapError(
246 (cause) =>
247 new ServerSettingsError({
248 settingsPath,
249 detail: "failed to write settings file",
250 cause,
251 }),
252 ),
253 );
254 };
255
256 const revalidateAndEmit = writeSemaphore.withPermits(1)(
257 Effect.gen(function* () {
258 yield* Cache.invalidate(settingsCache, cacheKey);
259 const settings = yield* getSettingsFromCache;
260 yield* emitChange(settings);
261 }),
262 );
263
264 const startWatcher = Effect.gen(function* () {
265 const settingsDir = pathService.dirname(settingsPath);
266 const settingsFile = pathService.basename(settingsPath);
267 const settingsPathResolved = pathService.resolve(settingsPath);
268
269 yield* fs.makeDirectory(settingsDir, { recursive: true }).pipe(
270 Effect.mapError(
271 (cause) =>
272 new ServerSettingsError({
273 settingsPath,
274 detail: "failed to prepare settings directory",
275 cause,
276 }),
277 ),
278 );
279
280 const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
281
282 // Debounce watch events so the file is fully written before we read it.
283 // Editors emit multiple events per save (truncate, write, rename) and
284 // `fs.watch` can fire before the content has been flushed to disk.
285 const debouncedSettingsEvents = fs.watch(settingsDir).pipe(
286 Stream.filter((event) => {
287 return (
288 event.path === settingsFile ||
289 event.path === settingsPath ||
290 pathService.resolve(settingsDir, event.path) === settingsPathResolved
291 );
292 }),
293 Stream.debounce(Duration.millis(100)),
294 );
295
296 yield* Stream.runForEach(debouncedSettingsEvents, () => revalidateAndEmitSafely).pipe(
297 Effect.ignoreCause({ log: true }),
298 Effect.forkIn(watcherScope),
299 Effect.asVoid,
300 );
301 });
302
303 const start = Effect.gen(function* () {
304 const shouldStart = yield* Ref.modify(startedRef, (started) => [!started, true]);
305 if (!shouldStart) {
306 return yield* Deferred.await(startedDeferred);
307 }
308
309 const startup = Effect.gen(function* () {
310 yield* startWatcher;
311 yield* Cache.invalidate(settingsCache, cacheKey);
312 yield* getSettingsFromCache;
313 });
314
315 const startupExit = yield* Effect.exit(startup);
316 if (startupExit._tag === "Failure") {
317 yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);
318 return yield* Effect.failCause(startupExit.cause);
319 }
320
321 yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
322 });
323
324 return {
325 start,
326 ready: Deferred.await(startedDeferred),
327 getSettings: getSettingsFromCache.pipe(Effect.map(resolveTextGenerationProvider)),
328 updateSettings: (patch) =>
329 writeSemaphore.withPermits(1)(
330 Effect.gen(function* () {
331 const current = yield* getSettingsFromCache;
332 const next = yield* Schema.decodeEffect(ServerSettings)(
333 applyServerSettingsPatch(current, patch),
334 ).pipe(
335 Effect.mapError(
336 (cause) =>
337 new ServerSettingsError({
338 settingsPath: "<memory>",
339 detail: `failed to normalize server settings: ${SchemaIssue.makeFormatterDefault()(cause.issue)}`,
340 cause,
341 }),
342 ),
343 );
344 yield* writeSettingsAtomically(next);
345 yield* Cache.set(settingsCache, cacheKey, next);
346 yield* emitChange(next);
347 return resolveTextGenerationProvider(next);
348 }),
349 ),
350 get streamChanges() {
351 return Stream.fromPubSub(changesPubSub).pipe(Stream.map(resolveTextGenerationProvider));
352 },
353 } satisfies ServerSettingsShape;
354});
355
356export const ServerSettingsLive = Layer.effect(ServerSettingsService, makeServerSettings);