Repository navigation
Expand file tree
/
Copy pathserverSettings.ts
More file actions
1397 lines (1309 loc) · 52 KB
/
Copy pathserverSettings.ts
File metadata and controls
1397 lines (1309 loc) · 52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
DEFAULT_SERVER_SETTINGS,
ModelSelection,
ProjectId,
ProjectScript,
keepUnknownOverrideKeys,
ProjectSettingsOverrides,
type ProviderInstanceConfig,
type ProviderInstanceMutation,
defaultInstanceIdForDriver,
isProviderDriverKind,
ProviderDriverKind,
ProviderInstanceId,
resolveProviderInstanceEnabled,
ResponseStreamingMode,
ServerSettings,
ServerSettingsError,
type ServerSettingsPatch,
type ManagedPolicySummary,
globalIdleCompaction,
isSecretReference,
type SecretReference,
withIdleCompaction,
} from "@t3tools/contracts";
import * as Cache from "effect/Cache";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Equal from "effect/Equal";
import * as Effect from "effect/Effect";
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as SchemaTransformation from "effect/SchemaTransformation";
import * as Semaphore from "effect/Semaphore";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as SqlClient from "effect/sql/SqlClient";
import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
import { resolveSymlinkTarget } from "@t3tools/shared/symlink";
import * as ServerConfig from "./config.ts";
import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
import {
applyServerSettingsPatch,
deriveLegacyProjectOverrides,
fallbackTextGenerationModelSelection,
isModelSelectionProviderEnabled,
} from "@t3tools/shared/serverSettings";
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as ManagedPolicy from "./policy/ManagedPolicy.ts";
import { secretProviderDefinitions } from "./secrets/secretProviderDefinitions.ts";
import {
readSecretFieldValues,
sourceControlHostSecretName,
} from "./sourceControl/sourceControlHostSecrets.ts";
import {
mapSettingsSecrets,
mapSettingsSecretValues,
withoutRemovedSecretProviderReferences,
SECRET_REDACTED,
type SettingsSecret,
} from "./settingsSecrets.ts";
export {
resolveReviewGuideModelSelection,
resolveSourceControlWriterModelSelection,
} from "@t3tools/shared/serverSettings";
const encodeServerSettings = Schema.encodeEffect(ServerSettings);
const encodeServerSettingsJson = Schema.encodeUnknownEffect(fromJsonStringPretty(ServerSettings));
const decodeServerSettings = Schema.decodeUnknownEffect(ServerSettings);
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
// Conflicting flags resolve to false to preserve user disables.
const foldProviderInstanceEnabledFlags = (settings: ServerSettings): ServerSettings => {
let changed = false;
const providerInstances: Record<string, ProviderInstanceConfig> = {};
for (const [instanceId, instance] of Object.entries(settings.providerInstances)) {
const config = instance.config;
// Leave malformed flags for driver schema validation rather than silently repairing them.
if (
config === null ||
typeof config !== "object" ||
Array.isArray(config) ||
typeof (config as { readonly enabled?: unknown }).enabled !== "boolean"
) {
providerInstances[instanceId] = instance;
continue;
}
const { enabled: configEnabled, ...restConfig } = config as Record<string, unknown> & {
readonly enabled: boolean;
};
const resolved =
instance.enabled === false || configEnabled === false
? false
: (instance.enabled ?? configEnabled);
changed = true;
providerInstances[instanceId] = {
...instance,
enabled: resolved,
config: restConfig,
} satisfies ProviderInstanceConfig;
}
if (!changed) {
return settings;
}
return {
...settings,
providerInstances: providerInstances as ServerSettings["providerInstances"],
};
};
const normalizeServerSettings = (
settings: ServerSettings,
): Effect.Effect<ServerSettings, ServerSettingsError> =>
encodeServerSettings(settings).pipe(
Effect.flatMap(decodeServerSettings),
Effect.map(foldProviderInstanceEnabledFlags),
Effect.map((next) => withIdleCompaction(next, globalIdleCompaction(next))),
Effect.map((next) => ({ ...next, ...deriveLegacyProjectOverrides(next) })),
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath: "<memory>",
operation: "normalize",
cause,
}),
),
);
export function redactServerSettingsForClient(
settings: ServerSettings,
client: { readonly secretReferences: boolean },
): ServerSettings {
const redacted = mapSettingsSecrets(settings, (secret) =>
secret.sensitive
? { value: "", redacted: secret.redacted || secret.value.length > 0 }
: { value: secret.value, redacted: false },
);
// Older clients decode secret fields as strings and fail on a reference, so they see a saved secret.
const shaped = client.secretReferences
? redacted
: mapSettingsSecretValues(redacted, (value) =>
isSecretReference(value) ? SECRET_REDACTED : value,
);
return { ...shaped, secretProviders: withoutUnknownSecretProviderConfigs(shaped) };
}
/** A client shown a reference as a saved secret sends that marker back; it keeps the reference. */
function withEchoedSecretReferences(current: ServerSettings, next: ServerSettings): ServerSettings {
const references = new Map<string, SecretReference>();
mapSettingsSecretValues(current, (value, secretName) => {
if (isSecretReference(value)) references.set(secretName, value);
return value;
});
if (references.size === 0) return next;
return mapSettingsSecretValues(next, (value, secretName) =>
value === SECRET_REDACTED ? (references.get(secretName) ?? value) : value,
);
}
// A newer kind's config may hold credentials this build cannot recognize, so it never leaves the server.
function withoutUnknownSecretProviderConfigs(
settings: ServerSettings,
): ServerSettings["secretProviders"] {
return Object.fromEntries(
Object.entries(settings.secretProviders).map(([id, entry]) => {
if (secretProviderConfigGuards.has(entry.kind)) return [id, entry];
const { config: _config, ...envelope } = entry;
return [id, envelope];
}),
) as ServerSettings["secretProviders"];
}
export function applyProviderInstanceMutation(
settings: ServerSettings,
mutation: ProviderInstanceMutation,
): ServerSettings {
const providerInstances = { ...settings.providerInstances };
if (mutation.operation === "upsert" || mutation.operation === "create") {
providerInstances[mutation.instanceId] = mutation.instance;
} else {
delete providerInstances[mutation.instanceId];
}
return { ...settings, providerInstances };
}
const secretProviderConfigGuards = new Map(
secretProviderDefinitions.definitions.map((definition) => [
definition.kind as string,
Schema.is(definition.configSchema),
]),
);
// Rejects a kind this server has not loaded rather than storing a config it cannot check.
function ensureSecretProviderWritesAllowed(
patch: ServerSettingsPatch,
settingsPath: string,
): Effect.Effect<void, ServerSettingsError> {
for (const [id, entry] of Object.entries(patch.secretProviders ?? {})) {
if (entry === null) continue;
const isConfig = secretProviderConfigGuards.get(entry.kind);
const problem =
isConfig === undefined
? `Unsupported secret provider kind: ${entry.kind}.`
: isConfig(entry.config)
? undefined
: `Invalid ${entry.kind} config for secret provider ${id}.`;
if (problem !== undefined) {
return Effect.fail(
new ServerSettingsError({
settingsPath,
operation: "write-secret-provider",
cause: new Error(problem),
}),
);
}
}
return Effect.void;
}
function ensureProviderInstanceMutationAllowed(
settings: ServerSettings,
mutation: ProviderInstanceMutation,
settingsPath: string,
): Effect.Effect<void, ServerSettingsError> {
if (
mutation.operation === "create" &&
settings.providerInstances[mutation.instanceId] !== undefined
) {
return Effect.fail(
new ServerSettingsError({
settingsPath,
operation: "create-provider-instance",
providerInstanceId: mutation.instanceId,
}),
);
}
return Effect.void;
}
export class ServerSettingsService extends Context.Service<
ServerSettingsService,
{
readonly start: Effect.Effect<void, ServerSettingsError>;
readonly ready: Effect.Effect<void, ServerSettingsError>;
/** The administrator's policy as clients see it; absent when unmanaged. */
readonly managedPolicy?: ManagedPolicySummary | undefined;
readonly getSettings: Effect.Effect<ServerSettings, ServerSettingsError>;
readonly updateSettings: (
patch: ServerSettingsPatch,
) => Effect.Effect<ServerSettings, ServerSettingsError>;
readonly updateProviderInstance: (
mutation: ProviderInstanceMutation,
patch?: ServerSettingsPatch,
) => Effect.Effect<ServerSettings, ServerSettingsError>;
readonly withSettingsSnapshot: <A, E, R>(
use: (settings: ServerSettings) => Effect.Effect<A, E, R>,
) => Effect.Effect<A, E | ServerSettingsError, R>;
readonly streamChanges: Stream.Stream<ServerSettings>;
/** Subscribe before reading a snapshot to retain changes before lazy stream startup. */
readonly subscribeChanges: Effect.Effect<Stream.Stream<ServerSettings>, never, Scope.Scope>;
}
>()("t3/serverSettings/ServerSettingsService") {
static readonly layerTest = (
overrides: DeepPartial<ServerSettings> = {},
managedPolicy?: ManagedPolicySummary,
) => layerTest(overrides, managedPolicy);
}
const makeTest = Effect.fn("serverSettings.makeTest")(function* (
overrides: DeepPartial<ServerSettings> = {},
managedPolicy?: ManagedPolicySummary,
) {
const { automaticGitFetchInterval, providerHealthRefreshInterval, ...overridesForMerge } =
overrides;
const merged = deepMerge(DEFAULT_SERVER_SETTINGS, overridesForMerge);
const initialSettings = yield* normalizeServerSettings({
...merged,
...(automaticGitFetchInterval !== undefined
? { automaticGitFetchInterval: automaticGitFetchInterval as Duration.Duration }
: {}),
...(providerHealthRefreshInterval !== undefined
? { providerHealthRefreshInterval: providerHealthRefreshInterval as Duration.Duration }
: {}),
});
const currentSettingsRef = yield* Ref.make<ServerSettings>(initialSettings);
const writeSemaphore = yield* Semaphore.make(1);
const getSettings = Ref.get(currentSettingsRef).pipe(Effect.map(resolveTextGenerationProvider));
const updateTestSettings = (
update: (current: ServerSettings) => Effect.Effect<ServerSettings, ServerSettingsError>,
): Effect.Effect<ServerSettings, ServerSettingsError> =>
writeSemaphore.withPermits(1)(
Ref.get(currentSettingsRef).pipe(
Effect.flatMap(update),
Effect.flatMap(normalizeServerSettings),
Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
Effect.map(resolveTextGenerationProvider),
),
);
return {
managedPolicy,
start: Effect.void,
ready: Effect.void,
getSettings,
updateSettings: (patch) =>
updateTestSettings((currentSettings) =>
Effect.succeed(applyServerSettingsPatch(currentSettings, patch)),
),
updateProviderInstance: (mutation, patch = {}) =>
updateTestSettings((currentSettings) =>
Effect.gen(function* () {
yield* ensureProviderInstanceMutationAllowed(currentSettings, mutation, "test settings");
const patched = applyServerSettingsPatch(currentSettings, patch);
return applyProviderInstanceMutation(patched, mutation);
}),
),
withSettingsSnapshot: (use) =>
writeSemaphore.withPermits(1)(getSettings.pipe(Effect.flatMap(use))),
streamChanges: Stream.empty,
subscribeChanges: Effect.succeed(Stream.empty),
} satisfies ServerSettingsService["Service"];
});
/** Test settings; `managedPolicy` only tells consumers a policy applies, it does not lock values. */
export const layerTest = (
overrides: DeepPartial<ServerSettings> = {},
managedPolicy?: ManagedPolicySummary,
) => Layer.effect(ServerSettingsService, makeTest(overrides, managedPolicy));
// Accept retired token delivery only on load so one old value cannot reset all settings.
const PersistedResponseStreamingMode = Schema.Union([
ResponseStreamingMode,
Schema.Literal("token"),
]).pipe(
Schema.decodeTo(
ResponseStreamingMode,
SchemaTransformation.transform({
decode: (mode) => (mode === "token" ? "paragraph" : mode),
encode: (mode) => mode,
}),
),
);
const PersistedServerSettings = Schema.Struct({
...ServerSettings.fields,
responseStreamingMode: PersistedResponseStreamingMode.pipe(
Schema.withDecodingDefault(Effect.succeed("paragraph" as const)),
),
projectSettingsOverrides: Schema.Record(
ProjectId,
keepUnknownOverrideKeys(
Schema.Struct({
...ProjectSettingsOverrides.fields,
responseStreamingMode: Schema.optionalKey(PersistedResponseStreamingMode),
}),
),
).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
});
// Parse first and decode second, so a managed policy can fill its defaults in between.
const decodeSettingsFileJsonExit = Schema.decodeUnknownExit(fromLenientJson(Schema.Unknown));
const decodePersistedServerSettingsExit = Schema.decodeUnknownExit(PersistedServerSettings);
const LegacyProviderSettingsJson = fromLenientJson(
Schema.Struct({
providers: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),
bitbucket: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),
github: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),
}),
);
const decodeLegacyProviderSettingsJsonExit = Schema.decodeUnknownExit(LegacyProviderSettingsJson);
const LEGACY_BITBUCKET_SECRET_NAMES: Readonly<Record<string, string>> = {
accessToken: "bitbucket-access-token",
apiToken: "bitbucket-api-token",
};
const legacyGitHubTokenSecretName = (host: string) =>
`github-token-${Buffer.from(host.trim().toLowerCase(), "utf8").toString("base64url")}`;
function migrateLegacySourceControlSettings(
settings: ServerSettings,
legacy: {
readonly bitbucket?: Readonly<Record<string, unknown>> | undefined;
readonly github?: Readonly<Record<string, unknown>> | undefined;
},
): {
readonly settings: ServerSettings;
readonly secretMoves: ReadonlyArray<{ readonly from: string; readonly to: string }>;
} {
const sourceControlHosts = { ...settings.sourceControlHosts };
const secretMoves: Array<{ readonly from: string; readonly to: string }> = [];
if (legacy.bitbucket !== undefined && sourceControlHosts.bitbucket === undefined) {
sourceControlHosts.bitbucket = legacy.bitbucket;
for (const [field, from] of Object.entries(LEGACY_BITBUCKET_SECRET_NAMES)) {
if (legacy.bitbucket[field] !== SECRET_REDACTED) continue;
secretMoves.push({
from,
to: sourceControlHostSecretName({ kind: "bitbucket", field, serverHost: null }),
});
}
}
if (legacy.github !== undefined && sourceControlHosts.github === undefined) {
sourceControlHosts.github = legacy.github;
for (const [serverHost, value] of readSecretFieldValues(legacy.github.tokens)) {
if (serverHost === null || value !== SECRET_REDACTED) continue;
secretMoves.push({
from: legacyGitHubTokenSecretName(serverHost),
to: sourceControlHostSecretName({ kind: "github", field: "tokens", serverHost }),
});
}
}
return { settings: { ...settings, sourceControlHosts }, secretMoves };
}
const HISTORY_RESTORED_DRIVERS: ReadonlySet<ProviderDriverKind> = new Set(
["cursor", "grok", "opencode"].map((driver) => ProviderDriverKind.make(driver)),
);
function migrateLegacyProviderSettings(
settings: ServerSettings,
legacyProviders: Readonly<Record<string, unknown>>,
providerHistory: ReadonlyArray<{
readonly providerName: string;
readonly providerInstanceId: string | null;
}>,
): ServerSettings {
const usedProviders = new Set<string>(providerHistory.map(({ providerName }) => providerName));
const usedProviderInstances = new Set<string>(
providerHistory.map(
({ providerName, providerInstanceId }) => providerInstanceId ?? providerName,
),
);
const providerInstances: Record<ProviderInstanceId, ProviderInstanceConfig> = {};
for (const [instanceId, instance] of Object.entries(settings.providerInstances) as Array<
[ProviderInstanceId, ProviderInstanceConfig]
>) {
providerInstances[instanceId] =
instance.enabled === undefined &&
HISTORY_RESTORED_DRIVERS.has(instance.driver) &&
usedProviderInstances.has(instanceId)
? { ...instance, enabled: true }
: instance;
}
const legacyEntries = new Map(Object.entries(legacyProviders));
for (const driver of HISTORY_RESTORED_DRIVERS) {
if (!legacyEntries.has(driver)) legacyEntries.set(driver, {});
}
for (const [kind, blob] of legacyEntries) {
if (!isProviderDriverKind(kind) || blob === null || typeof blob !== "object") continue;
if (Array.isArray(blob)) continue;
const driver = kind;
const instanceId = defaultInstanceIdForDriver(driver);
if (Object.hasOwn(providerInstances, instanceId)) continue;
const { enabled: rawEnabled, ...config } = blob as Record<string, unknown>;
const explicitEnabled = typeof rawEnabled === "boolean" ? rawEnabled : undefined;
const enabled =
explicitEnabled ??
(HISTORY_RESTORED_DRIVERS.has(driver) && usedProviders.has(driver) ? true : undefined);
const driverDefault = resolveProviderInstanceEnabled({ driver, config: {} });
if (Object.keys(config).length === 0 && (enabled === undefined || enabled === driverDefault)) {
continue;
}
providerInstances[instanceId] = {
driver,
...(enabled === undefined ? {} : { enabled }),
config,
} satisfies ProviderInstanceConfig;
}
return {
...settings,
providerInstances,
};
}
const ACP_REGISTRY_DRIVER = ProviderDriverKind.make("acpRegistry");
function selectionSupportsTextGeneration(
settings: ServerSettings,
selection: ModelSelection,
): boolean {
return settings.providerInstances[selection.instanceId]?.driver !== ACP_REGISTRY_DRIVER;
}
type DriverAllowed = (driver: ProviderDriverKind) => boolean;
const anyDriver: DriverAllowed = () => true;
function resolveTextGenerationProvider(
settings: ServerSettings,
isDriverAllowed: DriverAllowed = anyDriver,
): ServerSettings {
const selection = settings.textGenerationModelSelection;
return isModelSelectionProviderEnabled(settings, selection) &&
selectionSupportsTextGeneration(settings, selection) &&
isDriverAllowed(
settings.providerInstances[selection.instanceId]?.driver ??
ProviderDriverKind.make(selection.instanceId),
)
? settings
: fallbackTextGenerationProvider(settings, isDriverAllowed);
}
function fallbackTextGenerationProvider(
settings: ServerSettings,
isDriverAllowed: DriverAllowed,
): ServerSettings {
const fallback = fallbackTextGenerationModelSelection(
settings.providerInstances,
(instanceId, driver) =>
// A default instance id can be configured with another driver.
isDriverAllowed(settings.providerInstances[instanceId]?.driver ?? driver) &&
resolveProviderInstanceEnabled(
settings.providerInstances[instanceId] ?? { driver, config: {} },
),
{ defaultModelSelection: settings.defaultModelSelection },
);
return fallback === null ? settings : { ...settings, textGenerationModelSelection: fallback };
}
const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set([
"backgroundActivity",
"automaticGitFetchInterval",
"providerHealthRefreshInterval",
"sourceControlWriterModelSelection",
"reviewGuideModelSelection",
"textGenerationModelSelection",
"fallbackModelSelection",
"pullRequestMergeMethod",
// Empty by default, these hold one whole value, which a managed policy can default.
...Object.entries(DEFAULT_SERVER_SETTINGS).flatMap(([key, value]) =>
value === null ? [key] : [],
),
]);
function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {
if (Array.isArray(current) || Array.isArray(defaults)) {
return Equal.equals(current, defaults) ? undefined : current;
}
if (
current !== null &&
defaults !== null &&
typeof current === "object" &&
typeof defaults === "object"
) {
const currentRecord = current as Record<string, unknown>;
const defaultsRecord = defaults as Record<string, unknown>;
const next: Record<string, unknown> = {};
for (const key of Object.keys(currentRecord)) {
if (ATOMIC_SETTINGS_KEYS.has(key)) {
if (!Equal.equals(currentRecord[key], defaultsRecord[key])) {
next[key] = currentRecord[key];
}
} else {
const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]);
if (stripped !== undefined) {
next[key] = stripped;
}
}
}
return Object.keys(next).length > 0 ? next : undefined;
}
return Object.is(current, defaults) ? undefined : current;
}
const decodeProjectScriptsJson = Schema.decodeUnknownOption(
Schema.fromJsonString(Schema.Array(ProjectScript)),
);
const decodeModelSelectionJson = Schema.decodeUnknownOption(
Schema.fromJsonString(Schema.NullOr(ModelSelection)),
);
interface LegacyProjectSettingsRow {
readonly projectId: string;
readonly defaultModelSelection: string | null;
readonly defaultThreadEnvMode: string | null;
readonly autoPull: number;
readonly scripts: string;
}
// projectSettingsFolded prevents restarts from undoing later UI resets.
function foldLegacyProjectSettings(
settings: ServerSettings,
rows: ReadonlyArray<LegacyProjectSettingsRow>,
): ServerSettings {
if (settings.projectSettingsFolded) return settings;
if (
rows.length === 0 &&
Object.keys(settings.projectAgentBrowserAccessOverrides).length === 0 &&
Object.keys(settings.projectAutoPullOverrides).length === 0 &&
Object.keys(settings.projectScriptOverrides).length === 0
) {
return settings;
}
const entries: Record<string, ProjectSettingsOverrides> = {
...settings.projectSettingsOverrides,
};
const set = <K extends keyof ProjectSettingsOverrides>(
projectId: string,
key: K,
value: ProjectSettingsOverrides[K] | undefined,
) => {
if (value === undefined) return;
const entry = entries[projectId] ?? {};
if (Object.hasOwn(entry, key)) return;
entries[projectId] = { ...entry, [key]: value };
};
for (const [projectId, value] of Object.entries(settings.projectAgentBrowserAccessOverrides)) {
set(projectId, "enableAgentBrowserAccess", value);
}
for (const [projectId, value] of Object.entries(settings.projectAutoPullOverrides)) {
set(projectId, "defaultAutoPull", value);
}
// A stored null resets to machine defaults, so the project's aggregate scripts must not resurface.
const resetScripts = new Set<string>();
for (const [projectId, value] of Object.entries(settings.projectScriptOverrides)) {
if (value === null) resetScripts.add(projectId);
else set(projectId, "defaultProjectScripts", value);
}
for (const row of rows) {
const model = decodeModelSelectionJson(row.defaultModelSelection ?? "null");
if (Option.isSome(model) && model.value !== null) {
set(row.projectId, "defaultModelSelection", model.value);
}
if (row.defaultThreadEnvMode === "local" || row.defaultThreadEnvMode === "worktree") {
set(row.projectId, "defaultThreadEnvMode", row.defaultThreadEnvMode);
}
if (row.autoPull === 1) set(row.projectId, "defaultAutoPull", true);
const scripts = decodeProjectScriptsJson(row.scripts);
if (Option.isSome(scripts) && scripts.value.length > 0 && !resetScripts.has(row.projectId)) {
set(row.projectId, "defaultProjectScripts", scripts.value);
}
}
const projectSettingsOverrides = Object.fromEntries(
Object.entries(entries).filter(([, entry]) => Object.keys(entry).length > 0),
);
return {
...settings,
projectSettingsOverrides,
projectSettingsFolded: true,
...deriveLegacyProjectOverrides({ projectSettingsOverrides }),
};
}
const make = Effect.gen(function* () {
const { settingsPath } = yield* ServerConfig.ServerConfig;
const fs = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
const secretStore = yield* ServerSecretStore.ServerSecretStore;
const sql = yield* SqlClient.SqlClient;
const {
settings: managed,
providers: managedProviders,
summary: managedPolicy,
} = yield* ManagedPolicy.ManagedPolicy;
// Locks are laid over every settings value that leaves this service, never persisted.
const toEffective = (settings: ServerSettings) =>
resolveTextGenerationProvider(
managedProviders.applyLimits(managed.applyLocks(settings)),
managedProviders.isDriverAllowed,
);
const writeSemaphore = yield* Semaphore.make(1);
const cacheKey = "settings" as const;
const changesPubSub = yield* PubSub.unbounded<ServerSettings>();
const startedRef = yield* Ref.make(false);
const startedDeferred = yield* Deferred.make<void, ServerSettingsError>();
const watcherScope = yield* Scope.make("sequential");
yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
const emitChange = (settings: ServerSettings) =>
PubSub.publish(changesPubSub, settings).pipe(Effect.asVoid);
const readConfigExists = fs.exists(settingsPath).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath,
operation: "check-exists",
cause,
}),
),
);
const readRawConfig = fs.readFileString(settingsPath).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath,
operation: "read-file",
cause,
}),
),
);
// The file before this write, parsed; only read when policy defaults need it.
const readStoredSettings = Effect.gen(function* () {
if (!(yield* readConfigExists)) return undefined;
const parsed = decodeSettingsFileJsonExit(yield* readRawConfig);
return Exit.isSuccess(parsed) ? parsed.value : undefined;
});
const writeSettingsAtomically = Effect.fnUntraced(
function* (settings: ServerSettings) {
const stripped = stripDefaultServerSettings(settings, managed.defaults) ?? {};
const sparseSettingsJson = yield* encodeServerSettingsJson(
managed.keepStored === undefined
? stripped
: managed.keepStored(stripped, settings, yield* readStoredSettings, (key) =>
ATOMIC_SETTINGS_KEYS.has(key),
),
);
return yield* writeFileStringAtomically({
filePath: settingsPath,
contents: `${sparseSettingsJson}\n`,
}).pipe(
Effect.provideService(FileSystem.FileSystem, fs),
Effect.provideService(Path.Path, pathService),
);
},
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath,
operation: "write-file",
cause,
}),
),
);
const moveInlineSettingsSecrets = Effect.fn("serverSettings.moveInlineSettingsSecrets")(
function* (settings: ServerSettings) {
const pending: SettingsSecret[] = [];
mapSettingsSecrets(settings, (secret) => {
if (secret.kind === "field" && !secret.redacted && secret.value.length > 0) {
pending.push(secret);
}
return secret;
});
const moved = new Set<string>();
for (const secret of pending) {
const stored = yield* secretStore
.set(secret.secretName, textEncoder.encode(secret.value))
.pipe(
Effect.as(true),
Effect.catch(() =>
Effect.logWarning("failed to move a settings secret into the secret store").pipe(
Effect.as(false),
),
),
);
if (stored) moved.add(secret.secretName);
}
if (moved.size === 0) return settings;
return mapSettingsSecrets(settings, (secret) =>
moved.has(secret.secretName) ? { value: "", redacted: true } : secret,
);
},
);
const loadSettingsFromDisk = Effect.gen(function* () {
let settings = managed.defaults;
let legacyProviders: Readonly<Record<string, unknown>> | undefined;
let legacySourceControl: Parameters<typeof migrateLegacySourceControlSettings>[1] = {};
let parseFailure = Option.none<unknown>();
if (yield* readConfigExists) {
const raw = yield* readRawConfig;
const parsed = decodeSettingsFileJsonExit(raw);
const decoded = Exit.isFailure(parsed)
? parsed
: decodePersistedServerSettingsExit(managed.withDefaults(parsed.value));
const legacySettings = decodeLegacyProviderSettingsJsonExit(raw);
if (legacySettings._tag === "Success") {
legacyProviders = legacySettings.value.providers;
legacySourceControl = {
bitbucket: legacySettings.value.bitbucket,
github: legacySettings.value.github,
};
}
if (decoded._tag === "Failure" || legacySettings._tag === "Failure") {
const failure = decoded._tag === "Failure" ? decoded : legacySettings;
// The file may hold an opt-out we can no longer read; never resume threads on a guess.
settings = { ...managed.defaults, continueThreadsAfterServerUpdate: false };
if (failure._tag === "Failure") {
parseFailure = Option.some(Cause.squash(failure.cause));
yield* Effect.logWarning("failed to parse settings.json, using defaults", {
path: settingsPath,
issues: Cause.pretty(failure.cause),
cause: failure.cause,
});
}
} else {
settings = decoded.value;
}
}
// Settings saved by a server that kept the mode in `compactIdleThreads` move
// it to `idleCompaction`, so that switch goes to clients as a boolean. The
// defaults gain the field too, which tells clients this server reads modes.
settings = withIdleCompaction(settings, globalIdleCompaction(settings));
// A file that failed to decode must stay on disk for the user to repair.
const settingsFileTrusted = Option.isNone(parseFailure);
const providerHistory = yield* sql<{
readonly providerName: string;
readonly providerInstanceId: string | null;
}>`
SELECT DISTINCT
provider_name AS "providerName",
provider_instance_id AS "providerInstanceId"
FROM projection_thread_sessions
WHERE provider_name IN ('cursor', 'grok', 'opencode')
UNION
SELECT DISTINCT
provider_name AS "providerName",
provider_instance_id AS "providerInstanceId"
FROM provider_session_runtime
WHERE provider_name IN ('cursor', 'grok', 'opencode')
`.pipe(
NodeSqliteClient.readOnly,
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath,
operation: "read-provider-history",
cause,
}),
),
);
const legacyProjectRows =
settings.projectSettingsFolded || !settingsFileTrusted
? []
: yield* sql<LegacyProjectSettingsRow>`
SELECT
project_id AS "projectId",
default_model_selection_json AS "defaultModelSelection",
default_thread_env_mode AS "defaultThreadEnvMode",
auto_pull AS "autoPull",
scripts_json AS "scripts"
FROM projection_projects
WHERE deleted_at IS NULL
`.pipe(
NodeSqliteClient.readOnly,
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath,
operation: "read-project-settings",
cause,
}),
),
);
const loaded = foldProviderInstanceEnabledFlags(
legacyProviders === undefined
? settings
: migrateLegacyProviderSettings(settings, legacyProviders, providerHistory),
);
const folded = settingsFileTrusted
? foldLegacyProjectSettings(loaded, legacyProjectRows)
: loaded;
// Remove retired keys only after copying secrets and writing the new file; failures retry on next load.
const legacySecretsCopied = yield* Effect.forEach(
settingsFileTrusted
? migrateLegacySourceControlSettings(folded, legacySourceControl).secretMoves
: [],
(move) =>
secretStore.get(move.from).pipe(
Effect.flatMap((secret) =>
Option.isNone(secret) ? Effect.void : secretStore.set(move.to, secret.value),
),
Effect.as(true),
Effect.catch(() =>
Effect.logWarning("failed to copy a source control secret to its new name", {
secretName: move.to,
}).pipe(Effect.as(false)),
),
),
).pipe(Effect.map((copied) => copied.every(Boolean)));
const hasLegacySourceControl =
settingsFileTrusted &&
legacySecretsCopied &&
(legacySourceControl.bitbucket !== undefined || legacySourceControl.github !== undefined);
const sourceControlMigration = hasLegacySourceControl
? migrateLegacySourceControlSettings(folded, legacySourceControl)
: { settings: folded, secretMoves: [] };
const migrated = settingsFileTrusted
? yield* moveInlineSettingsSecrets(sourceControlMigration.settings)
: folded;
if (
migrated !== loaded ||
(settingsFileTrusted && legacyProviders !== undefined) ||
hasLegacySourceControl
) {
yield* writeSettingsAtomically(migrated);
for (const move of sourceControlMigration.secretMoves) {
yield* secretStore.remove(move.from).pipe(Effect.ignore);
}
}
return { settings: migrated, parseFailure };
});
const settingsCache = yield* Cache.makeWith((_key: typeof cacheKey) => loadSettingsFromDisk, {
capacity: 1,
timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero),
});
const getSettingsFromCache = Cache.get(settingsCache, cacheKey).pipe(
Effect.map((loaded) => loaded.settings),
);
const reloadSettings = Cache.invalidate(settingsCache, cacheKey).pipe(
Effect.andThen(Cache.get(settingsCache, cacheKey)),
);
const materializeSettingsSecrets = Effect.fn("serverSettings.materializeSettingsSecrets")(
function* (settings: ServerSettings): Effect.fn.Return<ServerSettings, ServerSettingsError> {
const storedSecrets = new Map<string, string>();
const pending = new Map<string, SettingsSecret>();
mapSettingsSecrets(settings, (secret) => {
if (secret.sensitive && secret.redacted) pending.set(secret.secretName, secret);
return secret;
});
for (const secret of pending.values()) {
const value = yield* secretStore.get(secret.secretName).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath,
operation: "read-secret",
providerInstanceId: secret.providerInstanceId,
environmentVariable: secret.environmentVariable,
cause,
}),
),
);
storedSecrets.set(
secret.secretName,
Option.isSome(value) ? textDecoder.decode(value.value) : "",
);
}
return mapSettingsSecrets(settings, (secret) => ({
value:
secret.sensitive && secret.redacted
? (storedSecrets.get(secret.secretName) ?? "")
: secret.value,
redacted: secret.sensitive && secret.kind === "environment" && secret.redacted,
}));
},
);
// Background sweeps read settings every few seconds; reading secret files each time is wasted.
// Every secret write rewrites the settings file, so a new cached object implies fresh secrets.
// A read that overlaps a secret write may see files a rollback then restores, so it is not kept.
let materialized: { readonly source: ServerSettings; readonly value: ServerSettings } | null =
null;
let secretWriteGeneration = 0;
const invalidateMaterialized = Effect.sync(() => {
secretWriteGeneration++;
materialized = null;
});
const getMaterializedSettings = getSettingsFromCache.pipe(
Effect.flatMap((source) => {
if (materialized?.source === source) return Effect.succeed(materialized.value);
const generation = secretWriteGeneration;
return materializeSettingsSecrets(source).pipe(
Effect.map(toEffective),
Effect.tap((value) =>
Effect.sync(() => {
if (generation === secretWriteGeneration) materialized = { source, value };
}),
),
);
}),
);