Open History to see the last commit
1/**
2 * ProviderInstanceRegistryHydration — derive a `ProviderInstanceConfigMap`
3 * from `ServerSettings` and keep `ProviderInstanceRegistry` in sync with it.
4 *
5 * The server still reads two shapes:
6 *
7 * 1. `settings.providerInstances` — the new driver-agnostic map the
8 * registry expects. Keyed by `ProviderInstanceId`, values are
9 * `ProviderInstanceConfig` envelopes.
10 * 2. `settings.providers.<kind>` — the legacy single-instance-per-driver
11 * fields (`providers.codex`, `providers.claudeAgent`, …). These are
12 * the source of truth for every deployment that hasn't been migrated
13 * yet to an explicit `providerInstances` entry.
14 *
15 * This module bridges (2) into (1) and wires the resulting map into a
16 * mutable registry. For every built-in driver whose id is not already
17 * present in `providerInstances` (keyed on
18 * `defaultInstanceIdForDriver(driverKind)` — literally the driver kind as a
19 * routing slug), we synthesize an envelope from the legacy field. The
20 * registry decodes both flavours through the same `configSchema` and ends
21 * up with one uniform `ProviderInstance` per entry.
22 *
23 * Explicit `providerInstances` entries always win — users can already
24 * override the legacy `providers.<kind>` blob by authoring a
25 * `providerInstances.codex` entry with a matching driver, and we don't
26 * want the synthesized envelope to silently stomp their config.
27 *
28 * Hot-reload
29 * ----------
30 * On layer build we:
31 * 1. Read the current `ServerSettings` once and use it to seed the
32 * registry's initial state via `ProviderInstanceRegistryMutableLayer`.
33 * 2. Fork a daemon fiber (lifetime tied to the layer's scope) that
34 * acquires `ServerSettingsService.subscribeChanges` and calls
35 * `ProviderInstanceRegistryMutator.reconcile` on every emission.
36 *
37 * Failures inside the watcher are logged and swallowed so a single bad
38 * settings emission cannot kill the registry. Unknown drivers and invalid
39 * configs already round-trip through the registry's own "unavailable"
40 * shadow bucket.
41 *
42 * @module provider/Layers/ProviderInstanceRegistryHydration
43 */
44import {
45 defaultInstanceIdForDriver,
46 type ProviderInstanceConfig,
47 type ProviderInstanceConfigMap,
48 ServerSettings,
49} from "@t3tools/contracts";
50import * as Effect from "effect/Effect";
51import * as Layer from "effect/Layer";
52import * as Stream from "effect/Stream";
53
54import * as Settings from "../../serverSettings.ts";
55import { BUILT_IN_DRIVERS, type BuiltInDriversEnv } from "../builtInDrivers.ts";
56import * as ProviderInstanceRegistry from "../Services/ProviderInstanceRegistry.ts";
57import * as ProviderInstanceRegistryMutator from "../Services/ProviderInstanceRegistryMutator.ts";
58import { ProviderInstanceRegistryMutableLayer } from "./ProviderInstanceRegistryLive.ts";
59import {
60 type ProviderOrchestrationAdapterInfrastructure,
61 ProviderOrchestrationAdapterInfrastructureLive,
62} from "./ProviderOrchestrationAdapterInfrastructure.ts";
63import * as AcpRegistrySupport from "../acp/AcpRegistrySupport.ts";
64import { AcpRegistryCatalogLive } from "./AcpRegistryCatalog.ts";
65
66type ProviderInstanceRegistryHydrationEnv =
67 | Exclude<
68 BuiltInDriversEnv,
69 ProviderOrchestrationAdapterInfrastructure | AcpRegistrySupport.AcpRegistryCatalog
70 >
71 | Settings.ServerSettingsService;
72
73/**
74 * Synthesize a `ProviderInstanceConfigMap` from a `ServerSettings` snapshot.
75 *
76 * Strategy:
77 * 1. Copy all explicit `settings.providerInstances` entries verbatim.
78 * 2. For each built-in driver whose `defaultInstanceIdForDriver(id)` key
79 * is *not* already in the explicit map, synthesize an entry from the
80 * matching legacy `settings.providers.<kind>` blob.
81 *
82 * The returned map is the input the registry consumes; pure & exported
83 * separately so the hydration logic can be exercised by unit tests
84 * without layering.
85 */
86export const deriveProviderInstanceConfigMap = (
87 settings: ServerSettings,
88): ProviderInstanceConfigMap => {
89 const merged: Record<string, ProviderInstanceConfig> = { ...settings.providerInstances };
90
91 for (const driver of BUILT_IN_DRIVERS) {
92 const instanceId = defaultInstanceIdForDriver(driver.driverKind);
93 if (instanceId in merged) {
94 // Explicit `providerInstances` entry for this slot — user-authored
95 // config always wins over the legacy mirror.
96 continue;
97 }
98
99 // Only built-in drivers have a legacy mirror; the registry's
100 // `providers` struct is keyed on the same literal slug as
101 // `driverKind`. Access is dynamic (the driver kind is a branded string),
102 // but it's constrained to `keyof settings.providers` by the union of
103 // built-in driver kinds.
104 const legacyKey = driver.driverKind as keyof ServerSettings["providers"];
105 const legacyConfig = settings.providers[legacyKey];
106 if (legacyConfig === undefined) {
107 continue;
108 }
109
110 merged[instanceId] = {
111 driver: driver.driverKind,
112 config: legacyConfig,
113 };
114 }
115
116 return merged as ProviderInstanceConfigMap;
117};
118
119/**
120 * Layer that consumes `ProviderInstanceRegistryMutator` and forks a
121 * settings-watcher fiber. The fiber's lifetime is tied to the enclosing
122 * layer scope (process lifetime in production), so it is interrupted on
123 * shutdown without leaking.
124 *
125 * Errors inside the watcher are logged and swallowed — the registry's own
126 * "unavailable" bucket already absorbs unknown drivers and invalid
127 * configs, so the only way the watcher could fail is a settings stream
128 * tear-down, which logs and exits cleanly.
129 */
130const SettingsWatcherLive = Layer.effectDiscard(
131 Effect.gen(function* () {
132 const mutator = yield* ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator;
133 const serverSettings = yield* Settings.ServerSettingsService;
134 const settingsChanges = yield* serverSettings.subscribeChanges;
135 yield* settingsChanges.pipe(
136 Stream.runForEach((next) =>
137 mutator
138 .reconcile(deriveProviderInstanceConfigMap(next))
139 .pipe(
140 Effect.catchCause((cause) =>
141 Effect.logError("ProviderInstanceRegistry reconcile failed", cause),
142 ),
143 ),
144 ),
145 Effect.forkScoped,
146 );
147 }),
148);
149
150/**
151 * Hydrate `ProviderInstanceRegistry` from `ServerSettings` and keep it in
152 * sync with subsequent `streamChanges` emissions.
153 *
154 * The Layer's two halves:
155 * - `ProviderInstanceRegistryMutableLayer` produces the registry +
156 * mutator from the initial config map. Its scope owns every
157 * per-instance child scope created during reconcile.
158 * - `SettingsWatcherLive` consumes the mutator, acquires its settings
159 * subscription before forking, and runs a daemon fiber in the same scope.
160 *
161 * Composing via `Layer.provideMerge` makes the watcher's deps available
162 * from the mutable layer while still surfacing the registry as an output.
163 * The mutator tag is technically also exposed; only this module imports
164 * it, so the visibility leak is harmless in practice.
165 */
166export const ProviderInstanceRegistryHydrationLive: Layer.Layer<
167 ProviderInstanceRegistry.ProviderInstanceRegistry,
168 never,
169 ProviderInstanceRegistryHydrationEnv
170> = Layer.unwrap(
171 Effect.gen(function* () {
172 const serverSettings = yield* Settings.ServerSettingsService;
173 const initialSettings: ServerSettings | undefined = yield* serverSettings.getSettings.pipe(
174 Effect.orElseSucceed(() => undefined),
175 );
176 const initialConfigMap =
177 initialSettings === undefined
178 ? ({} as ProviderInstanceConfigMap)
179 : deriveProviderInstanceConfigMap(initialSettings);
180
181 const mutableLayer = ProviderInstanceRegistryMutableLayer({
182 drivers: BUILT_IN_DRIVERS,
183 configMap: initialConfigMap,
184 }).pipe(
185 Layer.provide(ProviderOrchestrationAdapterInfrastructureLive),
186 Layer.provide(AcpRegistryCatalogLive),
187 );
188
189 return SettingsWatcherLive.pipe(Layer.provideMerge(mutableLayer));
190 }),
191) as Layer.Layer<
192 ProviderInstanceRegistry.ProviderInstanceRegistry,
193 never,
194 ProviderInstanceRegistryHydrationEnv
195>;