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