Open History to see the last commit
1import {
2 officialAcpRegistryIconUrlForAgentId,
3 ProviderDriverKind,
4 resolveOfficialAcpRegistryIconUrl,
5 type AcpRegistryOperationError,
6 type AcpRegistryProbeModel,
7 type CustomModelSetting,
8 type ServerProvider,
9 type ServerProviderModel,
10} from "@t3tools/contracts";
11import { AcpRegistrySettings } from "../settings.ts";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13import { createModelCapabilities } from "@t3tools/shared/model";
14import * as Clock from "effect/Clock";
15import * as Digest from "effect/crypto/Digest";
16import * as SecureRandom from "effect/crypto/SecureRandom";
17import * as DateTime from "effect/DateTime";
18import * as Effect from "effect/Effect";
19import * as Equal from "effect/Equal";
20import * as FileSystem from "effect/FileSystem";
21import * as Option from "effect/Option";
22import * as Path from "effect/Path";
23import * as Ref from "effect/Ref";
24import * as Result from "effect/Result";
25import * as Schema from "effect/Schema";
26import * as Semaphore from "effect/Semaphore";
27import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
28
29import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
30import { AcpRegistryAdapterV2Driver, type AcpRegistryAdapterV2DriverEnv } from "./adapter.ts";
31import { makeAcpRegistryTextGeneration } from "./textGeneration.ts";
32import { ProviderDriverError } from "@t3tools/provider-core/server/errors";
33import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
34import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
35import {
36 defaultProviderContinuationIdentity,
37 type ProviderDriver,
38 type ProviderInstance,
39} from "@t3tools/provider-core/server/driver";
40import {
41 providerModelsFromSettings,
42 providerProbeEnvironment,
43} from "@t3tools/provider-core/server/snapshotProbe";
44import { makeManualOnlyProviderMaintenanceCapabilities } from "@t3tools/provider-core/server/maintenanceResolver";
45import {
46 haveProviderSnapshotSettingsChanged,
47 makeProviderSnapshotSettingsSource,
48 type ProviderSnapshotSettings,
49} from "@t3tools/provider-core/server/snapshotSettings";
50import {
51 type AcpRegistryAvailableCommands,
52 type AcpRegistryConfigurationProbe,
53 type AcpRegistryConfigurationProbeResult,
54 type AcpRegistryLiveConfiguration,
55 type AcpRegistryModelDiscovery,
56 deleteAcpRegistrySession,
57 disableAcpRegistryProvider,
58 listAcpRegistrySessions,
59 listAcpRegistryProviders,
60 logoutAcpRegistry,
61 probeAcpRegistryConfiguration,
62 setAcpRegistryProvider,
63} from "./probe.ts";
64import * as AcpRegistrySupport from "./AcpRegistrySupport.ts";
65import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts";
66import * as AcpRegistryAuth from "./auth.ts";
67import * as AcpRegistryAuthenticationState from "./authenticationState.ts";
68import {
69 acpRegistryCurrentModelOptions,
70 acpRegistryModelsToDiscover,
71 makeAcpRegistryLearnedModelOptionsStore,
72 withAcpRegistryLearnedModelOptions,
73} from "./learnedModelOptions.ts";
74
75const DRIVER_KIND = ProviderDriverKind.make("acpRegistry");
76const decodeSettings = Schema.decodeSync(AcpRegistrySettings);
77// Cache only successful authenticated probes so sign-in changes remain visible.
78const PROBE_SUCCESS_TTL_MS = 15 * 60 * 1_000;
79const PROBE_PROVISIONAL_TTL_MS = 30 * 1_000;
80const REGISTRY_REFRESH_FAILURE_BACKOFF_MS = 60 * 1_000;
81
82function acpRegistryProbeTtlMs(provider: ServerProvider): number {
83 const discoveredModels = provider.models.filter((model) => !model.isCustom);
84 return discoveredModels.length <= 1 ? PROBE_PROVISIONAL_TTL_MS : PROBE_SUCCESS_TTL_MS;
85}
86
87interface AcpRegistryEnrichmentCache {
88 readonly generation: number;
89 readonly entry: {
90 readonly provider: ServerProvider;
91 readonly launchIdentity?: string;
92 readonly expiresAt: number;
93 } | null;
94}
95
96export function isAcpRegistryCacheValid(
97 entry: NonNullable<AcpRegistryEnrichmentCache["entry"]>,
98 inspectedVersion: string | null,
99 local: boolean,
100 now: number,
101 inspectedLaunchIdentity?: string,
102): boolean {
103 return (
104 entry.expiresAt > now &&
105 ((local && inspectedVersion === null) || entry.provider.version === inspectedVersion) &&
106 (inspectedLaunchIdentity === undefined || entry.launchIdentity === inspectedLaunchIdentity)
107 );
108}
109
110export function updateAcpRegistryEnrichmentCache(input: {
111 readonly cache: AcpRegistryEnrichmentCache;
112 readonly configuration: AcpRegistryLiveConfiguration;
113 readonly customModels: ReadonlyArray<CustomModelSetting>;
114 readonly now: number;
115}): AcpRegistryEnrichmentCache {
116 const { cache, configuration, customModels, now } = input;
117 if (cache.entry === null) {
118 // Only a live catalog update advances the epoch; options-only updates must not discard an in-flight probe.
119 return configuration.models.length > 0 ? { ...cache, generation: cache.generation + 1 } : cache;
120 }
121 const provider = applyAcpRegistryLiveConfiguration(
122 cache.entry.provider,
123 configuration,
124 customModels,
125 );
126 if (Equal.equals(provider, cache.entry.provider)) return cache;
127 const catalogChanged = !Equal.equals(
128 cache.entry.provider.models.filter((model) => !model.isCustom).map((model) => model.slug),
129 provider.models.filter((model) => !model.isCustom).map((model) => model.slug),
130 );
131 return {
132 ...cache,
133 // Advance the epoch and renew TTL only when the live session actually changed the model catalog.
134 generation: catalogChanged ? cache.generation + 1 : cache.generation,
135 entry: {
136 ...cache.entry,
137 provider,
138 expiresAt: catalogChanged ? now + acpRegistryProbeTtlMs(provider) : cache.entry.expiresAt,
139 },
140 };
141}
142const EMPTY_CAPABILITIES = createModelCapabilities({ optionDescriptors: [] });
143const MAINTENANCE = makeManualOnlyProviderMaintenanceCapabilities({
144 provider: DRIVER_KIND,
145 packageName: null,
146});
147
148function modelsFromDiscovery(
149 discovery:
150 | Pick<
151 AcpRegistryLiveConfiguration,
152 "models" | "currentModelId" | "configOptions" | "modelOptionIds"
153 >
154 | undefined,
155 customModels: ReadonlyArray<CustomModelSetting>,
156 previousModels: ReadonlyArray<ServerProviderModel> = [],
157): ReadonlyArray<ServerProviderModel> {
158 const discovered = discovery?.models ?? [];
159 const capabilities =
160 discovery === undefined || discovery.configOptions.length === 0
161 ? EMPTY_CAPABILITIES
162 : createModelCapabilities({ optionDescriptors: discovery.configOptions });
163 // Model-specific options describe only the session's current model; other
164 // models keep the shared ones plus what an earlier session reported for them.
165 const modelOptionIds = new Set(discovery?.modelOptionIds ?? []);
166 const shared = (discovery?.configOptions ?? []).filter(
167 (descriptor) => !modelOptionIds.has(descriptor.id),
168 );
169 const sharedIds = new Set(shared.map((descriptor) => descriptor.id));
170 const capabilitiesFor = ({ id: slug, reasoningEffort }: AcpRegistryProbeModel) => {
171 if (slug === discovery?.currentModelId) return capabilities;
172 // The levels a model advertises replace the ones an earlier session reported.
173 const own = (
174 previousModels.find((model) => model.slug === slug)?.capabilities?.optionDescriptors ?? []
175 ).filter(
176 (descriptor) =>
177 !sharedIds.has(descriptor.id) &&
178 (reasoningEffort === undefined ||
179 descriptor.type !== "select" ||
180 descriptor.role !== "reasoning"),
181 );
182 const optionDescriptors = [...shared, ...own, ...(reasoningEffort ? [reasoningEffort] : [])];
183 return optionDescriptors.length === 0
184 ? EMPTY_CAPABILITIES
185 : createModelCapabilities({ optionDescriptors });
186 };
187 const builtInModels: ReadonlyArray<ServerProviderModel> =
188 discovered.length === 0
189 ? [
190 {
191 slug: "default",
192 name: "Default",
193 isCustom: false,
194 isDefault: true,
195 capabilities,
196 },
197 ]
198 : discovered.map((model) => ({
199 slug: model.id,
200 name: model.name,
201 isCustom: false,
202 ...(model.id === discovery?.currentModelId ? { isDefault: true } : {}),
203 capabilities: capabilitiesFor(model),
204 }));
205 return providerModelsFromSettings(builtInModels, customModels, capabilities);
206}
207
208function acpRegistrySnapshotReadiness(
209 inspection:
210 | AcpRegistrySupport.AcpRegistryInspection
211 | { readonly status: "failed"; readonly message: string },
212): Pick<ServerProvider, "installed" | "version" | "status" | "message"> {
213 switch (inspection.status) {
214 case "ready":
215 return { installed: true, version: inspection.version, status: "ready" };
216 case "unconfigured":
217 return {
218 installed: false,
219 version: null,
220 status: "warning",
221 message:
222 "Select an ACP Registry agent or configure a local ACP executable before starting a thread.",
223 };
224 case "not_found":
225 return {
226 installed: false,
227 version: null,
228 status: "error",
229 message: `ACP Registry does not contain agent '${inspection.agentId}'.`,
230 };
231 case "unsupported":
232 return {
233 installed: false,
234 version: inspection.version,
235 status: "error",
236 message: `ACP Registry agent '${inspection.agentId}' has no compatible distribution for this environment.`,
237 };
238 case "missing_runner":
239 return {
240 installed: false,
241 version: inspection.version,
242 status: "error",
243 message:
244 inspection.distribution === "local"
245 ? "Local ACP executable is not available on this environment's PATH."
246 : `ACP executable '${inspection.runner}' is not available on this environment's PATH.`,
247 };
248 case "unprepared":
249 return {
250 installed: false,
251 version: inspection.version,
252 status: "warning",
253 message: `ACP Registry agent '${inspection.agentId}' has not been prepared on this environment.`,
254 };
255 case "failed":
256 return {
257 installed: false,
258 version: null,
259 status: "error",
260 message: inspection.message,
261 };
262 }
263}
264
265interface SnapshotIdentity {
266 readonly instanceId: ProviderInstance["instanceId"];
267 readonly displayName: string | undefined;
268 readonly accentColor: string | undefined;
269 readonly continuationKey: string;
270}
271
272function baseSnapshot(
273 input: SnapshotIdentity & {
274 readonly settings: AcpRegistrySettings;
275 readonly checkedAt: string;
276 readonly installed: boolean;
277 readonly version: string | null;
278 readonly status: ServerProvider["status"];
279 readonly auth: ServerProvider["auth"];
280 readonly documentationUrl?: string;
281 readonly message?: string;
282 readonly probe?: AcpRegistryConfigurationProbeResult;
283 readonly probeError?: AcpRegistryOperationError;
284 },
285): ServerProvider {
286 const iconUrl =
287 input.settings.source === "local"
288 ? null
289 : (resolveOfficialAcpRegistryIconUrl(input.probe?.probe.icon) ??
290 officialAcpRegistryIconUrlForAgentId(input.settings.agentId));
291 return {
292 instanceId: input.instanceId,
293 driver: DRIVER_KIND,
294 ...(input.displayName ? { displayName: input.displayName } : {}),
295 ...(input.accentColor ? { accentColor: input.accentColor } : {}),
296 ...(iconUrl ? { iconUrl } : {}),
297 continuation: { groupKey: input.continuationKey },
298 enabled: input.settings.enabled,
299 installed: input.installed,
300 version: input.version,
301 status: input.settings.enabled ? input.status : "disabled",
302 auth: { ...input.auth, canLogout: input.auth.canLogout ?? false },
303 checkedAt: input.checkedAt,
304 setup: {
305 canInstall: false,
306 ...(input.documentationUrl ? { documentationUrl: input.documentationUrl } : {}),
307 canAuthenticate:
308 input.installed &&
309 (input.probe
310 ? input.probe.probe.authMethods.length > 0
311 : input.settings.source === "local"
312 ? (input.probeError?.authMethods?.length ?? 0) > 0
313 : input.settings.agentId.length > 0),
314 },
315 ...(input.message ? { message: input.message } : {}),
316 models: modelsFromDiscovery(input.probe?.probe, input.settings.customModels),
317 ...(input.probe === undefined
318 ? {}
319 : {
320 nativeSessions: {
321 canList: input.probe.probe.sessionManagement.canList,
322 canLoad: input.probe.probe.sessionManagement.canLoad,
323 canResume: input.probe.probe.sessionManagement.canResume,
324 canDelete: input.probe.probe.sessionManagement.canDelete,
325 },
326 configurableProviders: input.probe.probe.sessionManagement.canConfigureProviders,
327 }),
328 slashCommands: input.probe?.slashCommands ?? [],
329 skills: input.probe?.skills ?? [],
330 };
331}
332
333export function applyAcpRegistryAvailableCommands(
334 provider: ServerProvider,
335 commands: Option.Option<AcpRegistryAvailableCommands>,
336): ServerProvider {
337 return Option.match(commands, {
338 onNone: () => provider,
339 onSome: ({ slashCommands, skills }) => ({ ...provider, slashCommands, skills }),
340 });
341}
342
343export function applyAcpRegistryLiveConfiguration(
344 provider: ServerProvider,
345 configuration: AcpRegistryLiveConfiguration,
346 customModels: ReadonlyArray<CustomModelSetting>,
347 previousModels: ReadonlyArray<ServerProviderModel> = provider.models,
348): ServerProvider {
349 const { message: _staleProbeMessage, ...snapshot } = provider;
350 // session/load may omit models (Kimi returns `{}`); keep the probed list
351 // and apply any live option descriptors to it.
352 const probedModels = provider.models.filter((model) => !model.isCustom);
353 // A cold-start session can report one placeholder model before its catalog
354 // settles, while the probe may already have observed the full catalog. A
355 // single model enumerated by an explicit select is not that fallback but
356 // the agent's deliberate statement, so it wins over the probe catalog.
357 const liveCatalogIsProvisional =
358 configuration.models.length === 1 &&
359 !configuration.modelsFromModelSelect &&
360 probedModels.length > 1;
361 const useLiveCatalog =
362 configuration.models.length > 1 ||
363 (configuration.models.length === 1 && !liveCatalogIsProvisional);
364 const selectedProbedModelId =
365 configuration.currentModelId !== null &&
366 probedModels.some((model) => model.slug === configuration.currentModelId)
367 ? configuration.currentModelId
368 : (probedModels.find((model) => model.isDefault)?.slug ?? null);
369 const discovery = useLiveCatalog
370 ? configuration
371 : {
372 ...configuration,
373 models: probedModels.map((model) => ({
374 id: model.slug,
375 name: model.name,
376 description: null,
377 })),
378 currentModelId: selectedProbedModelId,
379 };
380 return {
381 ...snapshot,
382 status: provider.enabled ? "ready" : provider.status,
383 models:
384 !useLiveCatalog && configuration.configOptions.length === 0
385 ? withAcpRegistryDefaultModel(provider.models, selectedProbedModelId)
386 : modelsFromDiscovery(
387 discovery,
388 customModels,
389 previousModels.filter((model) => !model.isCustom),
390 ),
391 };
392}
393
394function withAcpRegistryDefaultModel(
395 models: ReadonlyArray<ServerProviderModel>,
396 currentModelId: string | null,
397): ReadonlyArray<ServerProviderModel> {
398 if (currentModelId === null) return models;
399 let changed = false;
400 const next = models.map((model) => {
401 if (model.isCustom) return model;
402 const isDefault = model.slug === currentModelId;
403 if ((model.isDefault ?? false) === isDefault) return model;
404 changed = true;
405 const { isDefault: _previous, ...rest } = model;
406 return isDefault ? { ...rest, isDefault: true } : rest;
407 });
408 return changed ? next : models;
409}
410
411function applyAcpRegistryUrlAuthAction(
412 provider: ServerProvider,
413 action: Option.Option<NonNullable<ServerProvider["auth"]["action"]>>,
414): ServerProvider {
415 const { action: _previousAction, ...auth } = provider.auth;
416 return {
417 ...provider,
418 auth: Option.match(action, {
419 onNone: () => auth,
420 onSome: (nextAction) => ({ ...auth, action: nextAction }),
421 }),
422 };
423}
424
425const buildInitialAcpRegistrySnapshot = Effect.fn("AcpRegistryDriver.buildInitialSnapshot")(
426 function* (input: SnapshotIdentity & { readonly settings: AcpRegistrySettings }) {
427 const checkedAt = DateTime.formatIso(yield* DateTime.now);
428 return baseSnapshot({
429 ...input,
430 checkedAt,
431 installed: false,
432 version: null,
433 status: "warning",
434 auth: { status: "unknown" },
435 message: input.settings.enabled
436 ? "Checking ACP Registry agent readiness..."
437 : "ACP Registry is disabled in T3 Code settings.",
438 });
439 },
440);
441
442export function buildCheckedAcpRegistrySnapshot(
443 input: SnapshotIdentity & {
444 readonly settings: AcpRegistrySettings;
445 readonly checkedAt: string;
446 readonly inspection:
447 | AcpRegistrySupport.AcpRegistryInspection
448 | { readonly status: "failed"; readonly message: string };
449 readonly probe?: AcpRegistryConfigurationProbeResult;
450 readonly probeError?: AcpRegistryOperationError;
451 },
452): ServerProvider {
453 const readiness = acpRegistrySnapshotReadiness(input.inspection);
454 const probeFailed = input.probeError !== undefined;
455 const advertisedAuthMethod =
456 input.probeError?.reason === "authentication_failed"
457 ? (input.probeError.authMethods?.find(
458 (method) => method.id === input.settings.authMethodId,
459 ) ?? input.probeError.authMethods?.[0])
460 : undefined;
461 const authenticationMessage = advertisedAuthMethod
462 ? advertisedAuthMethod.type === "terminal" && advertisedAuthMethod.command
463 ? `Sign in in provider settings using "${advertisedAuthMethod.name}". The login terminal runs on this environment.`
464 : advertisedAuthMethod.type === "env_var" &&
465 (advertisedAuthMethod.envVarNames?.length ?? 0) > 0
466 ? `Set ${advertisedAuthMethod.envVarNames!.join(", ")} under this instance's environment variables in provider settings. T3 Code will detect it on the next provider refresh.`
467 : `Sign in in provider settings using "${advertisedAuthMethod.name}".`
468 : undefined;
469 return baseSnapshot({
470 ...input,
471 ...(input.inspection.status === "ready" && input.inspection.documentationUrl
472 ? { documentationUrl: input.inspection.documentationUrl }
473 : {}),
474 installed: readiness.installed,
475 version:
476 input.settings.source === "local"
477 ? (input.probe?.probe.agentVersion ?? readiness.version)
478 : readiness.version,
479 // Failed discovery is a warning: an installed agent may still run real turns.
480 status: probeFailed ? "warning" : readiness.status,
481 auth: input.probe
482 ? {
483 // Discovery sessions and an empty auth-method list do not prove sign-in.
484 status: "unknown",
485 canLogout: input.probe.probe.sessionManagement.canLogout,
486 }
487 : input.probeError?.reason === "authentication_failed"
488 ? {
489 status: "unauthenticated",
490 ...(advertisedAuthMethod
491 ? { type: advertisedAuthMethod.type, label: advertisedAuthMethod.name }
492 : {}),
493 ...(input.probeError.authAction === undefined
494 ? {}
495 : { action: input.probeError.authAction }),
496 }
497 : { status: "unknown" },
498 ...(input.probeError
499 ? { message: authenticationMessage ?? input.probeError.message }
500 : readiness.message
501 ? { message: readiness.message }
502 : {}),
503 });
504}
505
506export const checkAcpRegistryProviderStatus = Effect.fn("AcpRegistryDriver.checkProviderStatus")(
507 function* <Requirements>(
508 input: SnapshotIdentity & {
509 readonly settings: AcpRegistrySettings;
510 readonly cwd: string;
511 readonly environment: NodeJS.ProcessEnv;
512 readonly modelDiscovery?: Omit<AcpRegistryModelDiscovery, "onProbed"> & {
513 readonly onProbed: (provider: ServerProvider) => Effect.Effect<ReadonlyArray<string>>;
514 };
515 },
516 probeConfiguration: AcpRegistryConfigurationProbe<Requirements>,
517 ): Effect.fn.Return<ServerProvider, never, AcpRegistrySupport.AcpRegistryCatalog | Requirements> {
518 const checkedAt = DateTime.formatIso(yield* DateTime.now);
519 if (!input.settings.enabled) {
520 return yield* buildInitialAcpRegistrySnapshot(input);
521 }
522 const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog;
523 const inspected = yield* Effect.result(catalog.inspect(input.settings, input.environment));
524 if (Result.isFailure(inspected)) {
525 return buildCheckedAcpRegistrySnapshot({
526 ...input,
527 checkedAt,
528 inspection: {
529 status: "failed",
530 message: `Could not inspect ACP Registry agent: ${inspected.failure.message}`,
531 },
532 });
533 }
534 if (inspected.success.status !== "ready") {
535 return buildCheckedAcpRegistrySnapshot({
536 ...input,
537 checkedAt,
538 inspection: inspected.success,
539 });
540 }
541 const inspection = inspected.success;
542 const modelDiscovery = input.modelDiscovery;
543 const probed = yield* Effect.result(
544 probeConfiguration({
545 instanceId: input.instanceId,
546 settings: input.settings,
547 cwd: input.cwd,
548 environment: providerProbeEnvironment(input.environment),
549 ...(modelDiscovery === undefined
550 ? {}
551 : {
552 modelDiscovery: {
553 onProbed: (probe) =>
554 modelDiscovery.onProbed(
555 buildCheckedAcpRegistrySnapshot({ ...input, checkedAt, inspection, probe }),
556 ),
557 onDiscovered: modelDiscovery.onDiscovered,
558 },
559 }),
560 }),
561 );
562 return Result.isFailure(probed)
563 ? buildCheckedAcpRegistrySnapshot({
564 ...input,
565 checkedAt,
566 inspection: inspected.success,
567 probeError: probed.failure,
568 })
569 : buildCheckedAcpRegistrySnapshot({
570 ...input,
571 checkedAt,
572 inspection: inspected.success,
573 probe: probed.success,
574 });
575 },
576);
577
578export const checkAcpRegistryProviderReadiness = Effect.fn(
579 "AcpRegistryDriver.checkProviderReadiness",
580)(function* (
581 input: SnapshotIdentity & {
582 readonly settings: AcpRegistrySettings;
583 readonly environment: NodeJS.ProcessEnv;
584 },
585): Effect.fn.Return<ServerProvider, never, AcpRegistrySupport.AcpRegistryCatalog> {
586 const checkedAt = DateTime.formatIso(yield* DateTime.now);
587 if (!input.settings.enabled) {
588 return yield* buildInitialAcpRegistrySnapshot(input);
589 }
590 const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog;
591 const inspected = yield* Effect.result(catalog.inspect(input.settings, input.environment));
592 const snapshot = buildCheckedAcpRegistrySnapshot({
593 ...input,
594 checkedAt,
595 inspection: Result.isFailure(inspected)
596 ? {
597 status: "failed",
598 message: `Could not inspect ACP Registry agent: ${inspected.failure.message}`,
599 }
600 : inspected.success,
601 });
602 return inspected._tag === "Success" && inspected.success.status === "ready"
603 ? {
604 ...snapshot,
605 message: "Checking ACP authentication, models, and commands in the background...",
606 }
607 : snapshot;
608});
609
610export type AcpRegistryDriverEnv =
611 | AcpRegistryAdapterV2DriverEnv
612 | Digest.Digest
613 | ProviderHost.ProviderHost;
614
615export const AcpRegistryDriver: ProviderDriver<AcpRegistrySettings, AcpRegistryDriverEnv> = {
616 driverKind: DRIVER_KIND,
617 metadata: {
618 displayName: "ACP Registry",
619 snapshotOmitsDisplayName: true,
620 supportsMultipleInstances: true,
621 hasDefaultInstance: false,
622 },
623 configSchema: AcpRegistrySettings,
624 defaultConfig: () => decodeSettings({}),
625 create: Effect.fn("AcpRegistryDriver.create")(function* ({
626 instanceId,
627 displayName,
628 accentColor,
629 environment,
630 enabled,
631 config,
632 }) {
633 const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog;
634 const runtimeCoordinator = yield* Effect.serviceOption(
635 AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
636 );
637 if (Option.isSome(runtimeCoordinator)) {
638 yield* runtimeCoordinator.value.clearAvailableCommands(instanceId);
639 yield* runtimeCoordinator.value.clearLiveConfiguration(instanceId);
640 yield* Effect.addFinalizer(() =>
641 runtimeCoordinator.value
642 .clearAvailableCommands(instanceId)
643 .pipe(Effect.andThen(runtimeCoordinator.value.clearLiveConfiguration(instanceId))),
644 );
645 }
646 const random = yield* SecureRandom.SecureRandom;
647 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
648 const fileSystem = yield* FileSystem.FileSystem;
649 const path = yield* Path.Path;
650 const hostEnvironment = yield* HostProcess.Environment;
651 const host = yield* ProviderHost.ProviderHost;
652 const continuationIdentity = defaultProviderContinuationIdentity({
653 driverKind: DRIVER_KIND,
654 instanceId,
655 });
656 const identity = {
657 instanceId,
658 displayName,
659 accentColor,
660 continuationKey: continuationIdentity.continuationKey,
661 };
662 const effectiveConfig = { ...config, enabled } satisfies AcpRegistrySettings;
663 const processEnvironment = yield* mergeProviderInstanceEnvironment(
664 environment,
665 hostEnvironment,
666 );
667 const orchestrationAdapter = yield* AcpRegistryAdapterV2Driver.create({
668 instanceId,
669 displayName,
670 accentColor,
671 environment,
672 enabled,
673 config,
674 }).pipe(
675 Effect.mapError(
676 (cause) =>
677 new ProviderDriverError({
678 driver: DRIVER_KIND,
679 instanceId,
680 detail: "Failed to build ACP Registry orchestration adapter.",
681 cause,
682 }),
683 ),
684 );
685 const readinessInput = {
686 ...identity,
687 settings: effectiveConfig,
688 environment: processEnvironment,
689 };
690 const confirmedAuthentication =
691 yield* AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({
692 cacheDir: host.paths.providerStatusCacheDir,
693 instanceId,
694 settings: effectiveConfig,
695 environment,
696 processEnvironment,
697 });
698 // Refreshes rebuild the snapshot from the probe, so per-model options
699 // reported by sessions and probe discovery are kept here and on disk.
700 const learnedModelOptions = yield* makeAcpRegistryLearnedModelOptionsStore({
701 cacheDir: host.paths.providerStatusCacheDir,
702 instanceId,
703 settings: effectiveConfig,
704 });
705 const applyLiveConfiguration = Effect.fn("AcpRegistryDriver.applyLiveConfiguration")(function* (
706 provider: ServerProvider,
707 configuration: AcpRegistryLiveConfiguration,
708 ) {
709 const reported = acpRegistryCurrentModelOptions(configuration);
710 if (reported !== undefined) {
711 yield* learnedModelOptions.learn(reported.modelId, reported.options, "live");
712 }
713 return withAcpRegistryLearnedModelOptions(
714 applyAcpRegistryLiveConfiguration(provider, configuration, effectiveConfig.customModels),
715 yield* learnedModelOptions.get,
716 );
717 });
718 // Tracks the latest live revision already applied so restarting enrichSnapshot skips replaying it.
719 const lastObservedLiveRevision = yield* Ref.make(0);
720 // Retains the last settled catalog so readiness stays populated after a probe clears live state.
721 const lastAcceptedCatalog = yield* Ref.make<ReadonlyArray<ServerProviderModel> | null>(null);
722 const observeLiveRevision = (revision: number) =>
723 Ref.update(lastObservedLiveRevision, (current) => Math.max(current, revision));
724 const isSyntheticDefaultOnly = (models: ReadonlyArray<ServerProviderModel>) => {
725 const builtIn = models.filter((model) => !model.isCustom);
726 return builtIn.length === 0 || (builtIn.length === 1 && builtIn[0]?.slug === "default");
727 };
728 const clearLearnedModels = learnedModelOptions.clear;
729 const withLiveRuntimeState = Effect.fn("AcpRegistryDriver.withLiveRuntimeState")(function* (
730 input: ServerProvider,
731 ) {
732 if (input.auth.status === "unauthenticated") {
733 yield* confirmedAuthentication.set(false);
734 yield* Ref.set(lastAcceptedCatalog, null);
735 }
736 if (input.installed) yield* learnedModelOptions.setVersion(input.version);
737 const provider =
738 input.enabled &&
739 input.installed &&
740 input.auth.status === "unknown" &&
741 (yield* confirmedAuthentication.get)
742 ? { ...input, auth: { ...input.auth, status: "authenticated" as const } }
743 : input;
744 const withAcceptedFallback = Effect.fnUntraced(function* (candidate: ServerProvider) {
745 const learned = yield* learnedModelOptions.get;
746 const accepted = yield* Ref.get(lastAcceptedCatalog);
747 if (
748 accepted !== null &&
749 candidate.enabled &&
750 candidate.installed &&
751 candidate.auth.status !== "unauthenticated" &&
752 isSyntheticDefaultOnly(candidate.models)
753 ) {
754 const custom = candidate.models.filter((model) => model.isCustom);
755 return withAcpRegistryLearnedModelOptions(
756 { ...candidate, models: [...accepted, ...custom] },
757 learned,
758 );
759 }
760 return withAcpRegistryLearnedModelOptions(candidate, learned);
761 });
762 if (Option.isNone(runtimeCoordinator)) {
763 return yield* withAcceptedFallback(provider);
764 }
765 const coordinator = runtimeCoordinator.value;
766 const withCommands = applyAcpRegistryAvailableCommands(
767 provider,
768 yield* coordinator.getAvailableCommands(instanceId),
769 );
770 const liveSnapshot = yield* coordinator.getLiveConfigurationWithRevision(instanceId);
771 yield* observeLiveRevision(liveSnapshot.revision);
772 const base = yield* withAcceptedFallback(withCommands);
773 const withConfiguration = Option.isSome(liveSnapshot.configuration)
774 ? yield* applyLiveConfiguration(base, liveSnapshot.configuration.value)
775 : base;
776 return applyAcpRegistryUrlAuthAction(
777 withConfiguration,
778 yield* coordinator.getUrlAuthAction(instanceId),
779 );
780 });
781 // A local executable's version comes only from probing it, so readiness checks reuse the last report.
782 const reportedLocalVersion = yield* Ref.make<string | null>(null);
783 const checkProvider = checkAcpRegistryProviderReadiness(readinessInput).pipe(
784 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
785 Effect.flatMap((provider) =>
786 Ref.get(reportedLocalVersion).pipe(
787 Effect.map((version) =>
788 provider.installed && provider.version === null && version !== null
789 ? { ...provider, version }
790 : provider,
791 ),
792 ),
793 ),
794 Effect.flatMap(withLiveRuntimeState),
795 );
796 const modelsToDiscover = Effect.fn("AcpRegistryDriver.modelsToDiscover")(function* (
797 provider: ServerProvider,
798 ) {
799 yield* learnedModelOptions.setVersion(provider.version);
800 const settings = yield* host.settings.get.pipe(Effect.option);
801 // Without settings the hidden models are unknown, so nothing is opened.
802 if (Option.isNone(settings)) return [];
803 return acpRegistryModelsToDiscover({
804 provider,
805 settings: settings.value,
806 learned: yield* learnedModelOptions.get,
807 });
808 });
809 const enrichProvider = Effect.fn("AcpRegistryDriver.enrichProvider")(function* (
810 publishProbed: (
811 provider: ServerProvider,
812 modelsFromModelSelect: boolean,
813 ) => Effect.Effect<void>,
814 ) {
815 const modelsFromSelectRef = yield* Ref.make(false);
816 const provider = yield* checkAcpRegistryProviderStatus(
817 {
818 ...readinessInput,
819 cwd: host.paths.cwd,
820 modelDiscovery: {
821 // Publish what the probe found first; discovery only adds options to it.
822 onProbed: (provider) =>
823 modelsToDiscover(provider).pipe(
824 Effect.tap((modelIds) =>
825 modelIds.length === 0
826 ? Effect.void
827 : Ref.get(modelsFromSelectRef).pipe(
828 Effect.flatMap((fromSelect) => publishProbed(provider, fromSelect)),
829 ),
830 ),
831 ),
832 onDiscovered: (configuration) => {
833 const discovered = acpRegistryCurrentModelOptions(configuration);
834 return discovered === undefined
835 ? Effect.void
836 : learnedModelOptions.learn(discovered.modelId, discovered.options, "discovered");
837 },
838 },
839 },
840 (input) =>
841 probeAcpRegistryConfiguration(input).pipe(
842 Effect.tap((result) =>
843 Ref.set(modelsFromSelectRef, result.modelsFromModelSelect === true),
844 ),
845 ),
846 ).pipe(
847 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
848 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
849 Effect.provideService(FileSystem.FileSystem, fileSystem),
850 Effect.provideService(Path.Path, path),
851 Effect.provideService(SecureRandom.SecureRandom, random),
852 );
853 return { provider, modelsFromModelSelect: yield* Ref.get(modelsFromSelectRef) };
854 });
855 const hasRegistryAgent =
856 effectiveConfig.enabled &&
857 effectiveConfig.source !== "local" &&
858 effectiveConfig.agentId.trim().length > 0;
859 const clearLiveState = (
860 Option.isSome(runtimeCoordinator)
861 ? runtimeCoordinator.value
862 .clearLiveConfiguration(instanceId)
863 .pipe(Effect.andThen(runtimeCoordinator.value.clearAvailableCommands(instanceId)))
864 : Effect.void
865 ).pipe(Effect.andThen(clearLearnedModels), Effect.andThen(Ref.set(lastAcceptedCatalog, null)));
866 const enrichmentCache = yield* Ref.make<AcpRegistryEnrichmentCache>({
867 generation: 0,
868 entry: null,
869 });
870 const liveSnapshotSemaphore = yield* Semaphore.make(1);
871 const invalidateEnrichmentCache = Ref.update(enrichmentCache, (current) => ({
872 generation: current.generation + 1,
873 entry: null,
874 }));
875 const enrichProviderCached = Effect.fn("AcpRegistryDriver.enrichProviderCached")(function* (
876 baseSnapshot: ServerProvider,
877 publish: (enriched: {
878 readonly provider: ServerProvider;
879 readonly generation: number;
880 readonly fresh: boolean;
881 readonly probeStartLiveRevision: number;
882 readonly modelsFromModelSelect: boolean;
883 readonly runtimeChanged: boolean;
884 }) => Effect.Effect<void>,
885 ) {
886 if (hasRegistryAgent) {
887 yield* catalog
888 .refreshIndex({
889 maxAgeMs: PROBE_SUCCESS_TTL_MS,
890 failureBackoffMs: REGISTRY_REFRESH_FAILURE_BACKOFF_MS,
891 })
892 .pipe(Effect.ignore);
893 }
894 const currentInspection = hasRegistryAgent
895 ? yield* catalog.inspect(effectiveConfig, processEnvironment).pipe(Effect.option)
896 : Option.none();
897 const inspectedVersion =
898 Option.isSome(currentInspection) && currentInspection.value.status === "ready"
899 ? currentInspection.value.version
900 : baseSnapshot.version;
901 const inspectedLaunchIdentity =
902 Option.isSome(currentInspection) && currentInspection.value.status === "ready"
903 ? currentInspection.value.launchIdentity
904 : undefined;
905 const now = yield* Clock.currentTimeMillis;
906 const cacheState = yield* Ref.get(enrichmentCache);
907 const cached = cacheState.entry;
908 if (
909 cached !== null &&
910 isAcpRegistryCacheValid(
911 cached,
912 inspectedVersion,
913 effectiveConfig.source === "local",
914 now,
915 inspectedLaunchIdentity,
916 )
917 ) {
918 return {
919 provider: { ...cached.provider, checkedAt: baseSnapshot.checkedAt },
920 generation: cacheState.generation,
921 fresh: false,
922 probeStartLiveRevision: 0,
923 modelsFromModelSelect: false,
924 runtimeChanged: false,
925 };
926 }
927 const probeStartLiveRevision = Option.isSome(runtimeCoordinator)
928 ? (yield* runtimeCoordinator.value.getLiveConfigurationWithRevision(instanceId)).revision
929 : 0;
930 const runtimeChanged =
931 (cached !== null &&
932 (cached.provider.version !== inspectedVersion ||
933 (inspectedLaunchIdentity !== undefined &&
934 cached.launchIdentity !== inspectedLaunchIdentity))) ||
935 (inspectedVersion !== null &&
936 baseSnapshot.version !== null &&
937 inspectedVersion !== baseSnapshot.version);
938 const remember = Effect.fn("AcpRegistryDriver.rememberEnrichment")(function* (
939 enriched: ServerProvider,
940 ) {
941 if (effectiveConfig.source === "local" && enriched.status === "ready") {
942 yield* Ref.set(reportedLocalVersion, enriched.version);
943 }
944 if (enriched.status === "ready") {
945 const completedAt = yield* Clock.currentTimeMillis;
946 yield* Ref.update(enrichmentCache, (current) =>
947 current.generation === cacheState.generation
948 ? {
949 ...current,
950 entry: {
951 provider: enriched,
952 ...(inspectedLaunchIdentity === undefined
953 ? {}
954 : { launchIdentity: inspectedLaunchIdentity }),
955 expiresAt: completedAt + acpRegistryProbeTtlMs(enriched),
956 },
957 }
958 : current,
959 );
960 }
961 });
962 const { provider: enriched, modelsFromModelSelect } = yield* enrichProvider(
963 (provider, fromSelect) =>
964 remember(provider).pipe(
965 Effect.andThen(
966 publish({
967 provider,
968 generation: cacheState.generation,
969 fresh: true,
970 probeStartLiveRevision,
971 modelsFromModelSelect: fromSelect,
972 runtimeChanged,
973 }),
974 ),
975 ),
976 );
977 yield* remember(enriched);
978 return {
979 provider: enriched,
980 generation: cacheState.generation,
981 fresh: true,
982 probeStartLiveRevision,
983 modelsFromModelSelect,
984 runtimeChanged,
985 };
986 });
987 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
988 const snapshot = yield* makeManagedServerProvider<
989 ProviderSnapshotSettings<AcpRegistrySettings>
990 >({
991 resolveMaintenance: () => Effect.succeed(MAINTENANCE),
992 getSettings: snapshotSettings.getSettings,
993 streamSettings: snapshotSettings.streamSettings,
994 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
995 // Inspection may fetch the registry when its disk cache is missing; creation must not wait on that.
996 initialSnapshot: () => buildInitialAcpRegistrySnapshot(readinessInput),
997 checkProvider,
998 enrichSnapshot: Effect.fn("enrichSnapshot")(function* ({
999 snapshot,
1000 getSnapshot,
1001 publishSnapshot,
1002 }) {
1003 let targetSnapshot = snapshot;
1004 if (!targetSnapshot.installed) {
1005 if (!hasRegistryAgent) return;
1006 const refresh = catalog
1007 .refreshIndex({
1008 maxAgeMs: PROBE_SUCCESS_TTL_MS,
1009 failureBackoffMs: REGISTRY_REFRESH_FAILURE_BACKOFF_MS,
1010 })
1011 .pipe(Effect.orElseSucceed(() => false));
1012 const refreshed = yield* Option.isSome(runtimeCoordinator)
1013 ? runtimeCoordinator.value.runBackgroundProbe(effectiveConfig.agentId, refresh)
1014 : refresh.pipe(Effect.asSome);
1015 if (Option.isNone(refreshed)) return;
1016 targetSnapshot = yield* checkProvider;
1017 if (!targetSnapshot.installed) {
1018 if (refreshed.value) {
1019 yield* liveSnapshotSemaphore.withPermit(publishSnapshot(targetSnapshot));
1020 }
1021 return;
1022 }
1023 yield* liveSnapshotSemaphore.withPermit(publishSnapshot(targetSnapshot));
1024 }
1025 const publishEnriched = ({
1026 provider,
1027 generation,
1028 fresh,
1029 probeStartLiveRevision,
1030 modelsFromModelSelect,
1031 runtimeChanged,
1032 }: {
1033 readonly provider: ServerProvider;
1034 readonly generation: number;
1035 readonly fresh: boolean;
1036 readonly probeStartLiveRevision: number;
1037 readonly modelsFromModelSelect: boolean;
1038 readonly runtimeChanged: boolean;
1039 }) =>
1040 liveSnapshotSemaphore.withPermit(
1041 Effect.gen(function* () {
1042 const current = yield* Ref.get(enrichmentCache);
1043 if (current.generation !== generation) return;
1044 if (fresh && provider.status === "ready") {
1045 const probedBuiltIn = provider.models.filter((model) => !model.isCustom);
1046 const authoritativeProbe =
1047 probedBuiltIn.length > 1 || (probedBuiltIn.length === 1 && modelsFromModelSelect);
1048 if (runtimeChanged || authoritativeProbe) {
1049 const cleared = Option.isSome(runtimeCoordinator)
1050 ? yield* runtimeCoordinator.value.clearLiveConfigurationIfRevision(
1051 instanceId,
1052 probeStartLiveRevision,
1053 )
1054 : true;
1055 if (cleared) {
1056 if (runtimeChanged) {
1057 yield* clearLiveState;
1058 }
1059 if (authoritativeProbe) {
1060 yield* Ref.set(lastAcceptedCatalog, probedBuiltIn);
1061 }
1062 }
1063 }
1064 }
1065 yield* publishSnapshot(yield* withLiveRuntimeState(provider));
1066 }),
1067 );
1068 const enrichment = enrichProviderCached(targetSnapshot, publishEnriched);
1069 const publishEnrichment = (
1070 Option.isSome(runtimeCoordinator)
1071 ? runtimeCoordinator.value.runBackgroundProbe(
1072 effectiveConfig.source === "local"
1073 ? `local:${instanceId}`
1074 : effectiveConfig.agentId,
1075 enrichment,
1076 )
1077 : enrichment.pipe(Effect.asSome)
1078 ).pipe(
1079 Effect.flatMap(
1080 Option.match({
1081 onNone: () => Effect.void,
1082 onSome: publishEnriched,
1083 }),
1084 ),
1085 );
1086 if (Option.isNone(runtimeCoordinator)) return yield* publishEnrichment;
1087
1088 const publishLiveCommands = runtimeCoordinator.value.watchAvailableCommands(
1089 instanceId,
1090 ({ slashCommands, skills }) =>
1091 liveSnapshotSemaphore.withPermit(
1092 getSnapshot.pipe(
1093 Effect.flatMap((current) =>
1094 publishSnapshot({
1095 ...current,
1096 slashCommands,
1097 skills,
1098 }),
1099 ),
1100 ),
1101 ),
1102 );
1103 const publishLiveConfiguration = Ref.get(lastObservedLiveRevision).pipe(
1104 Effect.flatMap((afterRevision) =>
1105 runtimeCoordinator.value.watchLiveConfiguration(
1106 instanceId,
1107 (configuration, revision) =>
1108 liveSnapshotSemaphore.withPermit(
1109 Effect.gen(function* () {
1110 const live =
1111 yield* runtimeCoordinator.value.getLiveConfigurationWithRevision(instanceId);
1112 // A fresh probe cleared this revision; replaying it would restore a stale catalog.
1113 if (live.revision !== revision && Option.isNone(live.configuration)) return;
1114 yield* observeLiveRevision(revision);
1115 const current = yield* getSnapshot;
1116 const updated = yield* applyLiveConfiguration(current, configuration);
1117 if (configuration.models.length > 0) {
1118 const builtIn = updated.models.filter((model) => !model.isCustom);
1119 if (
1120 builtIn.length > 1 ||
1121 (builtIn.length === 1 && configuration.modelsFromModelSelect === true)
1122 ) {
1123 yield* Ref.set(lastAcceptedCatalog, builtIn);
1124 }
1125 }
1126 const now = yield* Clock.currentTimeMillis;
1127 yield* Ref.update(enrichmentCache, (cache) =>
1128 updateAcpRegistryEnrichmentCache({
1129 cache,
1130 configuration,
1131 customModels: effectiveConfig.customModels,
1132 now,
1133 }),
1134 );
1135 yield* publishSnapshot(updated);
1136 }),
1137 ),
1138 { afterRevision },
1139 ),
1140 ),
1141 );
1142 const publishUrlAuthAction = runtimeCoordinator.value.watchUrlAuthAction(
1143 instanceId,
1144 (action) =>
1145 liveSnapshotSemaphore.withPermit(
1146 getSnapshot.pipe(
1147 Effect.flatMap((current) =>
1148 publishSnapshot(
1149 applyAcpRegistryUrlAuthAction(current, Option.fromNullishOr(action)),
1150 ),
1151 ),
1152 ),
1153 ),
1154 );
1155 yield* Effect.all(
1156 [publishEnrichment, publishLiveCommands, publishLiveConfiguration, publishUrlAuthAction],
1157 {
1158 concurrency: "unbounded",
1159 discard: true,
1160 },
1161 );
1162 }),
1163 }).pipe(
1164 Effect.mapError(
1165 (cause) =>
1166 new ProviderDriverError({
1167 driver: DRIVER_KIND,
1168 instanceId,
1169 detail: "Failed to build the ACP Registry provider snapshot.",
1170 cause,
1171 }),
1172 ),
1173 );
1174
1175 const provideAcpManagementServices = <A, E>(
1176 effect: Effect.Effect<
1177 A,
1178 E,
1179 | AcpRegistrySupport.AcpRegistryCatalog
1180 | ChildProcessSpawner.ChildProcessSpawner
1181 | SecureRandom.SecureRandom
1182 >,
1183 ): Effect.Effect<A, E> => {
1184 const provided = effect.pipe(
1185 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
1186 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1187 Effect.provideService(SecureRandom.SecureRandom, random),
1188 );
1189 return Option.isSome(runtimeCoordinator)
1190 ? provided.pipe(
1191 Effect.provideService(
1192 AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
1193 runtimeCoordinator.value,
1194 ),
1195 )
1196 : provided;
1197 };
1198
1199 const controller = yield* AcpRegistryAuth.makeAcpRegistryAuth({
1200 instanceId,
1201 settings: effectiveConfig,
1202 cwd: host.paths.cwd,
1203 environment: processEnvironment,
1204 onChanged: (authenticated) =>
1205 confirmedAuthentication
1206 .set(authenticated)
1207 .pipe(
1208 Effect.andThen(authenticated ? Effect.void : clearLiveState),
1209 Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)),
1210 Effect.andThen(snapshot.refresh),
1211 Effect.asVoid,
1212 ),
1213 }).pipe(
1214 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
1215 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1216 Effect.provideService(SecureRandom.SecureRandom, random),
1217 );
1218 const auth = {
1219 ...controller,
1220 invalidate: (controller.invalidate ?? Effect.void).pipe(
1221 Effect.andThen(confirmedAuthentication.set(false)),
1222 Effect.andThen(clearLiveState),
1223 Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)),
1224 Effect.andThen(snapshot.refresh),
1225 Effect.asVoid,
1226 ),
1227 };
1228
1229 return {
1230 instanceId,
1231 driverKind: DRIVER_KIND,
1232 continuationIdentity,
1233 displayName,
1234 accentColor,
1235 enabled,
1236 auth,
1237 snapshot: {
1238 ...snapshot,
1239 refresh: snapshot.refresh.pipe(Effect.tap(() => controller.refreshMethods ?? Effect.void)),
1240 },
1241 invalidateCaches: liveSnapshotSemaphore
1242 .withPermit(
1243 (Option.isSome(runtimeCoordinator)
1244 ? runtimeCoordinator.value.clearLiveConfiguration(instanceId)
1245 : Effect.void
1246 ).pipe(
1247 Effect.andThen(clearLearnedModels),
1248 Effect.andThen(Ref.set(lastAcceptedCatalog, null)),
1249 Effect.andThen(invalidateEnrichmentCache),
1250 ),
1251 )
1252 .pipe(Effect.andThen(hasRegistryAgent ? catalog.invalidateIndex() : Effect.void)),
1253 orchestrationAdapter,
1254 textGeneration: yield* makeAcpRegistryTextGeneration({
1255 instanceId,
1256 settings: effectiveConfig,
1257 environment: processEnvironment,
1258 }),
1259 acpSessionManagement: {
1260 listSessions: ({ cwd, cursor }) =>
1261 provideAcpManagementServices(
1262 listAcpRegistrySessions({
1263 instanceId,
1264 settings: effectiveConfig,
1265 cwd,
1266 environment: processEnvironment,
1267 ...(cursor === undefined ? {} : { cursor }),
1268 }),
1269 ),
1270 deleteSession: ({ cwd, sessionId }) =>
1271 provideAcpManagementServices(
1272 deleteAcpRegistrySession({
1273 instanceId,
1274 settings: effectiveConfig,
1275 cwd,
1276 environment: processEnvironment,
1277 sessionId,
1278 }),
1279 ),
1280 listProviders: (cwd) =>
1281 provideAcpManagementServices(
1282 listAcpRegistryProviders({
1283 instanceId,
1284 settings: effectiveConfig,
1285 cwd,
1286 environment: processEnvironment,
1287 }),
1288 ),
1289 setProvider: ({ cwd, providerId, apiType, baseUrl, headers }) =>
1290 provideAcpManagementServices(
1291 setAcpRegistryProvider({
1292 instanceId,
1293 settings: effectiveConfig,
1294 cwd,
1295 environment: processEnvironment,
1296 providerId,
1297 apiType,
1298 baseUrl,
1299 ...(headers === undefined ? {} : { headers }),
1300 }),
1301 ).pipe(
1302 Effect.tap(() =>
1303 liveSnapshotSemaphore.withPermit(
1304 (Option.isSome(runtimeCoordinator)
1305 ? runtimeCoordinator.value.clearLiveConfiguration(instanceId)
1306 : Effect.void
1307 ).pipe(
1308 Effect.andThen(Ref.set(lastAcceptedCatalog, null)),
1309 Effect.andThen(invalidateEnrichmentCache),
1310 ),
1311 ),
1312 ),
1313 ),
1314 disableProvider: ({ cwd, providerId }) =>
1315 provideAcpManagementServices(
1316 disableAcpRegistryProvider({
1317 instanceId,
1318 settings: effectiveConfig,
1319 cwd,
1320 environment: processEnvironment,
1321 providerId,
1322 }),
1323 ).pipe(
1324 Effect.tap(() =>
1325 liveSnapshotSemaphore.withPermit(
1326 (Option.isSome(runtimeCoordinator)
1327 ? runtimeCoordinator.value.clearLiveConfiguration(instanceId)
1328 : Effect.void
1329 ).pipe(
1330 Effect.andThen(Ref.set(lastAcceptedCatalog, null)),
1331 Effect.andThen(invalidateEnrichmentCache),
1332 ),
1333 ),
1334 ),
1335 ),
1336 logout: (cwd) => {
1337 const logout = logoutAcpRegistry({
1338 instanceId,
1339 settings: effectiveConfig,
1340 cwd,
1341 environment: processEnvironment,
1342 }).pipe(
1343 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
1344 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1345 Effect.provideService(SecureRandom.SecureRandom, random),
1346 Effect.tap(() => confirmedAuthentication.set(false)),
1347 Effect.tap(() =>
1348 liveSnapshotSemaphore.withPermit(
1349 invalidateEnrichmentCache.pipe(
1350 Effect.andThen(Ref.set(lastAcceptedCatalog, null)),
1351 Effect.andThen(clearLearnedModels),
1352 Effect.andThen(
1353 Option.isSome(runtimeCoordinator)
1354 ? Effect.all(
1355 [
1356 runtimeCoordinator.value.clearAvailableCommands(instanceId),
1357 runtimeCoordinator.value.clearLiveConfiguration(instanceId),
1358 ],
1359 { concurrency: "unbounded", discard: true },
1360 )
1361 : Effect.void,
1362 ),
1363 ),
1364 ),
1365 ),
1366 );
1367 return Option.isSome(runtimeCoordinator)
1368 ? logout.pipe(
1369 Effect.provideService(
1370 AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
1371 runtimeCoordinator.value,
1372 ),
1373 )
1374 : logout;
1375 },
1376 },
1377 } satisfies ProviderInstance;
1378 }),
1379};