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

ProviderRegistry.ts

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