Open History to see the last commit
1import {
2 defaultInstanceIdForDriver,
3 isProviderWorkspaceSnapshotCurrent,
4 isProviderWorkspaceSnapshotPending,
5 ProviderDriverKind,
6 type ProviderInstanceId,
7 type ProviderRuntimeModeLimit,
8 type SecretReference,
9 type ServerProvider,
10 type ServerProviderUpdateState,
11} from "@t3tools/contracts";
12import * as Cause from "effect/Cause";
13import * as Context from "effect/Context";
14import * as DateTime from "effect/DateTime";
15import * as Duration from "effect/Duration";
16import * as Deferred from "effect/Deferred";
17import * as Effect from "effect/Effect";
18import * as Equal from "effect/Equal";
19import * as Fiber from "effect/Fiber";
20import * as FileSystem from "effect/FileSystem";
21import * as Layer from "effect/Layer";
22import * as Option from "effect/Option";
23import * as Path from "effect/Path";
24import * as PubSub from "effect/PubSub";
25import * as Queue from "effect/Queue";
26import * as Ref from "effect/Ref";
27import * as Scope from "effect/Scope";
28import * as Stream from "effect/Stream";
29import * as Semaphore from "effect/Semaphore";
30import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
31import * as HostProcess from "@t3tools/shared/HostProcess";
32
33import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
34import * as ModelManifest from "./ModelManifest.ts";
35import { applyProviderCompatibility } from "./providerCompatibility.ts";
36import * as ServerConfig from "../config.ts";
37import { refreshPathFromLoginShell, refreshWindowsPath } from "../os-jank.ts";
38import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
39import * as ProviderInstanceRegistryMutator from "./ProviderInstanceRegistryMutator.ts";
40import {
41 hydrateCachedProvider,
42 isCachedProviderCorrelated,
43 orderProviderSnapshots,
44 readProviderStatusCache,
45 resolveProviderStatusCachePath,
46 writeProviderStatusCache,
47} from "./providerStatusCache.ts";
48import type {
49 ProviderInstance,
50 ProviderWorkspaceSnapshot,
51} from "@t3tools/provider-core/server/driver";
52import {
53 makeManualOnlyProviderMaintenanceCapabilities,
54 type ProviderMaintenanceCapabilities,
55 latestProviderVersionCacheKeys,
56} from "@t3tools/provider-core/server/maintenanceResolver";
57import type { ProviderSnapshotSource } from "./builtInProviderCatalog.ts";
58
59export type ProviderMaintenanceActionKind = "update";
60
61export class ProviderRegistry extends Context.Service<
62 ProviderRegistry,
63 {
64 readonly getProviders: Effect.Effect<ReadonlyArray<ServerProvider>>;
65
66 readonly refresh: (
67 provider?: ProviderDriverKind,
68 ) => Effect.Effect<ReadonlyArray<ServerProvider>>;
69
70 /** Unknown instance ids return the cached list without error. */
71 readonly refreshInstance: (
72 instanceId: ProviderInstanceId,
73 ) => Effect.Effect<ReadonlyArray<ServerProvider>>;
74
75 /** Re-reads secret-backed environments first, so a fixed secret applies without a restart. */
76 readonly reloadSecretsAndRefresh: (
77 instanceId?: ProviderInstanceId,
78 ) => Effect.Effect<ReadonlyArray<ServerProvider>>;
79
80 /**
81 * Rebuilds and re-checks enabled instances not yet found installed after the host environment
82 * changed. Drivers copy the environment when built, so only a rebuild sees a later PATH.
83 */
84 readonly rebuildMissingAndRefresh: Effect.Effect<ReadonlyArray<ServerProvider>>;
85
86 /** Rebuilds and refreshes only the instances that read a secret, with the value the caller just read. */
87 readonly applySecretAndRefresh: (
88 reference: SecretReference,
89 value: string,
90 ) => Effect.Effect<ReadonlyArray<ServerProvider>>;
91
92 /** Only refreshed instances can verify an update; the published list still includes every row. */
93 readonly refreshAfterUpdate: (
94 provider: ProviderDriverKind,
95 selectedInstanceId: ProviderInstanceId,
96 ) => Effect.Effect<ReadonlyArray<ServerProvider>>;
97
98 readonly refreshWorkspaceSnapshot: (input: {
99 readonly instanceId: ProviderInstanceId;
100 readonly cwd: string;
101 /** Directory the driver scans; the snapshot stays keyed by `cwd`. Defaults to `cwd`. */
102 readonly scanCwd?: string;
103 readonly fresh?: boolean;
104 }) => Effect.Effect<ReadonlyArray<ServerProvider>>;
105
106 /**
107 * Modes the instance offers that cannot run in `scanCwd`. Empty for an unknown instance and
108 * for a provider that reports none.
109 */
110 readonly runtimeModeLimits: (input: {
111 readonly instanceId: ProviderInstanceId;
112 readonly scanCwd: string;
113 }) => Effect.Effect<ReadonlyArray<ProviderRuntimeModeLimit>>;
114
115 /**
116 * Drop T3-owned model caches before an explicit model refresh. Pass the
117 * target of the refresh that follows. Background and ordinary refreshes
118 * keep their cache timers and must not call this.
119 */
120 readonly invalidateModelCaches: (input: {
121 readonly instanceId?: ProviderInstanceId | undefined;
122 readonly cwd?: string | undefined;
123 readonly fresh?: boolean | undefined;
124 }) => Effect.Effect<void>;
125
126 /**
127 * For an opened model picker: refetch a model manifest older than a few
128 * minutes. When it changed, recheck latest CLI versions and probe providers.
129 */
130 readonly refreshModelCatalog: Effect.Effect<void>;
131
132 readonly getProviderMaintenanceCapabilitiesForInstance: (
133 instanceId: ProviderInstanceId,
134 provider: ProviderDriverKind,
135 options?: { readonly fresh?: boolean },
136 ) => Effect.Effect<ProviderMaintenanceCapabilities>;
137
138 readonly setProviderMaintenanceActionState: (input: {
139 readonly instanceId: ProviderInstanceId;
140 readonly action: ProviderMaintenanceActionKind;
141 readonly state: ServerProviderUpdateState | null;
142 readonly targetVersion?: string | undefined;
143 }) => Effect.Effect<ReadonlyArray<ServerProvider>>;
144
145 readonly streamChanges: Stream.Stream<ReadonlyArray<ServerProvider>>;
146 }
147>()("t3/provider/ProviderRegistry") {}
148
149const loadProviders = (
150 providerSources: ReadonlyArray<ProviderSnapshotSource>,
151): Effect.Effect<ReadonlyArray<ServerProvider>> =>
152 Effect.forEach(
153 providerSources,
154 (providerSource) =>
155 providerSource.getSnapshot.pipe(
156 Effect.flatMap((snapshot) => correlateSnapshotWithSource(providerSource, snapshot)),
157 ),
158 {
159 concurrency: "unbounded",
160 },
161 );
162
163const makeManualProviderMaintenanceCapabilities = (provider: ProviderDriverKind) =>
164 makeManualOnlyProviderMaintenanceCapabilities({
165 provider,
166 packageName: null,
167 });
168
169const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean =>
170 (model.capabilities?.optionDescriptors?.length ?? 0) > 0;
171
172const MAX_WORKSPACE_SNAPSHOTS_PER_PROVIDER = 16;
173
174function dropProviderWorkspaceSnapshot(provider: ServerProvider, cwd: string): ServerProvider {
175 return provider.workspaceSnapshots?.some((snapshot) => snapshot.cwd === cwd)
176 ? {
177 ...provider,
178 workspaceSnapshots: provider.workspaceSnapshots.filter((snapshot) => snapshot.cwd !== cwd),
179 }
180 : provider;
181}
182
183export function upsertProviderWorkspaceSnapshot(
184 provider: ServerProvider,
185 cwd: string,
186 scopedSnapshot: ProviderWorkspaceSnapshot,
187): ServerProvider {
188 const previousSnapshot = provider.workspaceSnapshots?.find((snapshot) => snapshot.cwd === cwd);
189 const optionDescriptors = scopedSnapshot.optionDescriptors ?? previousSnapshot?.optionDescriptors;
190 const models = scopedSnapshot.workspaceModelsPending
191 ? previousSnapshot?.models
192 : scopedSnapshot.workspaceModels;
193 const workspaceSnapshot = {
194 cwd,
195 checkedAt: scopedSnapshot.checkedAt,
196 slashCommands: scopedSnapshot.slashCommandsPending
197 ? (previousSnapshot?.slashCommands ?? scopedSnapshot.slashCommands)
198 : scopedSnapshot.slashCommands,
199 ...(scopedSnapshot.slashCommandsPending ? { slashCommandsPending: true } : {}),
200 skills: scopedSnapshot.skills,
201 ...(optionDescriptors === undefined ? {} : { optionDescriptors }),
202 ...(models === undefined ? {} : { models }),
203 ...(scopedSnapshot.workspaceModelsPending ? { modelsPending: true } : {}),
204 } satisfies NonNullable<ServerProvider["workspaceSnapshots"]>[number];
205 return {
206 ...provider,
207 workspaceSnapshots: [
208 ...(provider.workspaceSnapshots ?? []).filter((snapshot) => snapshot.cwd !== cwd),
209 workspaceSnapshot,
210 ].slice(-MAX_WORKSPACE_SNAPSHOTS_PER_PROVIDER),
211 };
212}
213
214const shouldRetainMissingProviderModels = (provider: ServerProvider): boolean => {
215 if (provider.driver === ProviderDriverKind.make("pi")) {
216 // Pi auth becomes known only after inventory discovery: empty means unauthenticated; failed/interactive discovery preserves unknown auth and cached models.
217 return !(
218 provider.installed &&
219 (provider.status === "ready" || provider.status === "warning") &&
220 provider.auth.status !== "unknown"
221 );
222 }
223
224 if (provider.driver === ProviderDriverKind.make("acpRegistry")) {
225 // Only completed ACP discovery provides nativeSessions and inventory; placeholder probes cannot establish auth for agents without sign-in.
226 return !(
227 provider.installed &&
228 provider.status === "ready" &&
229 provider.nativeSessions !== undefined
230 );
231 }
232
233 if (provider.driver === ProviderDriverKind.make("kiro")) {
234 // Kiro is ready once `whoami` confirms the account, even when `--list-models` failed and
235 // the snapshot fell back to the built-in list.
236 return true;
237 }
238
239 if (provider.driver === ProviderDriverKind.make("claudeAgent")) {
240 // Claude Code keeps one gateway model cache per Claude home, for one base URL at a time, so a
241 // ready probe can omit this instance's gateway models after another instance or a terminal
242 // `claude` on a different gateway rewrote that cache.
243 return true;
244 }
245
246 const isAntigravity = provider.driver === ProviderDriverKind.make("antigravity");
247 const isCodex = provider.driver === ProviderDriverKind.make("codex");
248 const isOpenCode = provider.driver === ProviderDriverKind.make("opencode");
249 if (!isAntigravity && !isCodex && !isOpenCode) {
250 // Any other driver must report ready only after a completed model listing, or opt out above:
251 // a ready list is authoritative, and warning/error probes keep the old models.
252 return !(provider.installed && provider.status === "ready");
253 }
254
255 if (
256 (isAntigravity || isCodex) &&
257 (!provider.enabled || provider.auth.status === "unauthenticated")
258 ) {
259 return false;
260 }
261
262 // Antigravity's local health check does not authenticate or discover models.
263 const isPendingAntigravityAuthentication =
264 isAntigravity && provider.status === "warning" && provider.auth.status === "unknown";
265 const isPendingInitialProbe =
266 provider.enabled && !provider.installed && provider.status === "warning";
267 // A cold OpenCode server can finish its probe as a warning before it lists any models.
268 const isIncompleteInstalledProbe =
269 provider.installed &&
270 (provider.status === "error" || ((isCodex || isOpenCode) && provider.status === "warning"));
271 return isPendingAntigravityAuthentication || isPendingInitialProbe || isIncompleteInstalledProbe;
272};
273
274const shouldRetainMissingOpenCodeMetadata = (provider: ServerProvider): boolean =>
275 provider.driver === ProviderDriverKind.make("opencode") &&
276 shouldRetainMissingProviderModels(provider);
277
278const mergeProviderModels = (
279 provider: ServerProvider,
280 previousModels: ReadonlyArray<ServerProvider["models"][number]>,
281 nextModels: ReadonlyArray<ServerProvider["models"][number]>,
282): ReadonlyArray<ServerProvider["models"][number]> => {
283 const shouldRetainMissingModels = shouldRetainMissingProviderModels(provider);
284 const updateRequiredSlugs = new Set(provider.updateRequiredModels?.map((model) => model.slug));
285 const unavailableSubProviders = new Set(
286 provider.subProviders?.flatMap((subProvider) =>
287 subProvider.unavailableReason === undefined ? [] : [subProvider.name],
288 ),
289 );
290 const retainablePreviousModels = previousModels.filter(
291 (model) =>
292 !model.isCustom &&
293 !updateRequiredSlugs.has(model.slug) &&
294 !unavailableSubProviders.has(model.subProvider ?? ""),
295 );
296
297 if (shouldRetainMissingModels && nextModels.length === 0 && retainablePreviousModels.length > 0) {
298 return retainablePreviousModels;
299 }
300
301 const previousBySlug = new Map(previousModels.map((model) => [model.slug, model] as const));
302 const preserveDefault =
303 nextModels.length > 0 && !nextModels.some((model) => model.isDefault === true);
304 const mergedModels = nextModels.map((model) => {
305 const previousModel = previousBySlug.get(model.slug);
306 if (!previousModel) {
307 return model;
308 }
309 const retainCapabilities = !hasModelCapabilities(model) && hasModelCapabilities(previousModel);
310 const retainDefault = preserveDefault && previousModel.isDefault === true;
311 if (!retainCapabilities && !retainDefault) {
312 return model;
313 }
314 const aliases = retainDefault
315 ? [...new Set([...(model.aliases ?? []), ...(previousModel.aliases ?? [])])]
316 : undefined;
317 return {
318 ...model,
319 ...(retainCapabilities ? { capabilities: previousModel.capabilities } : {}),
320 ...(retainDefault
321 ? {
322 isDefault: true,
323 ...(aliases && aliases.length > 0 ? { aliases } : {}),
324 }
325 : {}),
326 };
327 });
328 const nextSlugs = new Set(nextModels.map((model) => model.slug));
329 return shouldRetainMissingModels
330 ? [...mergedModels, ...retainablePreviousModels.filter((model) => !nextSlugs.has(model.slug))]
331 : mergedModels;
332};
333
334/** Antigravity health checks only initialize; preserve previously verified Google auth across restarts. */
335const carrySavedAntigravityAccount = (
336 previousProvider: ServerProvider,
337 nextProvider: ServerProvider,
338): Pick<ServerProvider, "auth" | "status"> | undefined => {
339 const antigravity = ProviderDriverKind.make("antigravity");
340 if (
341 nextProvider.driver !== antigravity ||
342 previousProvider.driver !== antigravity ||
343 !nextProvider.enabled ||
344 nextProvider.auth.status !== "unknown" ||
345 previousProvider.auth.status !== "authenticated" ||
346 (nextProvider.auth.type !== undefined &&
347 nextProvider.auth.type !== previousProvider.auth.type) ||
348 (!nextProvider.installed && nextProvider.status !== "warning")
349 ) {
350 return undefined;
351 }
352 const status =
353 nextProvider.installed && nextProvider.status === "warning" ? "ready" : nextProvider.status;
354 return { auth: previousProvider.auth, status };
355};
356
357/** One failed check after a ready one is often transient, so its retained catalog stays offered. */
358const retainsReadyCatalog = (
359 previousProvider: ServerProvider,
360 nextProvider: ServerProvider,
361 status: ServerProvider["status"],
362 models: ServerProvider["models"],
363): boolean =>
364 nextProvider.enabled &&
365 nextProvider.installed &&
366 (status === "error" || status === "warning") &&
367 nextProvider.auth.status !== "unauthenticated" &&
368 models.length > 0 &&
369 (previousProvider.status === "ready" ||
370 // Usage and metadata updates republish the same check.
371 (previousProvider.modelsRetained === true &&
372 previousProvider.checkedAt === nextProvider.checkedAt));
373
374export const mergeProviderSnapshot = (
375 previousProvider: ServerProvider | undefined,
376 nextProvider: ServerProvider,
377): ServerProvider => {
378 if (!previousProvider) {
379 return nextProvider;
380 }
381 const savedAccount = carrySavedAntigravityAccount(previousProvider, nextProvider);
382 const { message: _uncheckedMessage, ...nextWithoutMessage } = nextProvider;
383 const models = mergeProviderModels(nextProvider, previousProvider.models, nextProvider.models);
384 // Folder catalogs were compared with the old machine catalog, so every folder rescans.
385 const previousWorkspaceSnapshots = Equal.equals(models, previousProvider.models)
386 ? previousProvider.workspaceSnapshots
387 : previousProvider.workspaceSnapshots?.map((snapshot) => ({
388 ...snapshot,
389 modelsPending: true,
390 }));
391 const nextWorkspaceSnapshots = nextProvider.workspaceSnapshots;
392 // A provider reports only folders its own sessions saw, so registry scans of other folders stay.
393 const workspaceSnapshots =
394 nextWorkspaceSnapshots === undefined ||
395 !nextProvider.enabled ||
396 nextProvider.auth.status === "unauthenticated" ||
397 (!nextProvider.installed && nextProvider.status === "error")
398 ? (nextWorkspaceSnapshots ?? previousWorkspaceSnapshots)
399 : [
400 ...(previousWorkspaceSnapshots ?? []).filter(
401 ({ cwd }) => !nextWorkspaceSnapshots.some((snapshot) => snapshot.cwd === cwd),
402 ),
403 ...nextWorkspaceSnapshots,
404 ].slice(-MAX_WORKSPACE_SNAPSHOTS_PER_PROVIDER);
405 return {
406 ...(savedAccount?.status === "ready" ? nextWithoutMessage : nextProvider),
407 ...savedAccount,
408 models,
409 ...(retainsReadyCatalog(
410 previousProvider,
411 nextProvider,
412 savedAccount?.status ?? nextProvider.status,
413 models,
414 )
415 ? { modelsRetained: true }
416 : {}),
417 ...(workspaceSnapshots === undefined ? {} : { workspaceSnapshots }),
418 ...(nextProvider.workspaceRescannedAt === undefined &&
419 previousProvider.workspaceRescannedAt !== undefined
420 ? { workspaceRescannedAt: previousProvider.workspaceRescannedAt }
421 : {}),
422 ...(shouldRetainMissingOpenCodeMetadata(nextProvider)
423 ? {
424 slashCommands:
425 nextProvider.slashCommands.length === 0
426 ? previousProvider.slashCommands
427 : nextProvider.slashCommands,
428 skills: nextProvider.skills.length === 0 ? previousProvider.skills : nextProvider.skills,
429 }
430 : {}),
431 };
432};
433
434const haveProvidersChanged = (
435 previousProviders: ReadonlyArray<ServerProvider>,
436 nextProviders: ReadonlyArray<ServerProvider>,
437): boolean => !Equal.equals(previousProviders, nextProviders);
438
439const correlateSnapshotWithSource = (
440 source: ProviderSnapshotSource,
441 snapshot: ServerProvider,
442): Effect.Effect<ServerProvider> => {
443 if (snapshot.instanceId !== source.instanceId) {
444 return Effect.die(
445 new Error(
446 `Provider snapshot instance mismatch: source '${source.instanceId}' emitted '${snapshot.instanceId}'.`,
447 ),
448 );
449 }
450 if (snapshot.driver !== source.driverKind) {
451 return Effect.die(
452 new Error(
453 `Provider snapshot driver mismatch for instance '${source.instanceId}': source '${source.driverKind}' emitted '${snapshot.driver}'.`,
454 ),
455 );
456 }
457 return Effect.succeed(snapshot);
458};
459
460const snapshotInstanceKey = (provider: ServerProvider): ProviderInstanceId => {
461 return provider.instanceId;
462};
463
464// Rebuilt instances have new PubSubs; capture their fresh closures instead of a closed source.
465const buildSnapshotSource = (instance: ProviderInstance): ProviderSnapshotSource => ({
466 instanceId: instance.instanceId,
467 driverKind: instance.driverKind,
468 getSnapshot: instance.snapshot.getSnapshot,
469 refresh: instance.snapshot.refresh,
470 streamChanges: instance.snapshot.streamChanges,
471});
472
473export const layer = Layer.effect(
474 ProviderRegistry,
475 Effect.gen(function* () {
476 const instanceRegistry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
477 const instanceRegistryMutator =
478 yield* ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator;
479 const manifestService = yield* ModelManifest.ModelManifest;
480 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
481 const serviceScope = yield* Effect.scope;
482 const config = yield* ServerConfig.ServerConfig;
483 const fileSystem = yield* FileSystem.FileSystem;
484 const path = yield* Path.Path;
485
486 const changesPubSub = yield* Effect.acquireRelease(
487 PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
488 PubSub.shutdown,
489 );
490
491 const bootInstances = yield* instanceRegistry.listInstances;
492 const bootSources = bootInstances.map(buildSnapshotSource);
493 const fallbackProviders = yield* loadProviders(bootSources);
494 const fallbackByInstance = new Map<ProviderInstanceId, ServerProvider>();
495 for (let index = 0; index < fallbackProviders.length; index++) {
496 const provider = fallbackProviders[index];
497 const source = bootSources[index];
498 if (provider === undefined || source === undefined) {
499 continue;
500 }
501 fallbackByInstance.set(source.instanceId, provider);
502 }
503 // Read after the snapshots: a snapshot read as awaiting is the pre-check placeholder.
504 const awaitingBootInstances = new Set<ProviderInstance>();
505 for (const instance of bootInstances) {
506 if (yield* instance.snapshot.isAwaitingFirstCheck ?? Effect.succeed(false)) {
507 awaitingBootInstances.add(instance);
508 }
509 }
510
511 const bootProviders = yield* Effect.forEach(
512 bootSources,
513 (source, index) =>
514 Effect.gen(function* () {
515 const filePath = yield* resolveProviderStatusCachePath({
516 cacheDir: config.providerStatusCacheDir,
517 instanceId: source.instanceId,
518 }).pipe(Effect.provideService(Path.Path, path));
519 const fallbackProvider = fallbackByInstance.get(source.instanceId);
520 if (fallbackProvider === undefined) {
521 return undefined;
522 }
523 // A completed check is seeded by the boot upsert instead, which persists it.
524 const placeholder = awaitingBootInstances.has(bootInstances[index]!)
525 ? fallbackProvider
526 : undefined;
527 return yield* readProviderStatusCache(filePath).pipe(
528 Effect.provideService(FileSystem.FileSystem, fileSystem),
529 Effect.flatMap((cachedProvider) => {
530 if (cachedProvider === undefined) {
531 return Effect.succeed(placeholder);
532 }
533 const correlation = {
534 cachedProvider,
535 fallbackProvider,
536 } as const;
537 if (!isCachedProviderCorrelated(correlation)) {
538 return Effect.logWarning("provider status cache identity mismatch, ignoring", {
539 path: filePath,
540 instanceId: source.instanceId,
541 cachedInstanceId: cachedProvider.instanceId ?? null,
542 driver: source.driverKind,
543 cachedDriver: cachedProvider.driver ?? null,
544 }).pipe(Effect.as(placeholder));
545 }
546 return Effect.succeed(hydrateCachedProvider(correlation));
547 }),
548 );
549 }),
550 { concurrency: "unbounded" },
551 ).pipe(
552 Effect.map((providers) =>
553 orderProviderSnapshots(
554 providers.filter((provider): provider is ServerProvider => provider !== undefined),
555 ),
556 ),
557 );
558 const initialManifest = yield* manifestService.current;
559 const classifyCompatibility = (
560 provider: ServerProvider,
561 manifest: ModelManifest.ModelManifestData,
562 ) =>
563 applyProviderCompatibility(
564 provider,
565 manifest.compatibility,
566 ModelManifest.BUNDLED_MODEL_MANIFEST.compatibility,
567 );
568 const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(
569 bootProviders.map((provider) => classifyCompatibility(provider, initialManifest)),
570 );
571 const workspaceRefreshesRef = yield* Ref.make<
572 ReadonlyMap<ProviderInstance, ReadonlyMap<string, Deferred.Deferred<void>>>
573 >(new Map());
574 const workspaceRescans = yield* Queue.unbounded<{
575 readonly instance: ProviderInstance;
576 readonly cwd: string;
577 }>();
578 const maintenanceActionStatesRef = yield* Ref.make<
579 ReadonlyMap<
580 ProviderInstanceId,
581 { readonly update?: ServerProviderUpdateState; readonly targetVersion?: string | undefined }
582 >
583 >(new Map());
584
585 const liveSubsRef = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ProviderInstance>>(
586 new Map(),
587 );
588 const syncSemaphore = yield* Semaphore.make(1);
589
590 const persistProvider = Effect.fn("ProviderRegistry.persistProvider")(function* (
591 provider: ServerProvider,
592 ) {
593 const key = snapshotInstanceKey(provider);
594 const filePath = yield* resolveProviderStatusCachePath({
595 cacheDir: config.providerStatusCacheDir,
596 instanceId: key,
597 }).pipe(Effect.provideService(Path.Path, path));
598 const {
599 workspaceSnapshots: _workspaceSnapshots,
600 workspaceRescannedAt: _workspaceRescannedAt,
601 ...machineProvider
602 } = provider;
603 yield* writeProviderStatusCache({ filePath, provider: machineProvider }).pipe(
604 Effect.provideService(FileSystem.FileSystem, fileSystem),
605 Effect.provideService(Path.Path, path),
606 Effect.tapError(Effect.logError),
607 Effect.ignore,
608 );
609 });
610
611 const applyProviderUpdateState = Effect.fn("applyProviderUpdateState")(function* (
612 provider: ServerProvider,
613 ) {
614 const maintenanceActionStates = yield* Ref.get(maintenanceActionStatesRef);
615 const updateState = maintenanceActionStates.get(provider.instanceId)?.update;
616 if (!updateState) {
617 const { updateState: _updateState, ...providerWithoutUpdateState } = provider;
618 return providerWithoutUpdateState;
619 }
620 return {
621 ...provider,
622 updateState,
623 };
624 });
625
626 const upsertProviders = Effect.fn("upsertProviders")(function* (
627 nextProviders: ReadonlyArray<ServerProvider>,
628 options?: {
629 readonly publish?: boolean;
630 readonly persist?: boolean;
631 readonly replace?: boolean;
632 },
633 ) {
634 const manifest = yield* manifestService.current;
635 const nextProvidersWithUpdateState = yield* Effect.forEach(
636 nextProviders,
637 applyProviderUpdateState,
638 {
639 concurrency: "unbounded",
640 },
641 );
642 const [previousProviders, providers, providersToPersist] = yield* Ref.modify(
643 providersRef,
644 (previousProviders) => {
645 const mergedProviders = new Map(
646 previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
647 );
648 const updatedKeys = new Set<ProviderInstanceId>();
649
650 for (const provider of nextProvidersWithUpdateState) {
651 const key = snapshotInstanceKey(provider);
652 updatedKeys.add(key);
653 mergedProviders.set(
654 key,
655 options?.replace === true
656 ? provider
657 : mergeProviderSnapshot(mergedProviders.get(key), provider),
658 );
659 }
660
661 const providers = orderProviderSnapshots(
662 [...mergedProviders.values()].map((provider) =>
663 classifyCompatibility(provider, manifest),
664 ),
665 );
666 const providersToPersist = providers.filter((provider) =>
667 updatedKeys.has(snapshotInstanceKey(provider)),
668 );
669 return [[previousProviders, providers, providersToPersist] as const, providers];
670 },
671 );
672
673 if (haveProvidersChanged(previousProviders, providers)) {
674 if (options?.persist !== false) {
675 yield* Effect.forEach(providersToPersist, persistProvider, {
676 concurrency: "unbounded",
677 discard: true,
678 });
679 }
680 if (options?.publish !== false) {
681 // A newer upsert may have committed and published during the cache write; never republish an older array.
682 yield* PubSub.publish(changesPubSub, yield* Ref.get(providersRef));
683 }
684 }
685
686 return providers;
687 });
688
689 const compatibilityRefreshRunning = yield* Ref.make(false);
690 // Reclassify the current model after fetch; republishing the old probe could overwrite newer health results.
691 const refreshCompatibility = Effect.gen(function* () {
692 if (!(yield* Ref.getAndSet(compatibilityRefreshRunning, true))) {
693 yield* manifestService.refresh.pipe(
694 Effect.andThen(upsertProviders([], { persist: false })),
695 Effect.ensuring(Ref.set(compatibilityRefreshRunning, false)),
696 Effect.forkIn(serviceScope),
697 );
698 }
699 });
700 const syncProvider = Effect.fn("syncProvider")(function* (
701 provider: ServerProvider,
702 options?: {
703 readonly publish?: boolean;
704 },
705 ) {
706 // Latest-version status cannot resolve a failed recommended-version install.
707 if (provider.versionAdvisory?.status === "current") {
708 yield* Ref.update(maintenanceActionStatesRef, (previous) => {
709 const action = previous.get(provider.instanceId);
710 if (
711 action?.targetVersion !== undefined ||
712 (action?.update?.status !== "unchanged" && action?.update?.status !== "failed")
713 ) {
714 return previous;
715 }
716 const next = new Map(previous);
717 next.delete(provider.instanceId);
718 return next;
719 });
720 }
721 const providers = yield* upsertProviders([provider], options);
722 yield* refreshCompatibility;
723 return providers;
724 });
725
726 const setProviderMaintenanceActionState = Effect.fn("setProviderMaintenanceActionState")(
727 function* (input: {
728 readonly instanceId: ProviderInstanceId;
729 readonly action: "update";
730 readonly state: ServerProviderUpdateState | null;
731 readonly targetVersion?: string | undefined;
732 }) {
733 yield* Ref.update(maintenanceActionStatesRef, (previous) => {
734 const next = new Map(previous);
735 if (input.state === null || input.state.status === "idle") {
736 next.delete(input.instanceId);
737 } else {
738 next.set(input.instanceId, { update: input.state, targetVersion: input.targetVersion });
739 }
740 return next;
741 });
742
743 const existingProviders = yield* Ref.get(providersRef);
744 const matchingProvider = existingProviders.find(
745 (candidate) => candidate.instanceId === input.instanceId,
746 );
747 if (!matchingProvider) {
748 return existingProviders;
749 }
750
751 const nextProvider = yield* applyProviderUpdateState(matchingProvider);
752 return yield* upsertProviders([nextProvider], {
753 persist: false,
754 });
755 },
756 );
757
758 const isCurrentInstance = (instance: ProviderInstance) =>
759 instanceRegistry
760 .getInstance(instance.instanceId)
761 .pipe(Effect.map((current) => current === instance));
762
763 const refreshOneSource = Effect.fn("refreshOneSource")(function* (instance: ProviderInstance) {
764 const providerSource = buildSnapshotSource(instance);
765 // Enrichment can publish a newer snapshot before refresh returns its pre-enrichment probe.
766 const probe = yield* providerSource.refresh.pipe(
767 Effect.andThen(providerSource.getSnapshot),
768 Effect.exit,
769 );
770 // Settings can replace or remove the instance mid-probe; its late result or failure is stale.
771 if (!(yield* isCurrentInstance(instance))) {
772 return yield* Ref.get(providersRef);
773 }
774 const nextProvider = yield* probe;
775 return yield* correlateSnapshotWithSource(providerSource, nextProvider).pipe(
776 Effect.flatMap(syncProvider),
777 );
778 });
779
780 type RefreshAllCompletion = Deferred.Deferred<ReadonlyArray<ServerProvider>>;
781 // A refresh is how a user asks T3 to see a CLI installed since launch; a burst shares one probe.
782 // Drivers copy the environment when built, so instances still missing their CLI are rebuilt
783 // on the new PATH. They cannot have live sessions, and installed ones keep theirs.
784 // Compared with the last PATH seen here, since other features re-read the login shell too.
785 const hostEnvironment = yield* HostProcess.Environment;
786 const readHostPath = () => hostEnvironment.PATH ?? hostEnvironment.Path ?? hostEnvironment.path;
787 const lastHostPathRef = yield* Ref.make(readHostPath());
788 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
789 const refreshHostPath = yield* refreshWindowsPath().pipe(
790 Effect.andThen(refreshPathFromLoginShell()),
791 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
792 Effect.andThen(
793 Effect.suspend(() => {
794 const path = readHostPath();
795 return Ref.getAndSet(lastHostPathRef, path).pipe(Effect.map((last) => last !== path));
796 }),
797 ),
798 Effect.flatMap((changed) =>
799 changed
800 ? Ref.get(providersRef).pipe(
801 Effect.flatMap((providers) =>
802 instanceRegistryMutator.rebuild(
803 providers
804 .filter((provider) => provider.enabled && !provider.installed)
805 .map((provider) => provider.instanceId),
806 ),
807 ),
808 )
809 : Effect.void,
810 ),
811 Effect.cachedWithTTL(Duration.seconds(10)),
812 );
813 const refreshAllInFlightRef = yield* Ref.make<Option.Option<RefreshAllCompletion>>(
814 Option.none(),
815 );
816
817 // What the last full pass could see; a later manifest fetch does not reach providers by itself.
818 const probedManifestUpdatedAt = yield* Ref.make(initialManifest.updatedAt);
819
820 const refreshAll = Effect.fn("refreshAll")(function* () {
821 yield* refreshHostPath;
822 const claimed = yield* Ref.modify(
823 refreshAllInFlightRef,
824 (
825 inFlight,
826 ): readonly [
827 { readonly owner: boolean; readonly completion: RefreshAllCompletion },
828 Option.Option<RefreshAllCompletion>,
829 ] => {
830 if (Option.isSome(inFlight)) {
831 return [{ owner: false, completion: inFlight.value }, inFlight];
832 }
833 const completion = Deferred.makeUnsafe<ReadonlyArray<ServerProvider>>();
834 return [{ owner: true, completion }, Option.some(completion)];
835 },
836 );
837 if (claimed.owner) {
838 // Detach shared passes so the first caller's interruption cannot cancel other callers' work.
839 // Syncing first keeps a refresh right after a rebuild from probing the replaced instance.
840 yield* manifestService.current.pipe(
841 Effect.flatMap(({ updatedAt }) =>
842 syncLiveSourcesAndContinue.pipe(
843 Effect.andThen(Ref.get(liveSubsRef)),
844 Effect.flatMap((instances) =>
845 Effect.forEach(instances.values(), (instance) => refreshOneSource(instance), {
846 concurrency: "unbounded",
847 discard: true,
848 }),
849 ),
850 Effect.andThen(Ref.get(providersRef)),
851 Effect.tap(() => Ref.set(probedManifestUpdatedAt, updatedAt)),
852 ),
853 ),
854 Effect.onExit((exit) =>
855 Ref.set(refreshAllInFlightRef, Option.none()).pipe(
856 Effect.andThen(Deferred.done(claimed.completion, exit)),
857 ),
858 ),
859 Effect.forkDetach,
860 );
861 }
862 return yield* Deferred.await(claimed.completion);
863 });
864
865 const refresh = Effect.fn("refresh")(function* (provider?: ProviderDriverKind) {
866 if (provider === undefined) {
867 return yield* refreshAll();
868 }
869 return yield* refreshInstance(defaultInstanceIdForDriver(provider));
870 });
871
872 const refreshInstance = Effect.fn("refreshInstance")(function* (
873 instanceId: ProviderInstanceId,
874 ) {
875 yield* refreshHostPath;
876 yield* syncLiveSourcesAndContinue;
877 const instance = (yield* Ref.get(liveSubsRef)).get(instanceId);
878 if (!instance) {
879 return yield* Ref.get(providersRef);
880 }
881 return yield* refreshOneSource(instance);
882 });
883
884 const reloadSecretsAndRefresh = Effect.fn("reloadSecretsAndRefresh")(function* (
885 instanceId?: ProviderInstanceId,
886 ) {
887 yield* instanceRegistryMutator.reloadSecrets(instanceId);
888 return yield* instanceId === undefined ? refresh() : refreshInstance(instanceId);
889 });
890
891 // Only instances whose CLI was not found are rebuilt; installed ones may have live sessions.
892 const rebuildMissingAndRefresh = Effect.fn("rebuildMissingAndRefresh")(function* () {
893 const instances = yield* instanceRegistry.listInstances;
894 yield* refresh().pipe(Effect.catchCause(recoverRefreshFailure));
895 const missing = yield* Effect.filter(instances, (instance) =>
896 Effect.gen(function* () {
897 // ACP also reports installed:false for setup states unrelated to executable discovery.
898 if (
899 !instance.enabled ||
900 instance.driverKind === "acpRegistry" ||
901 !(yield* isCurrentInstance(instance))
902 )
903 return false;
904 const snapshot = yield* instance.snapshot.getSnapshot;
905 return !snapshot.installed;
906 }),
907 );
908 if (missing.length === 0) return yield* Ref.get(providersRef);
909 yield* instanceRegistryMutator.rebuild(missing.map((instance) => instance.instanceId));
910 // A shared pass already in flight may hold the retired instances, so probe each rebuilt one.
911 yield* Effect.forEach(
912 missing,
913 (instance) =>
914 refreshInstance(instance.instanceId).pipe(Effect.catchCause(recoverRefreshFailure)),
915 { concurrency: "unbounded", discard: true },
916 );
917 return yield* Ref.get(providersRef);
918 });
919
920 const applySecretAndRefresh = Effect.fn("applySecretAndRefresh")(function* (
921 reference: SecretReference,
922 value: string,
923 ) {
924 const instanceIds = yield* instanceRegistryMutator.applySecret(reference, value);
925 yield* Effect.forEach(instanceIds, refreshInstance, { discard: true });
926 return yield* Ref.get(providersRef);
927 });
928
929 const refreshAfterUpdate = Effect.fn("refreshAfterUpdate")(function* (
930 provider: ProviderDriverKind,
931 selectedInstanceId: ProviderInstanceId,
932 ) {
933 yield* manifestService.forceRefresh;
934 const instances = (yield* instanceRegistry.listInstances).filter(
935 (instance) =>
936 instance.driverKind === provider &&
937 (instance.enabled || instance.instanceId === selectedInstanceId),
938 );
939 const failedInstances = new Set<ProviderInstanceId>();
940 const recoverInstanceFailure = Effect.fn("recoverPostUpdateRefreshFailure")(function* (
941 instanceId: ProviderInstanceId,
942 cause: Cause.Cause<unknown>,
943 ) {
944 if (Cause.hasInterruptsOnly(cause)) {
945 return yield* Effect.interrupt;
946 }
947 yield* Effect.logError("provider post-update refresh failed", {
948 instanceId,
949 cause: Cause.pretty(cause),
950 });
951 failedInstances.add(instanceId);
952 // A cached ready snapshot cannot verify a successful update.
953 return yield* updateProviders((providers) =>
954 providers.map((candidate) =>
955 candidate.instanceId === instanceId
956 ? { ...candidate, status: "error", message: "Provider refresh failed after update." }
957 : candidate,
958 ),
959 );
960 });
961 // Instances can share the replaced service, so none may invalidate before it restarts.
962 const selectedInstance = instances.find(
963 (instance) => instance.instanceId === selectedInstanceId,
964 );
965 if (selectedInstance?.afterUpdate !== undefined) {
966 // The probe below reports what is running, so a failed hook needs no status of its own.
967 yield* selectedInstance.afterUpdate.pipe(
968 Effect.catchCause((cause) =>
969 Cause.hasInterruptsOnly(cause)
970 ? Effect.interrupt
971 : Effect.logError("provider post-update hook failed", {
972 instanceId: selectedInstance.instanceId,
973 cause: Cause.pretty(cause),
974 }),
975 ),
976 );
977 }
978 // Accounts can share an installation, but discovery must use each
979 // instance's own executable, environment, and credentials.
980 yield* Effect.forEach(
981 instances,
982 (instance) =>
983 Effect.gen(function* () {
984 yield* instance.invalidateCaches ?? Effect.void;
985 const maintenance = yield* instance.snapshot.resolveMaintenance({ fresh: true });
986 yield* Effect.forEach(
987 latestProviderVersionCacheKeys(maintenance),
988 latestVersions.invalidate,
989 { discard: true },
990 );
991 }).pipe(Effect.catchCause((cause) => recoverInstanceFailure(instance.instanceId, cause))),
992 { concurrency: "unbounded", discard: true },
993 );
994 yield* Effect.forEach(
995 instances.filter((instance) => !failedInstances.has(instance.instanceId)),
996 (instance) =>
997 refreshOneSource(instance).pipe(
998 Effect.catchCause((cause) => recoverInstanceFailure(instance.instanceId, cause)),
999 ),
1000 { concurrency: "unbounded", discard: true },
1001 );
1002 // A replaced instance's cached row did not come from this pass's probe.
1003 const refreshedInstances = yield* Effect.filter(
1004 instances.filter((instance) => !failedInstances.has(instance.instanceId)),
1005 isCurrentInstance,
1006 );
1007 const refreshedInstanceIds = new Set(
1008 refreshedInstances.map((instance) => instance.instanceId),
1009 );
1010 return (yield* Ref.get(providersRef)).filter((candidate) =>
1011 refreshedInstanceIds.has(candidate.instanceId),
1012 );
1013 });
1014
1015 const getProviderMaintenanceCapabilitiesForInstance = Effect.fn(
1016 "getProviderMaintenanceCapabilitiesForInstance",
1017 )(function* (
1018 instanceId: ProviderInstanceId,
1019 provider: ProviderDriverKind,
1020 options?: { readonly fresh?: boolean },
1021 ) {
1022 // liveSubsRef trails reconciliation and could run a retired instance's command; read the registry.
1023 const instance = yield* instanceRegistry.getInstance(instanceId);
1024 if (!instance || instance.driverKind !== provider) {
1025 return makeManualProviderMaintenanceCapabilities(provider);
1026 }
1027 return yield* instance.snapshot.resolveMaintenance(options);
1028 });
1029
1030 const syncLiveSources = syncSemaphore.withPermits(1)(
1031 Effect.gen(function* () {
1032 const instances = yield* instanceRegistry.listInstances;
1033 const unavailableProviders = yield* instanceRegistry.listUnavailable;
1034 const nextByInstance = new Map<ProviderInstanceId, ProviderInstance>(
1035 instances.map((instance) => [instance.instanceId, instance] as const),
1036 );
1037 const knownInstanceIds = new Set<ProviderInstanceId>(nextByInstance.keys());
1038 for (const provider of unavailableProviders) {
1039 knownInstanceIds.add(snapshotInstanceKey(provider));
1040 }
1041 const previousSubs = yield* Ref.get(liveSubsRef);
1042
1043 const carriedOver = new Map<ProviderInstanceId, ProviderInstance>();
1044 for (const [instanceId, previousInstance] of previousSubs) {
1045 const nextInstance = nextByInstance.get(instanceId);
1046 if (nextInstance !== undefined && nextInstance === previousInstance) {
1047 carriedOver.set(instanceId, previousInstance);
1048 }
1049 }
1050
1051 const newlyAdded: Array<readonly [ProviderInstanceId, ProviderInstance]> = [];
1052 for (const [instanceId, instance] of nextByInstance) {
1053 if (carriedOver.has(instanceId)) {
1054 continue;
1055 }
1056 newlyAdded.push([instanceId, instance] as const);
1057 }
1058
1059 const rebuiltInstanceIds = new Set(
1060 newlyAdded
1061 .map(([instanceId]) => instanceId)
1062 .filter((instanceId) => previousSubs.has(instanceId)),
1063 );
1064 if (rebuiltInstanceIds.size > 0) {
1065 const [previousProviders, providers] = yield* Ref.modify(
1066 providersRef,
1067 (previousProviders) => {
1068 const providers = previousProviders.map((provider) => {
1069 if (!rebuiltInstanceIds.has(provider.instanceId)) return provider;
1070 const { workspaceSnapshots: _workspaceSnapshots, ...machineSnapshot } = provider;
1071 return machineSnapshot;
1072 });
1073 return [[previousProviders, providers] as const, providers];
1074 },
1075 );
1076 if (haveProvidersChanged(previousProviders, providers)) {
1077 yield* PubSub.publish(changesPubSub, providers);
1078 }
1079 }
1080
1081 // Subscribe before reading so a probe completing mid-sync is observed by at least one path.
1082 for (const [, instance] of newlyAdded) {
1083 const source = buildSnapshotSource(instance);
1084 yield* Stream.runForEach(source.streamChanges, (provider) =>
1085 correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)),
1086 ).pipe(Effect.forkScoped);
1087 if (instance.workspaceRescans) {
1088 yield* Stream.runForEach(instance.workspaceRescans, (cwd) =>
1089 Queue.offer(workspaceRescans, { instance, cwd }),
1090 ).pipe(Effect.forkScoped);
1091 }
1092 }
1093 yield* Effect.yieldNow;
1094
1095 yield* Effect.forEach(
1096 newlyAdded,
1097 ([, instance]) =>
1098 Effect.gen(function* () {
1099 const source = buildSnapshotSource(instance);
1100 const provider = yield* source.getSnapshot;
1101 // Boot shows the cached status until this instance's first check publishes a result.
1102 if (
1103 awaitingBootInstances.has(instance) &&
1104 (yield* instance.snapshot.isAwaitingFirstCheck ?? Effect.succeed(false))
1105 ) {
1106 return yield* refreshCompatibility;
1107 }
1108 yield* correlateSnapshotWithSource(source, provider).pipe(
1109 Effect.flatMap(syncProvider),
1110 );
1111 }).pipe(Effect.ignoreCause({ log: true })),
1112 { concurrency: "unbounded", discard: true },
1113 );
1114 // A rename keeps the instance live, so its new label only arrives from a fresh read.
1115 const published = new Map(
1116 (yield* Ref.get(providersRef)).map((provider) => [provider.instanceId, provider]),
1117 );
1118 yield* Effect.forEach(
1119 carriedOver.values(),
1120 (instance) =>
1121 Effect.gen(function* () {
1122 // Its first check publishes the new label anyway; the placeholder must not replace the cache.
1123 if (yield* instance.snapshot.isAwaitingFirstCheck ?? Effect.succeed(false)) return;
1124 const provider = yield* instance.snapshot.getSnapshot;
1125 const previous = published.get(instance.instanceId);
1126 if (
1127 previous?.displayName !== provider.displayName ||
1128 previous?.accentColor !== provider.accentColor
1129 ) {
1130 yield* syncProvider(provider);
1131 }
1132 }).pipe(Effect.ignoreCause({ log: true })),
1133 { concurrency: "unbounded", discard: true },
1134 );
1135 yield* upsertProviders(unavailableProviders, {
1136 persist: false,
1137 replace: true,
1138 });
1139
1140 const nextSubs = new Map(carriedOver);
1141 for (const [instanceId, instance] of newlyAdded) {
1142 nextSubs.set(instanceId, instance);
1143 }
1144 yield* Ref.set(liveSubsRef, nextSubs);
1145
1146 const [previousProviders, providers] = yield* Ref.modify(
1147 providersRef,
1148 (previousProviders) => {
1149 const providers = orderProviderSnapshots(
1150 previousProviders.filter((provider) =>
1151 knownInstanceIds.has(snapshotInstanceKey(provider)),
1152 ),
1153 );
1154 return [[previousProviders, providers] as const, providers];
1155 },
1156 );
1157 if (haveProvidersChanged(previousProviders, providers)) {
1158 yield* PubSub.publish(changesPubSub, providers);
1159 }
1160 yield* Ref.update(maintenanceActionStatesRef, (previous) => {
1161 const next = new Map(previous);
1162 for (const instanceId of previous.keys()) {
1163 if (!knownInstanceIds.has(instanceId)) {
1164 next.delete(instanceId);
1165 }
1166 }
1167 return next;
1168 });
1169 }),
1170 );
1171 const syncLiveSourcesAndContinue = syncLiveSources.pipe(
1172 Effect.catchCause((cause) => {
1173 if (Cause.hasInterruptsOnly(cause)) {
1174 return Effect.interrupt;
1175 }
1176 return Effect.logError(
1177 "provider registry instance sync failed; keeping subscription alive",
1178 {
1179 cause: Cause.pretty(cause),
1180 },
1181 );
1182 }),
1183 Scope.provide(serviceScope),
1184 );
1185
1186 yield* upsertProviders(
1187 fallbackProviders.filter((_, index) => !awaitingBootInstances.has(bootInstances[index]!)),
1188 { publish: false },
1189 );
1190 const instanceChanges = yield* instanceRegistry.subscribeChanges;
1191 yield* syncLiveSources;
1192 yield* Stream.runForEach(
1193 Stream.fromSubscription(instanceChanges),
1194 () => syncLiveSourcesAndContinue,
1195 ).pipe(Effect.forkScoped);
1196
1197 const recoverRefreshFailure = Effect.fn("recoverRefreshFailure")(function* (
1198 cause: Cause.Cause<unknown>,
1199 ) {
1200 if (Cause.hasInterruptsOnly(cause)) {
1201 return yield* Effect.interrupt;
1202 }
1203 yield* Effect.logError("provider registry refresh failed; preserving cached providers", {
1204 cause: Cause.pretty(cause),
1205 });
1206 return yield* Ref.get(providersRef);
1207 });
1208
1209 const updateProviders = (
1210 update: (providers: ReadonlyArray<ServerProvider>) => ReadonlyArray<ServerProvider>,
1211 ) =>
1212 Ref.modify(providersRef, (currentProviders) => {
1213 const nextProviders = update(currentProviders);
1214 return [[currentProviders, nextProviders] as const, nextProviders];
1215 }).pipe(
1216 Effect.tap(([previousProviders, nextProviders]) =>
1217 haveProvidersChanged(previousProviders, nextProviders)
1218 ? PubSub.publish(changesPubSub, nextProviders)
1219 : Effect.void,
1220 ),
1221 Effect.map(([, nextProviders]) => nextProviders),
1222 );
1223
1224 const refreshWorkspaceSnapshot = Effect.fn("refreshWorkspaceSnapshot")(function* (input: {
1225 readonly instanceId: ProviderInstanceId;
1226 readonly cwd: string;
1227 readonly scanCwd?: string;
1228 readonly fresh?: boolean;
1229 // Set by an instance's own report that its workspace skills changed.
1230 readonly rescan?: ProviderInstance;
1231 }) {
1232 const workspaceSnapshotOf = (candidate: ServerProvider | undefined) =>
1233 candidate?.workspaceSnapshots?.find((s) => s.cwd === input.cwd);
1234 // What clients saw before the awaited scan, which may already have published the change.
1235 const heldBeforeWait = input.rescan
1236 ? workspaceSnapshotOf(
1237 (yield* Ref.get(providersRef)).find(
1238 (candidate) => candidate.instanceId === input.instanceId,
1239 ),
1240 )
1241 : undefined;
1242 // A rescan waits for a running scan, which may have read files before the hook linked them.
1243 // Claims are read before snapshots: a scan publishes before it releases its claim.
1244 const runningScan = input.rescan
1245 ? (yield* Ref.get(workspaceRefreshesRef)).get(input.rescan)?.get(input.cwd)
1246 : undefined;
1247 if (runningScan) yield* Deferred.await(runningScan);
1248 if (input.fresh) {
1249 yield* updateProviders((providers) =>
1250 providers.map((candidate) =>
1251 candidate.instanceId === input.instanceId
1252 ? candidate
1253 : dropProviderWorkspaceSnapshot(candidate, input.cwd),
1254 ),
1255 );
1256 }
1257 const providers = yield* Ref.get(providersRef);
1258 const provider = providers.find((candidate) => candidate.instanceId === input.instanceId);
1259 const scannedFrom = workspaceSnapshotOf(provider);
1260 const now = yield* DateTime.now;
1261 if (
1262 !provider ||
1263 !provider.enabled ||
1264 (!input.fresh &&
1265 !input.rescan &&
1266 scannedFrom &&
1267 !isProviderWorkspaceSnapshotPending(scannedFrom) &&
1268 isProviderWorkspaceSnapshotCurrent(scannedFrom, DateTime.toEpochMillis(now)))
1269 ) {
1270 return providers;
1271 }
1272 // Use scan start for TTL, not checkedAt inherited from the machine health check.
1273 const scannedAt = DateTime.formatIso(now);
1274 const instance = yield* instanceRegistry.getInstance(input.instanceId);
1275 const snapshotForCwd = instance?.snapshotForCwd;
1276 if (!instance || !snapshotForCwd) return providers;
1277 // A report never enrolls a cwd nobody requested, nor outlives the instance that made it.
1278 if (input.rescan && (input.rescan !== instance || (!runningScan && !scannedFrom))) {
1279 return providers;
1280 }
1281 const token = yield* Deferred.make<void>();
1282 // A machine refresh can change this cwd's snapshot, so the scan publishes against the result.
1283 const refreshMachineSnapshot = input.fresh
1284 ? (instance.invalidateCaches ?? Effect.void).pipe(
1285 Effect.andThen(refreshInstance(input.instanceId)),
1286 Effect.andThen(Ref.get(providersRef)),
1287 Effect.map((current) =>
1288 workspaceSnapshotOf(
1289 current.find((candidate) => candidate.instanceId === input.instanceId),
1290 ),
1291 ),
1292 )
1293 : Effect.succeed(scannedFrom);
1294 const runScan = refreshMachineSnapshot.pipe(
1295 Effect.flatMap((scanBase) =>
1296 Effect.map(snapshotForCwd(input.scanCwd ?? input.cwd), (scopedSnapshot) => ({
1297 scanBase,
1298 scopedSnapshot,
1299 })),
1300 ),
1301 // Scans fail on error; returned inventory remains valid even when provider health reports an error.
1302 Effect.flatMap(({ scanBase, scopedSnapshot }) =>
1303 instanceRegistry.getInstance(input.instanceId).pipe(
1304 Effect.flatMap((currentInstance) => {
1305 if (currentInstance !== instance) return Ref.get(providersRef);
1306 return updateProviders((currentProviders) => {
1307 // Read ownership inside the update so a newer claim cannot race publication.
1308 if (Ref.getUnsafe(workspaceRefreshesRef).get(instance)?.get(input.cwd) !== token) {
1309 return currentProviders;
1310 }
1311 return currentProviders.map((candidate) => {
1312 if (
1313 candidate.instanceId !== input.instanceId ||
1314 !Equal.equals(workspaceSnapshotOf(candidate), scanBase)
1315 ) {
1316 return candidate;
1317 }
1318 const scanned = upsertProviderWorkspaceSnapshot(candidate, input.cwd, {
1319 ...scopedSnapshot,
1320 checkedAt: scannedAt,
1321 // Without driver command discovery, retain previous commands after failed health checks and retry.
1322 slashCommandsPending:
1323 scopedSnapshot.slashCommandsPending ?? scopedSnapshot.status === "error",
1324 });
1325 // Clients keep fetched snapshots, so a changed rescan must tell them to fetch again.
1326 const rescanned = workspaceSnapshotOf(scanned);
1327 const held = heldBeforeWait ?? scanBase;
1328 return input.rescan &&
1329 !(
1330 Equal.equals(rescanned?.skills, held?.skills) &&
1331 Equal.equals(rescanned?.models, held?.models) &&
1332 Equal.equals(rescanned?.slashCommands, held?.slashCommands)
1333 )
1334 ? { ...scanned, workspaceRescannedAt: scannedAt }
1335 : scanned;
1336 });
1337 });
1338 }),
1339 ),
1340 ),
1341 Effect.ensuring(
1342 Ref.update(workspaceRefreshesRef, (refreshes) => {
1343 const current = refreshes.get(instance);
1344 if (current?.get(input.cwd) !== token) return refreshes;
1345 const next = new Map(refreshes);
1346 const nextCwds = new Map(current);
1347 nextCwds.delete(input.cwd);
1348 if (nextCwds.size) next.set(instance, nextCwds);
1349 else next.delete(instance);
1350 return next;
1351 }).pipe(Effect.andThen(Deferred.succeed(token, undefined))),
1352 ),
1353 );
1354 // The claim and the fork happen together, so the token is always completed. The scan is
1355 // detached so a disconnecting owner cannot cancel the result its waiters depend on.
1356 const claim = yield* Effect.uninterruptible(
1357 Effect.gen(function* () {
1358 const inFlight = yield* Ref.modify(workspaceRefreshesRef, (refreshes) => {
1359 const current = refreshes.get(instance);
1360 const running = current?.get(input.cwd);
1361 if (!input.fresh && running) return [running, refreshes] as const;
1362 const next = new Map(refreshes);
1363 next.set(instance, new Map(current).set(input.cwd, token));
1364 return [undefined, next] as const;
1365 });
1366 if (inFlight) return { inFlight } as const;
1367 return {
1368 // Starting now attaches the scan's `ensuring` before anything can close the scope.
1369 scan: yield* Effect.forkIn(runScan, serviceScope, { startImmediately: true }),
1370 } as const;
1371 }),
1372 );
1373 // Wait for the running scan: on-demand clients get its result only in this reply.
1374 if ("inFlight" in claim) {
1375 return yield* Deferred.await(claim.inFlight).pipe(Effect.andThen(Ref.get(providersRef)));
1376 }
1377 return yield* Fiber.join(claim.scan);
1378 });
1379 yield* Stream.runForEach(Stream.fromQueue(workspaceRescans), ({ instance, cwd }) =>
1380 refreshWorkspaceSnapshot({ instanceId: instance.instanceId, cwd, rescan: instance }).pipe(
1381 Effect.ignoreCause({ log: true }),
1382 ),
1383 ).pipe(Effect.forkScoped);
1384
1385 const runtimeModeLimits = Effect.fn("ProviderRegistry.runtimeModeLimits")(function* (input: {
1386 readonly instanceId: ProviderInstanceId;
1387 readonly scanCwd: string;
1388 }) {
1389 const instance = yield* instanceRegistry.getInstance(input.instanceId);
1390 return instance?.runtimeModeLimitsForCwd === undefined
1391 ? []
1392 : yield* instance.runtimeModeLimitsForCwd(input.scanCwd);
1393 });
1394
1395 const invalidateModelCaches = Effect.fn("ProviderRegistry.invalidateModelCaches")(function* (
1396 input: Parameters<ProviderRegistry["Service"]["invalidateModelCaches"]>[0],
1397 ) {
1398 yield* manifestService.forceRefresh;
1399 const instances = yield* instanceRegistry.listInstances;
1400 yield* Effect.forEach(
1401 instances.filter(
1402 (instance) => input.instanceId === undefined || input.instanceId === instance.instanceId,
1403 ),
1404 (instance) =>
1405 Effect.gen(function* () {
1406 yield* instance.invalidateCaches ?? Effect.void;
1407 // Instance and full refreshes resolve installer metadata fresh
1408 // themselves; a cached workspace refresh needs it resolved here.
1409 const maintenance = yield* instance.snapshot.resolveMaintenance({
1410 fresh:
1411 input.instanceId !== undefined && input.cwd !== undefined && input.fresh !== true,
1412 });
1413 yield* Effect.forEach(
1414 latestProviderVersionCacheKeys(maintenance),
1415 latestVersions.invalidate,
1416 { discard: true },
1417 );
1418 }),
1419 { concurrency: "unbounded", discard: true },
1420 );
1421 });
1422
1423 const refreshModelCatalog = Effect.fn("ProviderRegistry.refreshModelCatalog")(function* () {
1424 const { updatedAt } = yield* manifestService.refreshOnDemand;
1425 // The first pass can be one that started before the fetch, so allow one more.
1426 for (let pass = 0; pass < 2; pass++) {
1427 if ((yield* Ref.get(probedManifestUpdatedAt)) === updatedAt) return;
1428 // A new model usually ships with the CLI release that supports it.
1429 yield* latestVersions.invalidateAll;
1430 yield* refreshAll();
1431 }
1432 });
1433
1434 return {
1435 getProviders: Ref.get(providersRef),
1436 refresh: (provider?: ProviderDriverKind) =>
1437 refresh(provider).pipe(Effect.catchCause(recoverRefreshFailure)),
1438 refreshInstance: (instanceId: ProviderInstanceId) =>
1439 refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)),
1440 reloadSecretsAndRefresh: (instanceId?: ProviderInstanceId) =>
1441 reloadSecretsAndRefresh(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)),
1442 rebuildMissingAndRefresh: rebuildMissingAndRefresh().pipe(
1443 Effect.catchCause(recoverRefreshFailure),
1444 ),
1445 applySecretAndRefresh: (reference: SecretReference, value: string) =>
1446 applySecretAndRefresh(reference, value).pipe(Effect.catchCause(recoverRefreshFailure)),
1447 refreshWorkspaceSnapshot: (input) =>
1448 refreshWorkspaceSnapshot(input).pipe(Effect.catchCause(recoverRefreshFailure)),
1449 refreshAfterUpdate,
1450 runtimeModeLimits,
1451 invalidateModelCaches,
1452 refreshModelCatalog: refreshModelCatalog().pipe(
1453 Effect.catchCause(recoverRefreshFailure),
1454 Effect.asVoid,
1455 ),
1456 getProviderMaintenanceCapabilitiesForInstance,
1457 setProviderMaintenanceActionState,
1458 get streamChanges() {
1459 return Stream.fromPubSub(changesPubSub);
1460 },
1461 } satisfies ProviderRegistry["Service"];
1462 }),
1463);