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

ProviderRegistry.ts

1,086 lines44.6 KB

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