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