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