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

ProviderRegistry.ts

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