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