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