Open History to see the last commit
1/**
2 * ProviderRegistry - Provider snapshot service.
3 *
4 * Owns provider install/auth/version/model snapshots and exposes the latest
5 * provider state to transport layers.
6 *
7 * The live layer aggregates per-instance snapshot streams into a
8 * single materialized list.
9 *
10 * Historically this Layer composed four per-kind Live Layers
11 * (`CodexProviderLive`, `ClaudeProviderLive`, …) that each exposed a
12 * `ServerProviderShape`. Those Lives were deleted during the driver /
13 * instance refactor — every driver now carries its `snapshot: ServerProviderShape`
14 * bundled onto the `ProviderInstance` the registry produces.
15 *
16 * Each configured instance (including multi-instance setups like
17 * `codex_personal` + `codex_work`) contributes one `ProviderSnapshotSource`,
18 * keyed by `instanceId`. Instances whose driver is unavailable or whose
19 * config failed to decode are merged from `instanceRegistry.listUnavailable`
20 * as shadow snapshots so the UI can render their exact unavailable reason.
21 *
22 * Cache paths on disk are now keyed by `instanceId`. Because
23 * `defaultInstanceIdForDriver(kind) === kind` for built-in kinds, existing
24 * `<kind>.json` files remain the on-disk location for that driver's default
25 * instance. Identity-less legacy cache contents are ignored and replaced by
26 * the first live refresh.
27 *
28 * @module ProviderRegistry
29 */
30import {
31 defaultInstanceIdForDriver,
32 isProviderWorkspaceSnapshotCurrent,
33 ProviderDriverKind,
34 type ProviderInstanceId,
35 type ServerProvider,
36 type ServerProviderUpdateState,
37} from "@t3tools/contracts";
38import * as Cause from "effect/Cause";
39import * as Context from "effect/Context";
40import * as DateTime from "effect/DateTime";
41import * as Deferred from "effect/Deferred";
42import * as Effect from "effect/Effect";
43import * as Equal from "effect/Equal";
44import * as FileSystem from "effect/FileSystem";
45import * as Layer from "effect/Layer";
46import * as Option from "effect/Option";
47import * as Path from "effect/Path";
48import * as PubSub from "effect/PubSub";
49import * as Ref from "effect/Ref";
50import * as Stream from "effect/Stream";
51import * as Semaphore from "effect/Semaphore";
52
53import * as ModelManifest from "./ModelManifest.ts";
54import { applyProviderCompatibility } from "./providerCompatibility.ts";
55import * as ServerConfig from "../config.ts";
56import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
57import {
58 hydrateCachedProvider,
59 isCachedProviderCorrelated,
60 orderProviderSnapshots,
61 readProviderStatusCache,
62 resolveProviderStatusCachePath,
63 writeProviderStatusCache,
64} from "./providerStatusCache.ts";
65import type { ProviderInstance, ProviderWorkspaceSnapshot } from "./ProviderDriver.ts";
66import {
67 makeManualOnlyProviderMaintenanceCapabilities,
68 type ProviderMaintenanceCapabilities,
69} from "./providerMaintenance.ts";
70import type { ProviderSnapshotSource } from "./builtInProviderCatalog.ts";
71
72export type ProviderMaintenanceActionKind = "update";
73
74export class ProviderRegistry extends Context.Service<
75 ProviderRegistry,
76 {
77 /**
78 * Read the latest provider snapshots for every configured instance.
79 * Multiple snapshots may share the same `provider` kind (multiple
80 * instances of the same driver) and disambiguate via `instanceId`.
81 */
82 readonly getProviders: Effect.Effect<ReadonlyArray<ServerProvider>>;
83
84 /**
85 * Refresh all providers, or the default instance of the specified
86 * kind when supplied.
87 *
88 * Retained for back-compat with legacy call sites (WS refresh RPC,
89 * orchestration metrics). New code should prefer `refreshInstance`.
90 *
91 * @deprecated prefer `refreshInstance` for new call sites.
92 */
93 readonly refresh: (
94 provider?: ProviderDriverKind,
95 ) => Effect.Effect<ReadonlyArray<ServerProvider>>;
96
97 /**
98 * Refresh the specific configured instance. Returns the updated snapshot
99 * list. When the instance id is unknown the call resolves with the
100 * currently cached list (no error) — matching the legacy `refresh` shim
101 * behaviour so transport layers don't have to special-case unknowns.
102 */
103 readonly refreshInstance: (
104 instanceId: ProviderInstanceId,
105 ) => Effect.Effect<ReadonlyArray<ServerProvider>>;
106
107 /**
108 * Fill the skills and slash commands snapshot for one cwd. A cwd that
109 * already has a snapshot is left alone unless `fresh` is set. A fresh scan
110 * also refreshes the instance's machine snapshot and drops other
111 * instances' snapshots for the cwd.
112 */
113 readonly refreshWorkspaceSnapshot: (input: {
114 readonly instanceId: ProviderInstanceId;
115 readonly cwd: string;
116 readonly fresh?: boolean;
117 }) => Effect.Effect<ReadonlyArray<ServerProvider>>;
118
119 /**
120 * Resolve the maintenance capabilities owned by one live provider instance.
121 * Falls back to manual-only capabilities when the instance is not live.
122 * `fresh` re-derives ownership from the executable instead of the cache.
123 */
124 readonly getProviderMaintenanceCapabilitiesForInstance: (
125 instanceId: ProviderInstanceId,
126 provider: ProviderDriverKind,
127 options?: { readonly fresh?: boolean },
128 ) => Effect.Effect<ProviderMaintenanceCapabilities>;
129
130 /**
131 * Apply volatile maintenance-action state to one configured instance.
132 * This state is never persisted to disk. Today only update actions are
133 * projected onto `ServerProvider.updateState`; install/auth actions can
134 * extend this action map without adding driver-scoped APIs.
135 */
136 readonly setProviderMaintenanceActionState: (input: {
137 readonly instanceId: ProviderInstanceId;
138 readonly action: ProviderMaintenanceActionKind;
139 readonly state: ServerProviderUpdateState | null;
140 }) => Effect.Effect<ReadonlyArray<ServerProvider>>;
141
142 /**
143 * Stream of provider snapshot updates — one emission per aggregated
144 * change. The array contains the full current state.
145 */
146 readonly streamChanges: Stream.Stream<ReadonlyArray<ServerProvider>>;
147 }
148>()("t3/provider/ProviderRegistry") {}
149
150const loadProviders = (
151 providerSources: ReadonlyArray<ProviderSnapshotSource>,
152): Effect.Effect<ReadonlyArray<ServerProvider>> =>
153 Effect.forEach(
154 providerSources,
155 (providerSource) =>
156 providerSource.getSnapshot.pipe(
157 Effect.flatMap((snapshot) => correlateSnapshotWithSource(providerSource, snapshot)),
158 ),
159 {
160 concurrency: "unbounded",
161 },
162 );
163
164const makeManualProviderMaintenanceCapabilities = (provider: ProviderDriverKind) =>
165 makeManualOnlyProviderMaintenanceCapabilities({
166 provider,
167 packageName: null,
168 });
169
170const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean =>
171 (model.capabilities?.optionDescriptors?.length ?? 0) > 0;
172
173const MAX_WORKSPACE_SNAPSHOTS_PER_PROVIDER = 16;
174
175function dropProviderWorkspaceSnapshot(provider: ServerProvider, cwd: string): ServerProvider {
176 return provider.workspaceSnapshots?.some((snapshot) => snapshot.cwd === cwd)
177 ? {
178 ...provider,
179 workspaceSnapshots: provider.workspaceSnapshots.filter((snapshot) => snapshot.cwd !== cwd),
180 }
181 : provider;
182}
183
184export function upsertProviderWorkspaceSnapshot(
185 provider: ServerProvider,
186 cwd: string,
187 scopedSnapshot: ProviderWorkspaceSnapshot,
188): ServerProvider {
189 const workspaceSnapshot = {
190 cwd,
191 checkedAt: scopedSnapshot.checkedAt,
192 slashCommands: scopedSnapshot.slashCommandsPending
193 ? (provider.workspaceSnapshots?.find((snapshot) => snapshot.cwd === cwd)?.slashCommands ??
194 scopedSnapshot.slashCommands)
195 : scopedSnapshot.slashCommands,
196 ...(scopedSnapshot.slashCommandsPending ? { slashCommandsPending: true } : {}),
197 skills: scopedSnapshot.skills,
198 } satisfies NonNullable<ServerProvider["workspaceSnapshots"]>[number];
199 return {
200 ...provider,
201 workspaceSnapshots: [
202 ...(provider.workspaceSnapshots ?? []).filter((snapshot) => snapshot.cwd !== cwd),
203 workspaceSnapshot,
204 ].slice(-MAX_WORKSPACE_SNAPSHOTS_PER_PROVIDER),
205 };
206}
207
208const shouldRetainMissingProviderModels = (provider: ServerProvider): boolean => {
209 if (provider.driver === ProviderDriverKind.make("acpRegistry")) {
210 // ACP Registry discovery probes return the agent's complete inventory, so
211 // a completed probe (ready and authenticated) replaces the model list —
212 // otherwise agents that rename or collapse models leave stale entries
213 // pinned forever through the snapshot cache. Readiness-only and failed
214 // probe snapshots only know the "default" placeholder and stay partial.
215 return !(
216 provider.installed &&
217 provider.status === "ready" &&
218 provider.auth.status === "authenticated"
219 );
220 }
221
222 const isAntigravity = provider.driver === ProviderDriverKind.make("antigravity");
223 const isCodex = provider.driver === ProviderDriverKind.make("codex");
224 if (!isAntigravity && !isCodex && provider.driver !== ProviderDriverKind.make("opencode")) {
225 return true;
226 }
227
228 if (
229 (isAntigravity || isCodex) &&
230 (!provider.enabled || provider.auth.status === "unauthenticated")
231 ) {
232 return false;
233 }
234
235 // Successful discovery replaces these inventories so cached retired models disappear.
236 // Antigravity's local health check does not authenticate or discover models.
237 const isPendingAntigravityAuthentication =
238 isAntigravity && provider.status === "warning" && provider.auth.status === "unknown";
239 const isPendingInitialProbe =
240 provider.enabled && !provider.installed && provider.status === "warning";
241 const didInstalledProviderProbeFail = provider.installed && provider.status === "error";
242 return (
243 isPendingAntigravityAuthentication || isPendingInitialProbe || didInstalledProviderProbeFail
244 );
245};
246
247const shouldRetainMissingOpenCodeMetadata = (provider: ServerProvider): boolean =>
248 provider.driver === ProviderDriverKind.make("opencode") &&
249 shouldRetainMissingProviderModels(provider);
250
251const mergeProviderModels = (
252 provider: ServerProvider,
253 previousModels: ReadonlyArray<ServerProvider["models"][number]>,
254 nextModels: ReadonlyArray<ServerProvider["models"][number]>,
255): ReadonlyArray<ServerProvider["models"][number]> => {
256 const shouldRetainMissingModels = shouldRetainMissingProviderModels(provider);
257 // Custom rows are derived from settings and every snapshot carries the full
258 // current list, so a custom model missing from `nextModels` was removed by
259 // the user and must not be resurrected from the previous snapshot.
260 const retainablePreviousModels = previousModels.filter((model) => !model.isCustom);
261
262 if (shouldRetainMissingModels && nextModels.length === 0 && retainablePreviousModels.length > 0) {
263 return retainablePreviousModels;
264 }
265
266 const previousBySlug = new Map(previousModels.map((model) => [model.slug, model] as const));
267 const mergedModels = nextModels.map((model) => {
268 const previousModel = previousBySlug.get(model.slug);
269 if (!previousModel || hasModelCapabilities(model) || !hasModelCapabilities(previousModel)) {
270 return model;
271 }
272 return {
273 ...model,
274 capabilities: previousModel.capabilities,
275 };
276 });
277 const nextSlugs = new Set(nextModels.map((model) => model.slug));
278 return shouldRetainMissingModels
279 ? [...mergedModels, ...retainablePreviousModels.filter((model) => !nextSlugs.has(model.slug))]
280 : mergedModels;
281};
282
283/**
284 * Antigravity's health check only initializes the agent, so after a server
285 * restart it reports the account as unchecked. The saved Google login still
286 * works, and the previous snapshot proves it. Carry that account state until
287 * a session, refresh, or sign-out reports something new. A confirmed missing
288 * installation, sign-out, disabled instance, or a changed sign-in method is
289 * never overridden.
290 */
291const carrySavedAntigravityAccount = (
292 previousProvider: ServerProvider,
293 nextProvider: ServerProvider,
294): Pick<ServerProvider, "auth" | "status"> | undefined => {
295 const antigravity = ProviderDriverKind.make("antigravity");
296 if (
297 nextProvider.driver !== antigravity ||
298 previousProvider.driver !== antigravity ||
299 !nextProvider.enabled ||
300 nextProvider.auth.status !== "unknown" ||
301 previousProvider.auth.status !== "authenticated" ||
302 (nextProvider.auth.type !== undefined &&
303 nextProvider.auth.type !== previousProvider.auth.type) ||
304 (!nextProvider.installed && nextProvider.status !== "warning")
305 ) {
306 return undefined;
307 }
308 // The pending boot probe (`installed: false`, warning) and a failed probe
309 // keep their own status; only a passed health check reads as ready.
310 const status =
311 nextProvider.installed && nextProvider.status === "warning" ? "ready" : nextProvider.status;
312 return { auth: previousProvider.auth, status };
313};
314
315export const mergeProviderSnapshot = (
316 previousProvider: ServerProvider | undefined,
317 nextProvider: ServerProvider,
318): ServerProvider => {
319 if (!previousProvider) {
320 return nextProvider;
321 }
322 const savedAccount = carrySavedAntigravityAccount(previousProvider, nextProvider);
323 // "Google account access is not checked yet" describes the probe, not the
324 // account; it must not outlive the state it explained.
325 const { message: _uncheckedMessage, ...nextWithoutMessage } = nextProvider;
326 return {
327 ...(savedAccount?.status === "ready" ? nextWithoutMessage : nextProvider),
328 ...savedAccount,
329 models: mergeProviderModels(nextProvider, previousProvider.models, nextProvider.models),
330 ...(nextProvider.workspaceSnapshots !== undefined
331 ? { workspaceSnapshots: nextProvider.workspaceSnapshots }
332 : previousProvider.workspaceSnapshots !== undefined
333 ? { workspaceSnapshots: previousProvider.workspaceSnapshots }
334 : {}),
335 ...(shouldRetainMissingOpenCodeMetadata(nextProvider)
336 ? {
337 slashCommands:
338 nextProvider.slashCommands.length === 0
339 ? previousProvider.slashCommands
340 : nextProvider.slashCommands,
341 skills: nextProvider.skills.length === 0 ? previousProvider.skills : nextProvider.skills,
342 }
343 : {}),
344 };
345};
346
347export const mergeProviderSnapshots = (
348 previousProviders: ReadonlyArray<ServerProvider>,
349 nextProviders: ReadonlyArray<ServerProvider>,
350): ReadonlyArray<ServerProvider> => {
351 const mergedProviders = new Map(
352 previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
353 );
354
355 for (const provider of nextProviders) {
356 mergedProviders.set(
357 snapshotInstanceKey(provider),
358 mergeProviderSnapshot(mergedProviders.get(snapshotInstanceKey(provider)), provider),
359 );
360 }
361
362 return orderProviderSnapshots([...mergedProviders.values()]);
363};
364
365export const selectProvidersByKind = (
366 providers: ReadonlyArray<ServerProvider>,
367 providerKinds: ReadonlySet<ProviderDriverKind>,
368): ReadonlyArray<ServerProvider> =>
369 providers.filter((provider) => providerKinds.has(provider.driver));
370
371const haveProvidersChanged = (
372 previousProviders: ReadonlyArray<ServerProvider>,
373 nextProviders: ReadonlyArray<ServerProvider>,
374): boolean => !Equal.equals(previousProviders, nextProviders);
375
376const correlateSnapshotWithSource = (
377 source: ProviderSnapshotSource,
378 snapshot: ServerProvider,
379): Effect.Effect<ServerProvider> => {
380 if (snapshot.instanceId !== source.instanceId) {
381 return Effect.die(
382 new Error(
383 `Provider snapshot instance mismatch: source '${source.instanceId}' emitted '${snapshot.instanceId}'.`,
384 ),
385 );
386 }
387 if (snapshot.driver !== source.driverKind) {
388 return Effect.die(
389 new Error(
390 `Provider snapshot driver mismatch for instance '${source.instanceId}': source '${source.driverKind}' emitted '${snapshot.driver}'.`,
391 ),
392 );
393 }
394 return Effect.succeed(snapshot);
395};
396
397/**
398 * Key a snapshot for aggregation and persistence. Snapshot sources
399 * must be correlated by instance id before reaching this map; missing
400 * identities are defects, not runtime routing fallbacks.
401 */
402const snapshotInstanceKey = (provider: ServerProvider): ProviderInstanceId => {
403 return provider.instanceId;
404};
405
406// Project a live `ProviderInstance` into the aggregator's consumption
407// shape. Each call re-captures the instance's `snapshot` closures, so
408// after `ProviderInstanceRegistry` rebuilds an instance (e.g. because
409// its settings changed), a fresh source rides the new PubSub instead
410// of a closed one.
411const buildSnapshotSource = (instance: ProviderInstance): ProviderSnapshotSource => ({
412 instanceId: instance.instanceId,
413 driverKind: instance.driverKind,
414 getSnapshot: instance.snapshot.getSnapshot,
415 refresh: instance.snapshot.refresh,
416 streamChanges: instance.snapshot.streamChanges,
417});
418
419export const layer = Layer.effect(
420 ProviderRegistry,
421 Effect.gen(function* () {
422 const instanceRegistry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
423 const manifestService = yield* ModelManifest.ModelManifest;
424 const serviceScope = yield* Effect.scope;
425 const config = yield* ServerConfig.ServerConfig;
426 const fileSystem = yield* FileSystem.FileSystem;
427 const path = yield* Path.Path;
428
429 // Aggregator PubSub — consumers (WS gateway, etc.) subscribe here for
430 // coalesced updates across every instance.
431 const changesPubSub = yield* Effect.acquireRelease(
432 PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
433 PubSub.shutdown,
434 );
435
436 // Boot-only: hydrate `providersRef` from the on-disk per-instance
437 // cache so the UI has something to render during the first refresh.
438 // Instances added post-boot skip this path; their first entry in
439 // `providersRef` comes from the reactive `syncLiveSources` pass
440 // below.
441 const bootInstances = yield* instanceRegistry.listInstances;
442 const bootSources = bootInstances.map(buildSnapshotSource);
443 const fallbackProviders = yield* loadProviders(bootSources);
444 const fallbackByInstance = new Map<ProviderInstanceId, ServerProvider>();
445 for (let index = 0; index < fallbackProviders.length; index++) {
446 const provider = fallbackProviders[index];
447 const source = bootSources[index];
448 if (provider === undefined || source === undefined) {
449 continue;
450 }
451 fallbackByInstance.set(source.instanceId, provider);
452 }
453
454 const cachedProviders = yield* Effect.forEach(
455 bootSources,
456 (source) =>
457 Effect.gen(function* () {
458 // One cache file per configured instance. For the default
459 // instance of a built-in kind the path equals `<kind>.json` —
460 // identical to the legacy filename. We still require the cache
461 // payload to carry matching instance id + driver kind; old
462 // identity-less payloads are discarded and the awaited refresh
463 // below repopulates the cache.
464 const filePath = yield* resolveProviderStatusCachePath({
465 cacheDir: config.providerStatusCacheDir,
466 instanceId: source.instanceId,
467 }).pipe(Effect.provideService(Path.Path, path));
468 const fallbackProvider = fallbackByInstance.get(source.instanceId);
469 if (fallbackProvider === undefined) {
470 return undefined;
471 }
472 return yield* readProviderStatusCache(filePath).pipe(
473 Effect.provideService(FileSystem.FileSystem, fileSystem),
474 Effect.flatMap((cachedProvider) => {
475 if (cachedProvider === undefined) {
476 return Effect.void.pipe(Effect.as(undefined as ServerProvider | undefined));
477 }
478 const correlation = {
479 cachedProvider,
480 fallbackProvider,
481 } as const;
482 if (!isCachedProviderCorrelated(correlation)) {
483 return Effect.logWarning("provider status cache identity mismatch, ignoring", {
484 path: filePath,
485 instanceId: source.instanceId,
486 cachedInstanceId: cachedProvider.instanceId ?? null,
487 driver: source.driverKind,
488 cachedDriver: cachedProvider.driver ?? null,
489 }).pipe(Effect.as(undefined as ServerProvider | undefined));
490 }
491 return Effect.succeed(hydrateCachedProvider(correlation));
492 }),
493 );
494 }),
495 { concurrency: "unbounded" },
496 ).pipe(
497 Effect.map((providers) =>
498 orderProviderSnapshots(
499 providers.filter((provider): provider is ServerProvider => provider !== undefined),
500 ),
501 ),
502 );
503 const initialManifest = yield* manifestService.current;
504 const classifyCompatibility = (
505 provider: ServerProvider,
506 manifest: ModelManifest.ModelManifestData,
507 ) =>
508 applyProviderCompatibility(
509 provider,
510 manifest.compatibility,
511 ModelManifest.BUNDLED_MODEL_MANIFEST.compatibility,
512 );
513 const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(
514 cachedProviders.map((provider) => classifyCompatibility(provider, initialManifest)),
515 );
516 const workspaceRefreshesRef = yield* Ref.make<
517 ReadonlyMap<ProviderInstance, ReadonlySet<string>>
518 >(new Map());
519 const maintenanceActionStatesRef = yield* Ref.make<
520 ReadonlyMap<ProviderInstanceId, { readonly update?: ServerProviderUpdateState | undefined }>
521 >(new Map());
522
523 // Live-source registry — the dynamic counterpart to the boot-time
524 // `bootSources`. Keyed by `instanceId`; the stored `ProviderInstance`
525 // reference is used for identity equality so "no-op" reconciles
526 // (settings unchanged) skip re-subscribing + re-probing.
527 const liveSubsRef = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ProviderInstance>>(
528 new Map(),
529 );
530 // Serialize `syncLiveSources` so a rapid burst of reconciles doesn't
531 // interleave two passes clobbering each other's fiber bookkeeping.
532 const syncSemaphore = yield* Semaphore.make(1);
533
534 const getLiveSources: Effect.Effect<ReadonlyArray<ProviderSnapshotSource>> = Ref.get(
535 liveSubsRef,
536 ).pipe(Effect.map((map) => Array.from(map.values(), buildSnapshotSource)));
537
538 const persistProvider = (provider: ServerProvider) =>
539 Effect.gen(function* () {
540 // Persist every instance — the file name is the instance id, so
541 // multi-instance setups (e.g. `codex_personal`, `codex_work`) each
542 // get their own cache. We resolve the path fresh so snapshots
543 // produced by newly-added instances post-boot still land on disk
544 // without the aggregator holding a stale `cachePathByInstance`
545 // entry.
546 const key = snapshotInstanceKey(provider);
547 const filePath = yield* resolveProviderStatusCachePath({
548 cacheDir: config.providerStatusCacheDir,
549 instanceId: key,
550 }).pipe(Effect.provideService(Path.Path, path));
551 const { workspaceSnapshots: _workspaceSnapshots, ...machineProvider } = provider;
552 yield* writeProviderStatusCache({ filePath, provider: machineProvider }).pipe(
553 Effect.provideService(FileSystem.FileSystem, fileSystem),
554 Effect.provideService(Path.Path, path),
555 Effect.tapError(Effect.logError),
556 Effect.ignore,
557 );
558 });
559
560 const applyProviderUpdateState = Effect.fn("applyProviderUpdateState")(function* (
561 provider: ServerProvider,
562 ) {
563 const maintenanceActionStates = yield* Ref.get(maintenanceActionStatesRef);
564 const updateState = maintenanceActionStates.get(provider.instanceId)?.update;
565 if (!updateState) {
566 const { updateState: _updateState, ...providerWithoutUpdateState } = provider;
567 return providerWithoutUpdateState;
568 }
569 return {
570 ...provider,
571 updateState,
572 };
573 });
574
575 const upsertProviders = Effect.fn("upsertProviders")(function* (
576 nextProviders: ReadonlyArray<ServerProvider>,
577 options?: {
578 readonly publish?: boolean;
579 readonly persist?: boolean;
580 readonly replace?: boolean;
581 },
582 ) {
583 const manifest = yield* manifestService.current;
584 const nextProvidersWithUpdateState = yield* Effect.forEach(
585 nextProviders,
586 applyProviderUpdateState,
587 {
588 concurrency: "unbounded",
589 },
590 );
591 const [previousProviders, providers, providersToPersist] = yield* Ref.modify(
592 providersRef,
593 (previousProviders) => {
594 const mergedProviders = new Map(
595 previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
596 );
597 const updatedKeys = new Set<ProviderInstanceId>();
598
599 for (const provider of nextProvidersWithUpdateState) {
600 const key = snapshotInstanceKey(provider);
601 updatedKeys.add(key);
602 mergedProviders.set(
603 key,
604 options?.replace === true
605 ? provider
606 : mergeProviderSnapshot(mergedProviders.get(key), provider),
607 );
608 }
609
610 const providers = orderProviderSnapshots(
611 [...mergedProviders.values()].map((provider) =>
612 classifyCompatibility(provider, manifest),
613 ),
614 );
615 const providersToPersist = providers.filter((provider) =>
616 updatedKeys.has(snapshotInstanceKey(provider)),
617 );
618 return [[previousProviders, providers, providersToPersist] as const, providers];
619 },
620 );
621
622 if (haveProvidersChanged(previousProviders, providers)) {
623 if (options?.persist !== false) {
624 yield* Effect.forEach(providersToPersist, persistProvider, {
625 concurrency: "unbounded",
626 discard: true,
627 });
628 }
629 if (options?.publish !== false) {
630 yield* PubSub.publish(changesPubSub, providers);
631 }
632 }
633
634 return providers;
635 });
636
637 const compatibilityRefreshRunning = yield* Ref.make(false);
638 const syncProvider = Effect.fn("syncProvider")(function* (
639 provider: ServerProvider,
640 options?: {
641 readonly publish?: boolean;
642 },
643 ) {
644 const providers = yield* upsertProviders([provider], options);
645 // Reclassify the current read model after fetching. Never republish the
646 // probe captured before the fetch: a newer health result may have landed.
647 if (!(yield* Ref.getAndSet(compatibilityRefreshRunning, true))) {
648 yield* manifestService.refresh.pipe(
649 Effect.andThen(upsertProviders([], { persist: false })),
650 Effect.ensuring(Ref.set(compatibilityRefreshRunning, false)),
651 Effect.forkIn(serviceScope),
652 );
653 }
654 return providers;
655 });
656
657 const setProviderMaintenanceActionState = Effect.fn("setProviderMaintenanceActionState")(
658 function* (input: {
659 readonly instanceId: ProviderInstanceId;
660 readonly action: "update";
661 readonly state: ServerProviderUpdateState | null;
662 }) {
663 yield* Ref.update(maintenanceActionStatesRef, (previous) => {
664 const previousActions = previous.get(input.instanceId);
665 const nextActions = { ...previousActions };
666 if (input.state === null || input.state.status === "idle") {
667 delete nextActions[input.action];
668 } else {
669 nextActions[input.action] = input.state;
670 }
671
672 const next = new Map(previous);
673 if (Object.keys(nextActions).length === 0) {
674 next.delete(input.instanceId);
675 } else {
676 next.set(input.instanceId, nextActions);
677 }
678 return next;
679 });
680
681 const existingProviders = yield* Ref.get(providersRef);
682 const matchingProvider = existingProviders.find(
683 (candidate) => candidate.instanceId === input.instanceId,
684 );
685 if (!matchingProvider) {
686 return existingProviders;
687 }
688
689 const nextProvider = yield* applyProviderUpdateState(matchingProvider);
690 return yield* upsertProviders([nextProvider], {
691 persist: false,
692 });
693 },
694 );
695
696 const refreshOneSource = Effect.fn("refreshOneSource")(function* (
697 providerSource: ProviderSnapshotSource,
698 ) {
699 return yield* providerSource.refresh.pipe(
700 Effect.flatMap((nextProvider) =>
701 correlateSnapshotWithSource(providerSource, nextProvider).pipe(
702 Effect.flatMap(syncProvider),
703 ),
704 ),
705 );
706 });
707
708 type RefreshAllCompletion = Deferred.Deferred<ReadonlyArray<ServerProvider>>;
709 const refreshAllInFlightRef = yield* Ref.make<Option.Option<RefreshAllCompletion>>(
710 Option.none(),
711 );
712
713 // Untargeted refreshes probe every live source, so any read-scoped client
714 // can request them. Concurrent callers share one in-flight pass instead of
715 // each starting their own set of provider processes.
716 const refreshAll = Effect.fn("refreshAll")(function* () {
717 const claimed = yield* Ref.modify(
718 refreshAllInFlightRef,
719 (
720 inFlight,
721 ): readonly [
722 { readonly owner: boolean; readonly completion: RefreshAllCompletion },
723 Option.Option<RefreshAllCompletion>,
724 ] => {
725 if (Option.isSome(inFlight)) {
726 return [{ owner: false, completion: inFlight.value }, inFlight];
727 }
728 const completion = Deferred.makeUnsafe<ReadonlyArray<ServerProvider>>();
729 return [{ owner: true, completion }, Option.some(completion)];
730 },
731 );
732 if (claimed.owner) {
733 // Detached so an interrupted first caller cannot cancel the pass that
734 // other callers are already awaiting.
735 yield* getLiveSources.pipe(
736 Effect.flatMap((sources) =>
737 Effect.forEach(sources, (source) => refreshOneSource(source), {
738 concurrency: "unbounded",
739 discard: true,
740 }),
741 ),
742 Effect.andThen(Ref.get(providersRef)),
743 Effect.onExit((exit) =>
744 Ref.set(refreshAllInFlightRef, Option.none()).pipe(
745 Effect.andThen(Deferred.done(claimed.completion, exit)),
746 ),
747 ),
748 Effect.forkDetach,
749 );
750 }
751 return yield* Deferred.await(claimed.completion);
752 });
753
754 const refresh = Effect.fn("refresh")(function* (provider?: ProviderDriverKind) {
755 if (provider === undefined) {
756 return yield* refreshAll();
757 }
758 // Kind-scoped refreshes target the default instance for that driver.
759 const defaultInstanceId = defaultInstanceIdForDriver(provider);
760 const sources = yield* getLiveSources;
761 const providerSource = sources.find(
762 (candidate) => candidate.instanceId === defaultInstanceId,
763 );
764 if (!providerSource) {
765 return yield* Ref.get(providersRef);
766 }
767 return yield* refreshOneSource(providerSource);
768 });
769
770 const refreshInstance = Effect.fn("refreshInstance")(function* (
771 instanceId: ProviderInstanceId,
772 ) {
773 const sources = yield* getLiveSources;
774 const providerSource = sources.find((candidate) => candidate.instanceId === instanceId);
775 if (!providerSource) {
776 return yield* Ref.get(providersRef);
777 }
778 return yield* refreshOneSource(providerSource);
779 });
780
781 const getProviderMaintenanceCapabilitiesForInstance = Effect.fn(
782 "getProviderMaintenanceCapabilitiesForInstance",
783 )(function* (
784 instanceId: ProviderInstanceId,
785 provider: ProviderDriverKind,
786 options?: { readonly fresh?: boolean },
787 ) {
788 // Read the instance registry, not `liveSubsRef`: the latter trails
789 // reconciliation, and an update must never run a retired instance's
790 // command against a freshly configured executable.
791 const instance = yield* instanceRegistry.getInstance(instanceId);
792 if (!instance || instance.driverKind !== provider) {
793 return makeManualProviderMaintenanceCapabilities(provider);
794 }
795 return yield* instance.snapshot.resolveMaintenance(options);
796 });
797
798 /**
799 * Diff the aggregator's live-source set against the current
800 * `ProviderInstanceRegistry` and:
801 * - subscribe to each newly-added or rebuilt instance's
802 * `streamChanges` (so periodic + enrichment refreshes land in
803 * `providersRef`);
804 * - read each newly-added/rebuilt instance's current snapshot after
805 * subscribing, closing the race with its independently-running
806 * background startup probe;
807 * - prune `providersRef` of instances that no longer exist.
808 *
809 * Provider refreshes are owned by each managed provider and never run
810 * on this layer's construction path. Consumers see cached or pending
811 * snapshots immediately, then receive live probe results through the
812 * already-attached change stream.
813 *
814 * Per-instance subscription fibers are not tracked explicitly. When
815 * a rebuilt instance's old child scope closes, its PubSub shuts
816 * down and our `Stream.runForEach` fiber exits naturally.
817 */
818 const syncLiveSources = syncSemaphore.withPermits(1)(
819 Effect.gen(function* () {
820 const instances = yield* instanceRegistry.listInstances;
821 const unavailableProviders = yield* instanceRegistry.listUnavailable;
822 const nextByInstance = new Map<ProviderInstanceId, ProviderInstance>(
823 instances.map((instance) => [instance.instanceId, instance] as const),
824 );
825 const knownInstanceIds = new Set<ProviderInstanceId>(nextByInstance.keys());
826 for (const provider of unavailableProviders) {
827 knownInstanceIds.add(snapshotInstanceKey(provider));
828 }
829 const previousSubs = yield* Ref.get(liveSubsRef);
830
831 // Carry over subscriptions for instances whose identity is
832 // unchanged (reconcile treated them as no-op). Instances that
833 // disappeared, or were rebuilt with a different reference,
834 // fall through to the "newly-added" branch below.
835 const carriedOver = new Map<ProviderInstanceId, ProviderInstance>();
836 for (const [instanceId, previousInstance] of previousSubs) {
837 const nextInstance = nextByInstance.get(instanceId);
838 if (nextInstance !== undefined && nextInstance === previousInstance) {
839 carriedOver.set(instanceId, previousInstance);
840 }
841 }
842
843 // Collect new/rebuilt instances in `nextByInstance` insertion
844 // order (which preserves settings-author order).
845 const newlyAdded: Array<readonly [ProviderInstanceId, ProviderInstance]> = [];
846 for (const [instanceId, instance] of nextByInstance) {
847 if (carriedOver.has(instanceId)) {
848 continue;
849 }
850 newlyAdded.push([instanceId, instance] as const);
851 }
852
853 const rebuiltInstanceIds = new Set(
854 newlyAdded
855 .map(([instanceId]) => instanceId)
856 .filter((instanceId) => previousSubs.has(instanceId)),
857 );
858 if (rebuiltInstanceIds.size > 0) {
859 const [previousProviders, providers] = yield* Ref.modify(
860 providersRef,
861 (previousProviders) => {
862 const providers = previousProviders.map((provider) => {
863 if (!rebuiltInstanceIds.has(provider.instanceId)) return provider;
864 const { workspaceSnapshots: _workspaceSnapshots, ...machineSnapshot } = provider;
865 return machineSnapshot;
866 });
867 return [[previousProviders, providers] as const, providers];
868 },
869 );
870 if (haveProvidersChanged(previousProviders, providers)) {
871 yield* PubSub.publish(changesPubSub, providers);
872 }
873 }
874
875 // Fork long-lived subscriptions to each new/rebuilt instance's
876 // change stream before reading its current snapshot. If the
877 // driver's own initial probe finishes during this sync, either
878 // the current read or the active subscriber observes the result.
879 for (const [, instance] of newlyAdded) {
880 const source = buildSnapshotSource(instance);
881 yield* Stream.runForEach(source.streamChanges, (provider) =>
882 correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)),
883 ).pipe(Effect.forkScoped);
884 }
885 yield* Effect.yieldNow;
886
887 // Snapshot current state without starting a probe. Managed providers
888 // launch their startup refresh independently, so this closes the
889 // subscription race without putting external work on the registry
890 // or HTTP server construction path.
891 yield* Effect.forEach(
892 newlyAdded,
893 ([, instance]) =>
894 Effect.gen(function* () {
895 const source = buildSnapshotSource(instance);
896 const provider = yield* source.getSnapshot;
897 yield* correlateSnapshotWithSource(source, provider).pipe(
898 Effect.flatMap(syncProvider),
899 );
900 }).pipe(Effect.ignoreCause({ log: true })),
901 { concurrency: "unbounded", discard: true },
902 );
903 yield* upsertProviders(unavailableProviders, {
904 persist: false,
905 replace: true,
906 });
907
908 const nextSubs = new Map(carriedOver);
909 for (const [instanceId, instance] of newlyAdded) {
910 nextSubs.set(instanceId, instance);
911 }
912 yield* Ref.set(liveSubsRef, nextSubs);
913
914 // Drop aggregator state for instances that have disappeared —
915 // otherwise the UI would keep rendering ghosts.
916 const [previousProviders, providers] = yield* Ref.modify(
917 providersRef,
918 (previousProviders) => {
919 const providers = orderProviderSnapshots(
920 previousProviders.filter((provider) =>
921 knownInstanceIds.has(snapshotInstanceKey(provider)),
922 ),
923 );
924 return [[previousProviders, providers] as const, providers];
925 },
926 );
927 if (haveProvidersChanged(previousProviders, providers)) {
928 yield* PubSub.publish(changesPubSub, providers);
929 }
930 yield* Ref.update(maintenanceActionStatesRef, (previous) => {
931 const next = new Map(previous);
932 for (const instanceId of previous.keys()) {
933 if (!knownInstanceIds.has(instanceId)) {
934 next.delete(instanceId);
935 }
936 }
937 return next;
938 });
939 }),
940 );
941 const syncLiveSourcesAndContinue = syncLiveSources.pipe(
942 Effect.catchCause((cause) => {
943 if (Cause.hasInterruptsOnly(cause)) {
944 return Effect.interrupt;
945 }
946 return Effect.logError(
947 "provider registry instance sync failed; keeping subscription alive",
948 {
949 cause: Cause.pretty(cause),
950 },
951 );
952 }),
953 );
954
955 // Seed `providersRef` with the boot-time fallback snapshots so
956 // consumers calling `getProviders` immediately after layer build see
957 // a populated list — even before the first `syncLiveSources` refresh
958 // resolves. Cached snapshots (already in `providersRef`) merge with
959 // these via `upsertProviders` so on-disk state wins where present
960 // and pending fallbacks fill the gaps.
961 yield* upsertProviders(fallbackProviders, { publish: false });
962 // Subscribe to registry mutations BEFORE running the initial sync.
963 // `subscribeChanges` acquires the dequeue synchronously in this
964 // fibre; the subscription is active the instant this `yield*`
965 // returns. Forking the consumer loop later cannot lose a publish
966 // because no publish can reach a not-yet-subscribed dequeue.
967 //
968 // (Contrast with the pre-fix code that did
969 // `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`.
970 // `Stream.fromPubSub` defers `PubSub.subscribe` to stream start,
971 // and `forkScoped` only schedules the fibre — so a reconcile that
972 // published between "fibre scheduled" and "fibre starts running"
973 // was dropped, which made any settings change that replaced an
974 // instance never propagate to the aggregator's `providersRef`.)
975 // Subscribe to registry mutations BEFORE running the initial sync.
976 // `subscribeChanges` acquires the `PubSub.Subscription` synchronously
977 // in this fibre; the subscription is registered with the PubSub the
978 // instant this `yield*` returns, so any subsequent publish is
979 // buffered in the subscription regardless of when the consumer
980 // fibre below actually starts running.
981 //
982 // (Contrast with the pre-fix code that did
983 // `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`.
984 // `instanceRegistry.streamChanges` is `Stream.fromPubSub(changes)`,
985 // which defers `PubSub.subscribe` to stream start. `forkScoped` only
986 // schedules the consumer fibre — so a reconcile that published
987 // between "fibre scheduled" and "fibre starts running + subscribes"
988 // was dropped, which made any settings change that replaced an
989 // instance never propagate to the aggregator's `providersRef`.)
990 const instanceChanges = yield* instanceRegistry.subscribeChanges;
991 // Initial sync attaches subscriptions and snapshots current state for
992 // every instance present at boot. Provider probes are already running in
993 // their managed background fibers and never block this layer.
994 yield* syncLiveSources;
995 // React to registry mutations — instance added / removed / rebuilt.
996 // `Stream.fromSubscription` builds a stream over the pre-acquired
997 // subscription rather than subscribing on stream start, which is
998 // what closes the race.
999 yield* Stream.runForEach(
1000 Stream.fromSubscription(instanceChanges),
1001 () => syncLiveSourcesAndContinue,
1002 ).pipe(Effect.forkScoped);
1003
1004 const recoverRefreshFailure = Effect.fn("recoverRefreshFailure")(function* (
1005 cause: Cause.Cause<unknown>,
1006 ) {
1007 if (Cause.hasInterruptsOnly(cause)) {
1008 return yield* Effect.interrupt;
1009 }
1010 yield* Effect.logError("provider registry refresh failed; preserving cached providers", {
1011 cause: Cause.pretty(cause),
1012 });
1013 return yield* Ref.get(providersRef);
1014 });
1015
1016 const updateProviders = (
1017 update: (providers: ReadonlyArray<ServerProvider>) => ReadonlyArray<ServerProvider>,
1018 ) =>
1019 Ref.modify(providersRef, (currentProviders) => {
1020 const nextProviders = update(currentProviders);
1021 return [[currentProviders, nextProviders] as const, nextProviders];
1022 }).pipe(
1023 Effect.tap(([previousProviders, nextProviders]) =>
1024 haveProvidersChanged(previousProviders, nextProviders)
1025 ? PubSub.publish(changesPubSub, nextProviders)
1026 : Effect.void,
1027 ),
1028 Effect.map(([, nextProviders]) => nextProviders),
1029 );
1030
1031 const refreshWorkspaceSnapshot = Effect.fn("refreshWorkspaceSnapshot")(function* (input: {
1032 readonly instanceId: ProviderInstanceId;
1033 readonly cwd: string;
1034 readonly fresh?: boolean;
1035 }) {
1036 // Fresh scans drop other instances' snapshots for this cwd first, so a
1037 // composer on one of them scans again on next use, even when this
1038 // instance is gone or cannot be scanned.
1039 if (input.fresh) {
1040 yield* updateProviders((providers) =>
1041 providers.map((candidate) =>
1042 candidate.instanceId === input.instanceId
1043 ? candidate
1044 : dropProviderWorkspaceSnapshot(candidate, input.cwd),
1045 ),
1046 );
1047 }
1048 const providers = yield* Ref.get(providersRef);
1049 const provider = providers.find((candidate) => candidate.instanceId === input.instanceId);
1050 const workspaceSnapshotOf = (candidate: ServerProvider | undefined) =>
1051 candidate?.workspaceSnapshots?.find((s) => s.cwd === input.cwd);
1052 const scannedFrom = workspaceSnapshotOf(provider);
1053 const now = yield* DateTime.now;
1054 if (
1055 !provider ||
1056 !provider.enabled ||
1057 (!input.fresh &&
1058 scannedFrom &&
1059 !scannedFrom.slashCommandsPending &&
1060 isProviderWorkspaceSnapshotCurrent(scannedFrom, DateTime.toEpochMillis(now)))
1061 ) {
1062 return providers;
1063 }
1064 // Drivers spread their machine snapshot, whose `checkedAt` is the last
1065 // health check. The TTL needs the time this scan started reading files.
1066 const scannedAt = DateTime.formatIso(now);
1067 const instance = yield* instanceRegistry.getInstance(input.instanceId);
1068 if (!instance?.snapshotForCwd) return providers;
1069 const claimed = yield* Ref.modify(workspaceRefreshesRef, (refreshes) => {
1070 const current = refreshes.get(instance);
1071 if (current?.has(input.cwd)) return [false, refreshes] as const;
1072 const next = new Map(refreshes);
1073 next.set(instance, new Set(current).add(input.cwd));
1074 return [true, next] as const;
1075 });
1076 // A fresh scan never joins a running one, which may predate the change.
1077 if (!claimed && !input.fresh) return yield* Ref.get(providersRef);
1078 // Fresh scans also re-read the machine snapshot after invalidating caches.
1079 const refreshMachineSnapshot = input.fresh
1080 ? (instance.invalidateCaches ?? Effect.void).pipe(
1081 Effect.andThen(refreshInstance(input.instanceId)),
1082 )
1083 : Effect.void;
1084 return yield* refreshMachineSnapshot.pipe(
1085 Effect.andThen(instance.snapshotForCwd(input.cwd)),
1086 Effect.flatMap((scopedSnapshot) =>
1087 scopedSnapshot.status === "error" && scopedSnapshot.slashCommandsPending === undefined
1088 ? Ref.get(providersRef)
1089 : instanceRegistry.getInstance(input.instanceId).pipe(
1090 Effect.flatMap((currentInstance) => {
1091 if (currentInstance !== instance) return Ref.get(providersRef);
1092 // Write only if the cwd's snapshot did not change during the
1093 // scan. A session event or another scan that landed first is newer.
1094 return updateProviders((currentProviders) =>
1095 currentProviders.map((candidate) =>
1096 candidate.instanceId === input.instanceId &&
1097 Equal.equals(workspaceSnapshotOf(candidate), scannedFrom)
1098 ? upsertProviderWorkspaceSnapshot(candidate, input.cwd, {
1099 ...scopedSnapshot,
1100 checkedAt: scannedAt,
1101 })
1102 : candidate,
1103 ),
1104 );
1105 }),
1106 ),
1107 ),
1108 Effect.ensuring(
1109 claimed
1110 ? Ref.update(workspaceRefreshesRef, (refreshes) => {
1111 const next = new Map(refreshes);
1112 const current = new Set(next.get(instance));
1113 current.delete(input.cwd);
1114 if (current.size) next.set(instance, current);
1115 else next.delete(instance);
1116 return next;
1117 })
1118 : Effect.void,
1119 ),
1120 );
1121 });
1122
1123 return {
1124 getProviders: Ref.get(providersRef),
1125 refresh: (provider?: ProviderDriverKind) =>
1126 refresh(provider).pipe(Effect.catchCause(recoverRefreshFailure)),
1127 refreshInstance: (instanceId: ProviderInstanceId) =>
1128 refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)),
1129 refreshWorkspaceSnapshot: (input) =>
1130 refreshWorkspaceSnapshot(input).pipe(Effect.catchCause(recoverRefreshFailure)),
1131 getProviderMaintenanceCapabilitiesForInstance,
1132 setProviderMaintenanceActionState,
1133 get streamChanges() {
1134 return Stream.fromPubSub(changesPubSub);
1135 },
1136 } satisfies ProviderRegistry["Service"];
1137 }),
1138);