Open History to see the last commit
1/**
2 * ProviderRegistryLive — aggregates per-instance snapshot streams into a
3 * single materialized list.
4 *
5 * Historically this Layer composed four per-kind Live Layers
6 * (`CodexProviderLive`, `ClaudeProviderLive`, …) that each exposed a
7 * `ServerProviderShape`. Those Lives were deleted during the driver /
8 * instance refactor — every driver now carries its `snapshot: ServerProviderShape`
9 * bundled onto the `ProviderInstance` the registry produces.
10 *
11 * Each configured instance (including multi-instance setups like
12 * `codex_personal` + `codex_work`) contributes one `ProviderSnapshotSource`,
13 * keyed by `instanceId`. Instances whose driver is unavailable or whose
14 * config failed to decode are merged from `instanceRegistry.listUnavailable`
15 * as shadow snapshots so the UI can render their exact unavailable reason.
16 *
17 * Cache paths on disk are now keyed by `instanceId`. Because
18 * `defaultInstanceIdForDriver(kind) === kind` for built-in kinds, existing
19 * `<kind>.json` files remain the on-disk location for that driver's default
20 * instance. Identity-less legacy cache contents are ignored and replaced by
21 * the first live refresh.
22 *
23 * @module ProviderRegistryLive
24 */
25import {
26 defaultInstanceIdForDriver,
27 ProviderDriverKind,
28 type ProviderInstanceId,
29 type ServerProvider,
30 type ServerProviderUpdateState,
31} from "@t3tools/contracts";
32import * as Cause from "effect/Cause";
33import * as Effect from "effect/Effect";
34import * as Equal from "effect/Equal";
35import * as FileSystem from "effect/FileSystem";
36import * as Layer from "effect/Layer";
37import * as Path from "effect/Path";
38import * as PubSub from "effect/PubSub";
39import * as Ref from "effect/Ref";
40import * as Stream from "effect/Stream";
41import * as Semaphore from "effect/Semaphore";
42
43import { ServerConfig } from "../../config.ts";
44import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
45import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry.ts";
46import {
47 hydrateCachedProvider,
48 isCachedProviderCorrelated,
49 orderProviderSnapshots,
50 readProviderStatusCache,
51 resolveProviderStatusCachePath,
52 writeProviderStatusCache,
53} from "../providerStatusCache.ts";
54import type { ProviderInstance } from "../ProviderDriver.ts";
55import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
56import type { ProviderSnapshotSource } from "../builtInProviderCatalog.ts";
57
58const loadProviders = (
59 providerSources: ReadonlyArray<ProviderSnapshotSource>,
60): Effect.Effect<ReadonlyArray<ServerProvider>> =>
61 Effect.forEach(
62 providerSources,
63 (providerSource) =>
64 providerSource.getSnapshot.pipe(
65 Effect.flatMap((snapshot) => correlateSnapshotWithSource(providerSource, snapshot)),
66 ),
67 {
68 concurrency: "unbounded",
69 },
70 );
71
72const makeManualProviderMaintenanceCapabilities = (provider: ProviderDriverKind) =>
73 makeManualOnlyProviderMaintenanceCapabilities({
74 provider,
75 packageName: null,
76 });
77
78const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean =>
79 (model.capabilities?.optionDescriptors?.length ?? 0) > 0;
80
81const shouldRetainMissingProviderModels = (provider: ServerProvider): boolean => {
82 if (provider.driver !== ProviderDriverKind.make("opencode")) {
83 return true;
84 }
85
86 // OpenCode's initial snapshot is deliberately non-authoritative while its
87 // first probe is still running. A probe error from an installed CLI/server
88 // is likewise partial: it could not establish the current inventory.
89 // Conversely, disabled and missing-CLI snapshots are authoritative removals,
90 // as are successful ready/warning inventories (including an empty one after
91 // logout or plugin removal).
92 const isPendingInitialProbe =
93 provider.enabled && !provider.installed && provider.status === "warning";
94 const didInstalledProviderProbeFail = provider.installed && provider.status === "error";
95 return isPendingInitialProbe || didInstalledProviderProbeFail;
96};
97
98const mergeProviderModels = (
99 provider: ServerProvider,
100 previousModels: ReadonlyArray<ServerProvider["models"][number]>,
101 nextModels: ReadonlyArray<ServerProvider["models"][number]>,
102): ReadonlyArray<ServerProvider["models"][number]> => {
103 const shouldRetainMissingModels = shouldRetainMissingProviderModels(provider);
104
105 if (shouldRetainMissingModels && nextModels.length === 0 && previousModels.length > 0) {
106 return previousModels;
107 }
108
109 const previousBySlug = new Map(previousModels.map((model) => [model.slug, model] as const));
110 const mergedModels = nextModels.map((model) => {
111 const previousModel = previousBySlug.get(model.slug);
112 if (!previousModel || hasModelCapabilities(model) || !hasModelCapabilities(previousModel)) {
113 return model;
114 }
115 return {
116 ...model,
117 capabilities: previousModel.capabilities,
118 };
119 });
120 const nextSlugs = new Set(nextModels.map((model) => model.slug));
121 return shouldRetainMissingModels
122 ? [...mergedModels, ...previousModels.filter((model) => !nextSlugs.has(model.slug))]
123 : mergedModels;
124};
125
126export const mergeProviderSnapshot = (
127 previousProvider: ServerProvider | undefined,
128 nextProvider: ServerProvider,
129): ServerProvider =>
130 !previousProvider
131 ? nextProvider
132 : {
133 ...nextProvider,
134 models: mergeProviderModels(nextProvider, previousProvider.models, nextProvider.models),
135 };
136
137export const mergeProviderSnapshots = (
138 previousProviders: ReadonlyArray<ServerProvider>,
139 nextProviders: ReadonlyArray<ServerProvider>,
140): ReadonlyArray<ServerProvider> => {
141 const mergedProviders = new Map(
142 previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
143 );
144
145 for (const provider of nextProviders) {
146 mergedProviders.set(
147 snapshotInstanceKey(provider),
148 mergeProviderSnapshot(mergedProviders.get(snapshotInstanceKey(provider)), provider),
149 );
150 }
151
152 return orderProviderSnapshots([...mergedProviders.values()]);
153};
154
155export const selectProvidersByKind = (
156 providers: ReadonlyArray<ServerProvider>,
157 providerKinds: ReadonlySet<ProviderDriverKind>,
158): ReadonlyArray<ServerProvider> =>
159 providers.filter((provider) => providerKinds.has(provider.driver));
160
161export const haveProvidersChanged = (
162 previousProviders: ReadonlyArray<ServerProvider>,
163 nextProviders: ReadonlyArray<ServerProvider>,
164): boolean => !Equal.equals(previousProviders, nextProviders);
165
166const correlateSnapshotWithSource = (
167 source: ProviderSnapshotSource,
168 snapshot: ServerProvider,
169): Effect.Effect<ServerProvider> => {
170 if (snapshot.instanceId !== source.instanceId) {
171 return Effect.die(
172 new Error(
173 `Provider snapshot instance mismatch: source '${source.instanceId}' emitted '${snapshot.instanceId}'.`,
174 ),
175 );
176 }
177 if (snapshot.driver !== source.driverKind) {
178 return Effect.die(
179 new Error(
180 `Provider snapshot driver mismatch for instance '${source.instanceId}': source '${source.driverKind}' emitted '${snapshot.driver}'.`,
181 ),
182 );
183 }
184 return Effect.succeed(snapshot);
185};
186
187/**
188 * Key a snapshot for aggregation and persistence. Snapshot sources
189 * must be correlated by instance id before reaching this map; missing
190 * identities are defects, not runtime routing fallbacks.
191 */
192const snapshotInstanceKey = (provider: ServerProvider): ProviderInstanceId => {
193 return provider.instanceId;
194};
195
196// Project a live `ProviderInstance` into the aggregator's consumption
197// shape. Each call re-captures the instance's `snapshot` closures, so
198// after `ProviderInstanceRegistry` rebuilds an instance (e.g. because
199// its settings changed), a fresh source rides the new PubSub instead
200// of a closed one.
201const buildSnapshotSource = (instance: ProviderInstance): ProviderSnapshotSource => ({
202 instanceId: instance.instanceId,
203 driverKind: instance.driverKind,
204 getSnapshot: instance.snapshot.getSnapshot,
205 refresh: instance.snapshot.refresh,
206 streamChanges: instance.snapshot.streamChanges,
207});
208
209export const ProviderRegistryLive = Layer.effect(
210 ProviderRegistry,
211 Effect.gen(function* () {
212 const instanceRegistry = yield* ProviderInstanceRegistry;
213 const config = yield* ServerConfig;
214 const fileSystem = yield* FileSystem.FileSystem;
215 const path = yield* Path.Path;
216
217 // Aggregator PubSub — consumers (WS gateway, etc.) subscribe here for
218 // coalesced updates across every instance.
219 const changesPubSub = yield* Effect.acquireRelease(
220 PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
221 PubSub.shutdown,
222 );
223
224 // Boot-only: hydrate `providersRef` from the on-disk per-instance
225 // cache so the UI has something to render during the first refresh.
226 // Instances added post-boot skip this path; their first entry in
227 // `providersRef` comes from the reactive `syncLiveSources` pass
228 // below.
229 const bootInstances = yield* instanceRegistry.listInstances;
230 const bootSources = bootInstances.map(buildSnapshotSource);
231 const fallbackProviders = yield* loadProviders(bootSources);
232 const fallbackByInstance = new Map<ProviderInstanceId, ServerProvider>();
233 for (let index = 0; index < fallbackProviders.length; index++) {
234 const provider = fallbackProviders[index];
235 const source = bootSources[index];
236 if (provider === undefined || source === undefined) {
237 continue;
238 }
239 fallbackByInstance.set(source.instanceId, provider);
240 }
241
242 const cachedProviders = yield* Effect.forEach(
243 bootSources,
244 (source) =>
245 Effect.gen(function* () {
246 // One cache file per configured instance. For the default
247 // instance of a built-in kind the path equals `<kind>.json` —
248 // identical to the legacy filename. We still require the cache
249 // payload to carry matching instance id + driver kind; old
250 // identity-less payloads are discarded and the awaited refresh
251 // below repopulates the cache.
252 const filePath = yield* resolveProviderStatusCachePath({
253 cacheDir: config.providerStatusCacheDir,
254 instanceId: source.instanceId,
255 }).pipe(Effect.provideService(Path.Path, path));
256 const fallbackProvider = fallbackByInstance.get(source.instanceId);
257 if (fallbackProvider === undefined) {
258 return undefined;
259 }
260 return yield* readProviderStatusCache(filePath).pipe(
261 Effect.provideService(FileSystem.FileSystem, fileSystem),
262 Effect.flatMap((cachedProvider) => {
263 if (cachedProvider === undefined) {
264 return Effect.void.pipe(Effect.as(undefined as ServerProvider | undefined));
265 }
266 const correlation = {
267 cachedProvider,
268 fallbackProvider,
269 } as const;
270 if (!isCachedProviderCorrelated(correlation)) {
271 return Effect.logWarning("provider status cache identity mismatch, ignoring", {
272 path: filePath,
273 instanceId: source.instanceId,
274 cachedInstanceId: cachedProvider.instanceId ?? null,
275 driver: source.driverKind,
276 cachedDriver: cachedProvider.driver ?? null,
277 }).pipe(Effect.as(undefined as ServerProvider | undefined));
278 }
279 return Effect.succeed(hydrateCachedProvider(correlation));
280 }),
281 );
282 }),
283 { concurrency: "unbounded" },
284 ).pipe(
285 Effect.map((providers) =>
286 orderProviderSnapshots(
287 providers.filter((provider): provider is ServerProvider => provider !== undefined),
288 ),
289 ),
290 );
291 const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(cachedProviders);
292 const maintenanceActionStatesRef = yield* Ref.make<
293 ReadonlyMap<ProviderInstanceId, { readonly update?: ServerProviderUpdateState | undefined }>
294 >(new Map());
295
296 // Live-source registry — the dynamic counterpart to the boot-time
297 // `bootSources`. Keyed by `instanceId`; the stored `ProviderInstance`
298 // reference is used for identity equality so "no-op" reconciles
299 // (settings unchanged) skip re-subscribing + re-probing.
300 const liveSubsRef = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ProviderInstance>>(
301 new Map(),
302 );
303 // Serialize `syncLiveSources` so a rapid burst of reconciles doesn't
304 // interleave two passes clobbering each other's fiber bookkeeping.
305 const syncSemaphore = yield* Semaphore.make(1);
306
307 const getLiveSources: Effect.Effect<ReadonlyArray<ProviderSnapshotSource>> = Ref.get(
308 liveSubsRef,
309 ).pipe(Effect.map((map) => Array.from(map.values(), buildSnapshotSource)));
310
311 const persistProvider = (provider: ServerProvider) =>
312 Effect.gen(function* () {
313 // Persist every instance — the file name is the instance id, so
314 // multi-instance setups (e.g. `codex_personal`, `codex_work`) each
315 // get their own cache. We resolve the path fresh so snapshots
316 // produced by newly-added instances post-boot still land on disk
317 // without the aggregator holding a stale `cachePathByInstance`
318 // entry.
319 const key = snapshotInstanceKey(provider);
320 const filePath = yield* resolveProviderStatusCachePath({
321 cacheDir: config.providerStatusCacheDir,
322 instanceId: key,
323 }).pipe(Effect.provideService(Path.Path, path));
324 yield* writeProviderStatusCache({ filePath, provider }).pipe(
325 Effect.provideService(FileSystem.FileSystem, fileSystem),
326 Effect.provideService(Path.Path, path),
327 Effect.tapError(Effect.logError),
328 Effect.ignore,
329 );
330 });
331
332 const applyProviderUpdateState = Effect.fn("applyProviderUpdateState")(function* (
333 provider: ServerProvider,
334 ) {
335 const maintenanceActionStates = yield* Ref.get(maintenanceActionStatesRef);
336 const updateState = maintenanceActionStates.get(provider.instanceId)?.update;
337 if (!updateState) {
338 const { updateState: _updateState, ...providerWithoutUpdateState } = provider;
339 return providerWithoutUpdateState;
340 }
341 return {
342 ...provider,
343 updateState,
344 };
345 });
346
347 const upsertProviders = Effect.fn("upsertProviders")(function* (
348 nextProviders: ReadonlyArray<ServerProvider>,
349 options?: {
350 readonly publish?: boolean;
351 readonly persist?: boolean;
352 readonly replace?: boolean;
353 },
354 ) {
355 const nextProvidersWithUpdateState = yield* Effect.forEach(
356 nextProviders,
357 applyProviderUpdateState,
358 {
359 concurrency: "unbounded",
360 },
361 );
362 const [previousProviders, providers, providersToPersist] = yield* Ref.modify(
363 providersRef,
364 (previousProviders) => {
365 const mergedProviders = new Map(
366 previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
367 );
368 const updatedKeys = new Set<ProviderInstanceId>();
369
370 for (const provider of nextProvidersWithUpdateState) {
371 const key = snapshotInstanceKey(provider);
372 updatedKeys.add(key);
373 mergedProviders.set(
374 key,
375 options?.replace === true
376 ? provider
377 : mergeProviderSnapshot(mergedProviders.get(key), provider),
378 );
379 }
380
381 const providers = orderProviderSnapshots([...mergedProviders.values()]);
382 const providersToPersist = providers.filter((provider) =>
383 updatedKeys.has(snapshotInstanceKey(provider)),
384 );
385 return [[previousProviders, providers, providersToPersist] as const, providers];
386 },
387 );
388
389 if (haveProvidersChanged(previousProviders, providers)) {
390 if (options?.persist !== false) {
391 yield* Effect.forEach(providersToPersist, persistProvider, {
392 concurrency: "unbounded",
393 discard: true,
394 });
395 }
396 if (options?.publish !== false) {
397 yield* PubSub.publish(changesPubSub, providers);
398 }
399 }
400
401 return providers;
402 });
403
404 const syncProvider = Effect.fn("syncProvider")(function* (
405 provider: ServerProvider,
406 options?: {
407 readonly publish?: boolean;
408 },
409 ) {
410 return yield* upsertProviders([provider], options);
411 });
412
413 const setProviderMaintenanceActionState = Effect.fn("setProviderMaintenanceActionState")(
414 function* (input: {
415 readonly instanceId: ProviderInstanceId;
416 readonly action: "update";
417 readonly state: ServerProviderUpdateState | null;
418 }) {
419 yield* Ref.update(maintenanceActionStatesRef, (previous) => {
420 const previousActions = previous.get(input.instanceId);
421 const nextActions = { ...previousActions };
422 if (input.state === null || input.state.status === "idle") {
423 delete nextActions[input.action];
424 } else {
425 nextActions[input.action] = input.state;
426 }
427
428 const next = new Map(previous);
429 if (Object.keys(nextActions).length === 0) {
430 next.delete(input.instanceId);
431 } else {
432 next.set(input.instanceId, nextActions);
433 }
434 return next;
435 });
436
437 const existingProviders = yield* Ref.get(providersRef);
438 const matchingProvider = existingProviders.find(
439 (candidate) => candidate.instanceId === input.instanceId,
440 );
441 if (!matchingProvider) {
442 return existingProviders;
443 }
444
445 const nextProvider = yield* applyProviderUpdateState(matchingProvider);
446 return yield* upsertProviders([nextProvider], {
447 persist: false,
448 });
449 },
450 );
451
452 const refreshOneSource = Effect.fn("refreshOneSource")(function* (
453 providerSource: ProviderSnapshotSource,
454 ) {
455 return yield* providerSource.refresh.pipe(
456 Effect.flatMap((nextProvider) =>
457 correlateSnapshotWithSource(providerSource, nextProvider).pipe(
458 Effect.flatMap(syncProvider),
459 ),
460 ),
461 );
462 });
463
464 const refreshAll = Effect.fn("refreshAll")(function* () {
465 const sources = yield* getLiveSources;
466 return yield* Effect.forEach(sources, (source) => refreshOneSource(source), {
467 concurrency: "unbounded",
468 discard: true,
469 }).pipe(Effect.andThen(Ref.get(providersRef)));
470 });
471
472 const refresh = Effect.fn("refresh")(function* (provider?: ProviderDriverKind) {
473 if (provider === undefined) {
474 return yield* refreshAll();
475 }
476 // Kind-scoped refreshes target the default instance for that driver.
477 const defaultInstanceId = defaultInstanceIdForDriver(provider);
478 const sources = yield* getLiveSources;
479 const providerSource = sources.find(
480 (candidate) => candidate.instanceId === defaultInstanceId,
481 );
482 if (!providerSource) {
483 return yield* Ref.get(providersRef);
484 }
485 return yield* refreshOneSource(providerSource);
486 });
487
488 const refreshInstance = Effect.fn("refreshInstance")(function* (
489 instanceId: ProviderInstanceId,
490 ) {
491 const sources = yield* getLiveSources;
492 const providerSource = sources.find((candidate) => candidate.instanceId === instanceId);
493 if (!providerSource) {
494 return yield* Ref.get(providersRef);
495 }
496 return yield* refreshOneSource(providerSource);
497 });
498
499 const getProviderMaintenanceCapabilitiesForInstance = Effect.fn(
500 "getProviderMaintenanceCapabilitiesForInstance",
501 )(function* (instanceId: ProviderInstanceId, provider: ProviderDriverKind) {
502 const instance = Array.from((yield* Ref.get(liveSubsRef)).values()).find(
503 (candidate) => candidate.instanceId === instanceId,
504 );
505 return (
506 instance?.snapshot.maintenanceCapabilities ??
507 makeManualProviderMaintenanceCapabilities(provider)
508 );
509 });
510
511 /**
512 * Diff the aggregator's live-source set against the current
513 * `ProviderInstanceRegistry` and:
514 * - subscribe to each newly-added or rebuilt instance's
515 * `streamChanges` (so periodic + enrichment refreshes land in
516 * `providersRef`);
517 * - read each newly-added/rebuilt instance's current snapshot after
518 * subscribing, closing the race with its independently-running
519 * background startup probe;
520 * - prune `providersRef` of instances that no longer exist.
521 *
522 * Provider refreshes are owned by each managed provider and never run
523 * on this layer's construction path. Consumers see cached or pending
524 * snapshots immediately, then receive live probe results through the
525 * already-attached change stream.
526 *
527 * Per-instance subscription fibers are not tracked explicitly. When
528 * a rebuilt instance's old child scope closes, its PubSub shuts
529 * down and our `Stream.runForEach` fiber exits naturally.
530 */
531 const syncLiveSources = syncSemaphore.withPermits(1)(
532 Effect.gen(function* () {
533 const instances = yield* instanceRegistry.listInstances;
534 const unavailableProviders = yield* instanceRegistry.listUnavailable;
535 const nextByInstance = new Map<ProviderInstanceId, ProviderInstance>(
536 instances.map((instance) => [instance.instanceId, instance] as const),
537 );
538 const knownInstanceIds = new Set<ProviderInstanceId>(nextByInstance.keys());
539 for (const provider of unavailableProviders) {
540 knownInstanceIds.add(snapshotInstanceKey(provider));
541 }
542 const previousSubs = yield* Ref.get(liveSubsRef);
543
544 // Carry over subscriptions for instances whose identity is
545 // unchanged (reconcile treated them as no-op). Instances that
546 // disappeared, or were rebuilt with a different reference,
547 // fall through to the "newly-added" branch below.
548 const carriedOver = new Map<ProviderInstanceId, ProviderInstance>();
549 for (const [instanceId, previousInstance] of previousSubs) {
550 const nextInstance = nextByInstance.get(instanceId);
551 if (nextInstance !== undefined && nextInstance === previousInstance) {
552 carriedOver.set(instanceId, previousInstance);
553 }
554 }
555
556 // Collect new/rebuilt instances in `nextByInstance` insertion
557 // order (which preserves settings-author order).
558 const newlyAdded: Array<readonly [ProviderInstanceId, ProviderInstance]> = [];
559 for (const [instanceId, instance] of nextByInstance) {
560 if (carriedOver.has(instanceId)) {
561 continue;
562 }
563 newlyAdded.push([instanceId, instance] as const);
564 }
565
566 // Fork long-lived subscriptions to each new/rebuilt instance's
567 // change stream before reading its current snapshot. If the
568 // driver's own initial probe finishes during this sync, either
569 // the current read or the active subscriber observes the result.
570 for (const [, instance] of newlyAdded) {
571 const source = buildSnapshotSource(instance);
572 yield* Stream.runForEach(source.streamChanges, (provider) =>
573 correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)),
574 ).pipe(Effect.forkScoped);
575 }
576 yield* Effect.yieldNow;
577
578 // Snapshot current state without starting a probe. Managed providers
579 // launch their startup refresh independently, so this closes the
580 // subscription race without putting external work on the registry
581 // or HTTP server construction path.
582 yield* Effect.forEach(
583 newlyAdded,
584 ([, instance]) =>
585 Effect.gen(function* () {
586 const source = buildSnapshotSource(instance);
587 const provider = yield* source.getSnapshot;
588 yield* correlateSnapshotWithSource(source, provider).pipe(
589 Effect.flatMap(syncProvider),
590 );
591 }).pipe(Effect.ignoreCause({ log: true })),
592 { concurrency: "unbounded", discard: true },
593 );
594 yield* upsertProviders(unavailableProviders, {
595 persist: false,
596 replace: true,
597 });
598
599 const nextSubs = new Map(carriedOver);
600 for (const [instanceId, instance] of newlyAdded) {
601 nextSubs.set(instanceId, instance);
602 }
603 yield* Ref.set(liveSubsRef, nextSubs);
604
605 // Drop aggregator state for instances that have disappeared —
606 // otherwise the UI would keep rendering ghosts.
607 const [previousProviders, providers] = yield* Ref.modify(
608 providersRef,
609 (previousProviders) => {
610 const providers = orderProviderSnapshots(
611 previousProviders.filter((provider) =>
612 knownInstanceIds.has(snapshotInstanceKey(provider)),
613 ),
614 );
615 return [[previousProviders, providers] as const, providers];
616 },
617 );
618 if (haveProvidersChanged(previousProviders, providers)) {
619 yield* PubSub.publish(changesPubSub, providers);
620 }
621 yield* Ref.update(maintenanceActionStatesRef, (previous) => {
622 const next = new Map(previous);
623 for (const instanceId of previous.keys()) {
624 if (!knownInstanceIds.has(instanceId)) {
625 next.delete(instanceId);
626 }
627 }
628 return next;
629 });
630 }),
631 );
632 const syncLiveSourcesAndContinue = syncLiveSources.pipe(
633 Effect.catchCause((cause) => {
634 if (Cause.hasInterruptsOnly(cause)) {
635 return Effect.interrupt;
636 }
637 return Effect.logError(
638 "provider registry instance sync failed; keeping subscription alive",
639 {
640 cause: Cause.pretty(cause),
641 },
642 );
643 }),
644 );
645
646 // Seed `providersRef` with the boot-time fallback snapshots so
647 // consumers calling `getProviders` immediately after layer build see
648 // a populated list — even before the first `syncLiveSources` refresh
649 // resolves. Cached snapshots (already in `providersRef`) merge with
650 // these via `upsertProviders` so on-disk state wins where present
651 // and pending fallbacks fill the gaps.
652 yield* upsertProviders(fallbackProviders, { publish: false });
653 // Subscribe to registry mutations BEFORE running the initial sync.
654 // `subscribeChanges` acquires the dequeue synchronously in this
655 // fibre; the subscription is active the instant this `yield*`
656 // returns. Forking the consumer loop later cannot lose a publish
657 // because no publish can reach a not-yet-subscribed dequeue.
658 //
659 // (Contrast with the pre-fix code that did
660 // `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`.
661 // `Stream.fromPubSub` defers `PubSub.subscribe` to stream start,
662 // and `forkScoped` only schedules the fibre — so a reconcile that
663 // published between "fibre scheduled" and "fibre starts running"
664 // was dropped, which made any settings change that replaced an
665 // instance never propagate to the aggregator's `providersRef`.)
666 // Subscribe to registry mutations BEFORE running the initial sync.
667 // `subscribeChanges` acquires the `PubSub.Subscription` synchronously
668 // in this fibre; the subscription is registered with the PubSub the
669 // instant this `yield*` returns, so any subsequent publish is
670 // buffered in the subscription regardless of when the consumer
671 // fibre below actually starts running.
672 //
673 // (Contrast with the pre-fix code that did
674 // `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`.
675 // `instanceRegistry.streamChanges` is `Stream.fromPubSub(changes)`,
676 // which defers `PubSub.subscribe` to stream start. `forkScoped` only
677 // schedules the consumer fibre — so a reconcile that published
678 // between "fibre scheduled" and "fibre starts running + subscribes"
679 // was dropped, which made any settings change that replaced an
680 // instance never propagate to the aggregator's `providersRef`.)
681 const instanceChanges = yield* instanceRegistry.subscribeChanges;
682 // Initial sync attaches subscriptions and snapshots current state for
683 // every instance present at boot. Provider probes are already running in
684 // their managed background fibers and never block this layer.
685 yield* syncLiveSources;
686 // React to registry mutations — instance added / removed / rebuilt.
687 // `Stream.fromSubscription` builds a stream over the pre-acquired
688 // subscription rather than subscribing on stream start, which is
689 // what closes the race.
690 yield* Stream.runForEach(
691 Stream.fromSubscription(instanceChanges),
692 () => syncLiveSourcesAndContinue,
693 ).pipe(Effect.forkScoped);
694
695 const recoverRefreshFailure = Effect.fn("recoverRefreshFailure")(function* (
696 cause: Cause.Cause<unknown>,
697 ) {
698 if (Cause.hasInterruptsOnly(cause)) {
699 return yield* Effect.interrupt;
700 }
701 yield* Effect.logError("provider registry refresh failed; preserving cached providers", {
702 cause: Cause.pretty(cause),
703 });
704 return yield* Ref.get(providersRef);
705 });
706
707 return {
708 getProviders: Ref.get(providersRef),
709 refresh: (provider?: ProviderDriverKind) =>
710 refresh(provider).pipe(Effect.catchCause(recoverRefreshFailure)),
711 refreshInstance: (instanceId: ProviderInstanceId) =>
712 refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)),
713 getProviderMaintenanceCapabilitiesForInstance,
714 setProviderMaintenanceActionState,
715 get streamChanges() {
716 return Stream.fromPubSub(changesPubSub);
717 },
718 } satisfies ProviderRegistryShape;
719 }),
720);