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 `ProviderInstanceRegistry.layer`.
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/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 "./ProviderInstanceRegistry.ts";
57import * as ProviderInstanceRegistryMutator from "./ProviderInstanceRegistryMutator.ts";
58import * as ProviderOrchestrationAdapterInfrastructure from "./ProviderOrchestrationAdapterInfrastructure.ts";
59import * as AcpRegistrySupport from "./acp/AcpRegistrySupport.ts";
60import * as AcpRegistryCatalog from "./AcpRegistryCatalog.ts";
61
62type ProviderInstanceRegistryHydrationEnv =
63 | Exclude<
64 BuiltInDriversEnv,
65 | ProviderOrchestrationAdapterInfrastructure.ProviderOrchestrationAdapterInfrastructure
66 | AcpRegistrySupport.AcpRegistryCatalog
67 >
68 | Settings.ServerSettingsService;
69
70/**
71 * Synthesize a `ProviderInstanceConfigMap` from a `ServerSettings` snapshot.
72 *
73 * Strategy:
74 * 1. Copy all explicit `settings.providerInstances` entries verbatim.
75 * 2. For each built-in driver whose `defaultInstanceIdForDriver(id)` key
76 * is *not* already in the explicit map, synthesize an entry from the
77 * matching legacy `settings.providers.<kind>` blob.
78 *
79 * The returned map is the input the registry consumes; pure & exported
80 * separately so the hydration logic can be exercised by unit tests
81 * without layering.
82 */
83export const deriveProviderInstanceConfigMap = (
84 settings: ServerSettings,
85): ProviderInstanceConfigMap => {
86 const merged: Record<string, ProviderInstanceConfig> = { ...settings.providerInstances };
87
88 for (const driver of BUILT_IN_DRIVERS) {
89 const instanceId = defaultInstanceIdForDriver(driver.driverKind);
90 if (instanceId in merged) {
91 // Explicit `providerInstances` entry for this slot — user-authored
92 // config always wins over the legacy mirror.
93 continue;
94 }
95
96 // Only built-in drivers have a legacy mirror; the registry's
97 // `providers` struct is keyed on the same literal slug as
98 // `driverKind`. Access is dynamic (the driver kind is a branded string),
99 // but it's constrained to `keyof settings.providers` by the union of
100 // built-in driver kinds.
101 const legacyKey = driver.driverKind as keyof ServerSettings["providers"];
102 const legacyConfig = settings.providers[legacyKey];
103 if (legacyConfig === undefined) {
104 continue;
105 }
106
107 merged[instanceId] = {
108 driver: driver.driverKind,
109 config: legacyConfig,
110 };
111 }
112
113 return merged as ProviderInstanceConfigMap;
114};
115
116/**
117 * Layer that consumes `ProviderInstanceRegistryMutator` and forks a
118 * settings-watcher fiber. The fiber's lifetime is tied to the enclosing
119 * layer scope (process lifetime in production), so it is interrupted on
120 * shutdown without leaking.
121 *
122 * Errors inside the watcher are logged and swallowed — the registry's own
123 * "unavailable" bucket already absorbs unknown drivers and invalid
124 * configs, so the only way the watcher could fail is a settings stream
125 * tear-down, which logs and exits cleanly.
126 */
127const layerSettingsWatcher = Layer.effectDiscard(
128 Effect.gen(function* () {
129 const mutator = yield* ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator;
130 const serverSettings = yield* Settings.ServerSettingsService;
131 const settingsChanges = yield* serverSettings.subscribeChanges;
132 yield* settingsChanges.pipe(
133 Stream.runForEach((next) =>
134 mutator
135 .reconcile(deriveProviderInstanceConfigMap(next))
136 .pipe(
137 Effect.catchCause((cause) =>
138 Effect.logError("ProviderInstanceRegistry reconcile failed", cause),
139 ),
140 ),
141 ),
142 Effect.forkScoped,
143 );
144 }),
145);
146
147/**
148 * Hydrate `ProviderInstanceRegistry` from `ServerSettings` and keep it in
149 * sync with subsequent `streamChanges` emissions.
150 *
151 * The Layer's two halves:
152 * - `ProviderInstanceRegistry.layer` produces the registry +
153 * mutator from the initial config map. Its scope owns every
154 * per-instance child scope created during reconcile.
155 * - `SettingsWatcherLive` consumes the mutator, acquires its settings
156 * subscription before forking, and runs a daemon fiber in the same scope.
157 *
158 * Composing via `Layer.provideMerge` makes the watcher's deps available
159 * from the mutable layer while still surfacing the registry as an output.
160 * The mutator tag is technically also exposed; only this module imports
161 * it, so the visibility leak is harmless in practice.
162 */
163export const layer: Layer.Layer<
164 ProviderInstanceRegistry.ProviderInstanceRegistry,
165 never,
166 ProviderInstanceRegistryHydrationEnv
167> = Layer.unwrap(
168 Effect.gen(function* () {
169 const serverSettings = yield* Settings.ServerSettingsService;
170 const initialSettings: ServerSettings | undefined = yield* serverSettings.getSettings.pipe(
171 Effect.orElseSucceed(() => undefined),
172 );
173 const initialConfigMap =
174 initialSettings === undefined
175 ? ({} as ProviderInstanceConfigMap)
176 : deriveProviderInstanceConfigMap(initialSettings);
177
178 const layerMutable = ProviderInstanceRegistry.layer({
179 drivers: BUILT_IN_DRIVERS,
180 configMap: initialConfigMap,
181 }).pipe(
182 Layer.provide(ProviderOrchestrationAdapterInfrastructure.layer),
183 Layer.provide(AcpRegistryCatalog.layer),
184 );
185
186 return layerSettingsWatcher.pipe(Layer.provideMerge(layerMutable));
187 }),
188) as Layer.Layer<
189 ProviderInstanceRegistry.ProviderInstanceRegistry,
190 never,
191 ProviderInstanceRegistryHydrationEnv
192>;