Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProviderRegistry.ts

734 lines29.8 KB

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