Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProviderRegistry.ts

831 lines34.3 KB

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