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

ProviderRegistry.ts

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