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