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

ProviderRegistry.ts

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