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