Open History to see the last commit
1import {
2 officialAcpRegistryIconUrlForAgentId,
3 ProviderDriverKind,
4 resolveOfficialAcpRegistryIconUrl,
5 TextGenerationError,
6 type AcpRegistryOperationError,
7 type ServerProvider,
8 type ServerProviderModel,
9} from "@t3tools/contracts";
10import { AcpRegistrySettings } from "../settings.ts";
11import * as HostProcess from "@t3tools/shared/HostProcess";
12import { createModelCapabilities } from "@t3tools/shared/model";
13import * as Clock from "effect/Clock";
14import * as Crypto from "effect/Crypto";
15import * as DateTime from "effect/DateTime";
16import * as Effect from "effect/Effect";
17import * as Option from "effect/Option";
18import * as Ref from "effect/Ref";
19import * as Result from "effect/Result";
20import * as Schema from "effect/Schema";
21import * as Semaphore from "effect/Semaphore";
22import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
23
24import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
25import { AcpRegistryAdapterV2Driver, type AcpRegistryAdapterV2DriverEnv } from "./adapter.ts";
26import type { ProviderTextGeneration } from "@t3tools/provider-core/server/textGeneration";
27import { ProviderDriverError } from "@t3tools/provider-core/server/errors";
28import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
29import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
30import {
31 defaultProviderContinuationIdentity,
32 type ProviderDriver,
33 type ProviderInstance,
34} from "@t3tools/provider-core/server/driver";
35import { providerModelsFromSettings } from "@t3tools/provider-core/server/snapshotProbe";
36import { makeManualOnlyProviderMaintenanceCapabilities } from "@t3tools/provider-core/server/maintenanceResolver";
37import {
38 haveProviderSnapshotSettingsChanged,
39 makeProviderSnapshotSettingsSource,
40 type ProviderSnapshotSettings,
41} from "@t3tools/provider-core/server/snapshotSettings";
42import {
43 type AcpRegistryAvailableCommands,
44 type AcpRegistryConfigurationProbe,
45 type AcpRegistryConfigurationProbeResult,
46 type AcpRegistryLiveConfiguration,
47 deleteAcpRegistrySession,
48 disableAcpRegistryProvider,
49 listAcpRegistrySessions,
50 listAcpRegistryProviders,
51 logoutAcpRegistry,
52 probeAcpRegistryConfiguration,
53 setAcpRegistryProvider,
54} from "./probe.ts";
55import * as AcpRegistrySupport from "./AcpRegistrySupport.ts";
56import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts";
57import * as AcpRegistryAuth from "./auth.ts";
58import * as AcpRegistryAuthenticationState from "./authenticationState.ts";
59
60const DRIVER_KIND = ProviderDriverKind.make("acpRegistry");
61const decodeSettings = Schema.decodeSync(AcpRegistrySettings);
62// Cache only successful authenticated probes so sign-in changes remain visible.
63const PROBE_SUCCESS_TTL_MS = 15 * 60 * 1_000;
64const EMPTY_CAPABILITIES = createModelCapabilities({ optionDescriptors: [] });
65const MAINTENANCE = makeManualOnlyProviderMaintenanceCapabilities({
66 provider: DRIVER_KIND,
67 packageName: null,
68});
69
70const makeUnsupportedTextGeneration = (): ProviderTextGeneration => {
71 const unsupported = (operation: string) =>
72 Effect.fail(
73 new TextGenerationError({
74 operation,
75 detail: "ACP Registry instances do not provide application text generation.",
76 }),
77 );
78 return {
79 generateCommitMessage: () => unsupported("generateCommitMessage"),
80 generatePrContent: () => unsupported("generatePrContent"),
81 generateBranchName: () => unsupported("generateBranchName"),
82 generateThreadTitle: () => unsupported("generateThreadTitle"),
83 generateReviewGuide: () => unsupported("generateReviewGuide"),
84 };
85};
86
87function modelsFromDiscovery(
88 discovery:
89 | Pick<AcpRegistryLiveConfiguration, "models" | "currentModelId" | "configOptions">
90 | undefined,
91 customModels: ReadonlyArray<string>,
92): ReadonlyArray<ServerProviderModel> {
93 const discovered = discovery?.models ?? [];
94 const capabilities =
95 discovery === undefined || discovery.configOptions.length === 0
96 ? EMPTY_CAPABILITIES
97 : createModelCapabilities({ optionDescriptors: discovery.configOptions });
98 const builtInModels: ReadonlyArray<ServerProviderModel> =
99 discovered.length === 0
100 ? [
101 {
102 slug: "default",
103 name: "Default",
104 isCustom: false,
105 isDefault: true,
106 capabilities,
107 },
108 ]
109 : discovered.map((model) => ({
110 slug: model.id,
111 name: model.name,
112 isCustom: false,
113 ...(model.id === discovery?.currentModelId ? { isDefault: true } : {}),
114 capabilities,
115 }));
116 return providerModelsFromSettings(builtInModels, customModels, capabilities);
117}
118
119function acpRegistrySnapshotReadiness(
120 inspection:
121 | AcpRegistrySupport.AcpRegistryInspection
122 | { readonly status: "failed"; readonly message: string },
123): Pick<ServerProvider, "installed" | "version" | "status" | "message"> {
124 switch (inspection.status) {
125 case "ready":
126 return { installed: true, version: inspection.version, status: "ready" };
127 case "unconfigured":
128 return {
129 installed: false,
130 version: null,
131 status: "warning",
132 message:
133 "Select an ACP Registry agent or configure a local ACP executable before starting a thread.",
134 };
135 case "not_found":
136 return {
137 installed: false,
138 version: null,
139 status: "error",
140 message: `ACP Registry does not contain agent '${inspection.agentId}'.`,
141 };
142 case "unsupported":
143 return {
144 installed: false,
145 version: inspection.version,
146 status: "error",
147 message: `ACP Registry agent '${inspection.agentId}' has no compatible distribution for this environment.`,
148 };
149 case "missing_runner":
150 return {
151 installed: false,
152 version: inspection.version,
153 status: "error",
154 message:
155 inspection.distribution === "local"
156 ? "Local ACP executable is not available on this environment's PATH."
157 : `ACP executable '${inspection.runner}' is not available on this environment's PATH.`,
158 };
159 case "unprepared":
160 return {
161 installed: false,
162 version: inspection.version,
163 status: "warning",
164 message: `ACP Registry agent '${inspection.agentId}' has not been prepared on this environment.`,
165 };
166 case "failed":
167 return {
168 installed: false,
169 version: null,
170 status: "error",
171 message: inspection.message,
172 };
173 }
174}
175
176interface SnapshotIdentity {
177 readonly instanceId: ProviderInstance["instanceId"];
178 readonly displayName: string | undefined;
179 readonly accentColor: string | undefined;
180 readonly continuationKey: string;
181}
182
183function baseSnapshot(
184 input: SnapshotIdentity & {
185 readonly settings: AcpRegistrySettings;
186 readonly checkedAt: string;
187 readonly installed: boolean;
188 readonly version: string | null;
189 readonly status: ServerProvider["status"];
190 readonly auth: ServerProvider["auth"];
191 readonly documentationUrl?: string;
192 readonly message?: string;
193 readonly probe?: AcpRegistryConfigurationProbeResult;
194 readonly probeError?: AcpRegistryOperationError;
195 },
196): ServerProvider {
197 const iconUrl =
198 input.settings.source === "local"
199 ? null
200 : (resolveOfficialAcpRegistryIconUrl(input.probe?.probe.icon) ??
201 officialAcpRegistryIconUrlForAgentId(input.settings.agentId));
202 return {
203 instanceId: input.instanceId,
204 driver: DRIVER_KIND,
205 ...(input.displayName ? { displayName: input.displayName } : {}),
206 ...(input.accentColor ? { accentColor: input.accentColor } : {}),
207 ...(iconUrl ? { iconUrl } : {}),
208 continuation: { groupKey: input.continuationKey },
209 supportsTextGeneration: false,
210 enabled: input.settings.enabled,
211 installed: input.installed,
212 version: input.version,
213 status: input.settings.enabled ? input.status : "disabled",
214 auth: { ...input.auth, canLogout: input.auth.canLogout ?? false },
215 checkedAt: input.checkedAt,
216 setup: {
217 canInstall: false,
218 ...(input.documentationUrl ? { documentationUrl: input.documentationUrl } : {}),
219 canAuthenticate:
220 input.installed &&
221 (input.probe
222 ? input.probe.probe.authMethods.length > 0
223 : input.settings.source === "local"
224 ? (input.probeError?.authMethods?.length ?? 0) > 0
225 : input.settings.agentId.length > 0),
226 },
227 ...(input.message ? { message: input.message } : {}),
228 models: modelsFromDiscovery(input.probe?.probe, input.settings.customModels),
229 ...(input.probe === undefined
230 ? {}
231 : {
232 nativeSessions: {
233 canList: input.probe.probe.sessionManagement.canList,
234 canLoad: input.probe.probe.sessionManagement.canLoad,
235 canResume: input.probe.probe.sessionManagement.canResume,
236 canDelete: input.probe.probe.sessionManagement.canDelete,
237 },
238 configurableProviders: input.probe.probe.sessionManagement.canConfigureProviders,
239 }),
240 slashCommands: input.probe?.slashCommands ?? [],
241 skills: input.probe?.skills ?? [],
242 };
243}
244
245export function applyAcpRegistryAvailableCommands(
246 provider: ServerProvider,
247 commands: Option.Option<AcpRegistryAvailableCommands>,
248): ServerProvider {
249 return Option.match(commands, {
250 onNone: () => provider,
251 onSome: ({ slashCommands, skills }) => ({ ...provider, slashCommands, skills }),
252 });
253}
254
255export function applyAcpRegistryLiveConfiguration(
256 provider: ServerProvider,
257 configuration: AcpRegistryLiveConfiguration,
258 customModels: ReadonlyArray<string>,
259): ServerProvider {
260 const { message: _staleProbeMessage, ...snapshot } = provider;
261 return {
262 ...snapshot,
263 status: provider.enabled ? "ready" : provider.status,
264 models: modelsFromDiscovery(configuration, customModels),
265 };
266}
267
268function applyAcpRegistryUrlAuthAction(
269 provider: ServerProvider,
270 action: Option.Option<NonNullable<ServerProvider["auth"]["action"]>>,
271): ServerProvider {
272 const { action: _previousAction, ...auth } = provider.auth;
273 return {
274 ...provider,
275 auth: Option.match(action, {
276 onNone: () => auth,
277 onSome: (nextAction) => ({ ...auth, action: nextAction }),
278 }),
279 };
280}
281
282const buildInitialAcpRegistrySnapshot = Effect.fn("AcpRegistryDriver.buildInitialSnapshot")(
283 function* (input: SnapshotIdentity & { readonly settings: AcpRegistrySettings }) {
284 const checkedAt = DateTime.formatIso(yield* DateTime.now);
285 return baseSnapshot({
286 ...input,
287 checkedAt,
288 installed: false,
289 version: null,
290 status: "warning",
291 auth: { status: "unknown" },
292 message: input.settings.enabled
293 ? "Checking ACP Registry agent readiness..."
294 : "ACP Registry is disabled in T3 Code settings.",
295 });
296 },
297);
298
299export function buildCheckedAcpRegistrySnapshot(
300 input: SnapshotIdentity & {
301 readonly settings: AcpRegistrySettings;
302 readonly checkedAt: string;
303 readonly inspection:
304 | AcpRegistrySupport.AcpRegistryInspection
305 | { readonly status: "failed"; readonly message: string };
306 readonly probe?: AcpRegistryConfigurationProbeResult;
307 readonly probeError?: AcpRegistryOperationError;
308 },
309): ServerProvider {
310 const readiness = acpRegistrySnapshotReadiness(input.inspection);
311 const probeFailed = input.probeError !== undefined;
312 const advertisedAuthMethod =
313 input.probeError?.reason === "authentication_failed"
314 ? (input.probeError.authMethods?.find(
315 (method) => method.id === input.settings.authMethodId,
316 ) ?? input.probeError.authMethods?.[0])
317 : undefined;
318 const authenticationMessage = advertisedAuthMethod
319 ? advertisedAuthMethod.type === "terminal" && advertisedAuthMethod.command
320 ? `Sign in in provider settings using "${advertisedAuthMethod.name}". The login terminal runs on this environment.`
321 : advertisedAuthMethod.type === "env_var" &&
322 (advertisedAuthMethod.envVarNames?.length ?? 0) > 0
323 ? `Set ${advertisedAuthMethod.envVarNames!.join(", ")} under this instance's environment variables in provider settings. T3 Code will detect it on the next provider refresh.`
324 : `Sign in in provider settings using "${advertisedAuthMethod.name}".`
325 : undefined;
326 return baseSnapshot({
327 ...input,
328 ...(input.inspection.status === "ready" && input.inspection.documentationUrl
329 ? { documentationUrl: input.inspection.documentationUrl }
330 : {}),
331 installed: readiness.installed,
332 version: readiness.version,
333 // Failed discovery is a warning: an installed agent may still run real turns.
334 status: probeFailed ? "warning" : readiness.status,
335 auth: input.probe
336 ? {
337 // Discovery sessions and an empty auth-method list do not prove sign-in.
338 status: "unknown",
339 canLogout: input.probe.probe.sessionManagement.canLogout,
340 }
341 : input.probeError?.reason === "authentication_failed"
342 ? {
343 status: "unauthenticated",
344 ...(advertisedAuthMethod
345 ? { type: advertisedAuthMethod.type, label: advertisedAuthMethod.name }
346 : {}),
347 ...(input.probeError.authAction === undefined
348 ? {}
349 : { action: input.probeError.authAction }),
350 }
351 : { status: "unknown" },
352 ...(input.probeError
353 ? { message: authenticationMessage ?? input.probeError.message }
354 : readiness.message
355 ? { message: readiness.message }
356 : {}),
357 });
358}
359
360export const checkAcpRegistryProviderStatus = Effect.fn("AcpRegistryDriver.checkProviderStatus")(
361 function* <Requirements>(
362 input: SnapshotIdentity & {
363 readonly settings: AcpRegistrySettings;
364 readonly cwd: string;
365 readonly environment: NodeJS.ProcessEnv;
366 },
367 probeConfiguration: AcpRegistryConfigurationProbe<Requirements>,
368 ): Effect.fn.Return<ServerProvider, never, AcpRegistrySupport.AcpRegistryCatalog | Requirements> {
369 const checkedAt = DateTime.formatIso(yield* DateTime.now);
370 if (!input.settings.enabled) {
371 return yield* buildInitialAcpRegistrySnapshot(input);
372 }
373 const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog;
374 const inspected = yield* Effect.result(catalog.inspect(input.settings, input.environment));
375 if (Result.isFailure(inspected)) {
376 return buildCheckedAcpRegistrySnapshot({
377 ...input,
378 checkedAt,
379 inspection: {
380 status: "failed",
381 message: `Could not inspect ACP Registry agent: ${inspected.failure.message}`,
382 },
383 });
384 }
385 if (inspected.success.status !== "ready") {
386 return buildCheckedAcpRegistrySnapshot({
387 ...input,
388 checkedAt,
389 inspection: inspected.success,
390 });
391 }
392 const probed = yield* Effect.result(
393 probeConfiguration({
394 instanceId: input.instanceId,
395 settings: input.settings,
396 cwd: input.cwd,
397 environment: input.environment,
398 }),
399 );
400 return Result.isFailure(probed)
401 ? buildCheckedAcpRegistrySnapshot({
402 ...input,
403 checkedAt,
404 inspection: inspected.success,
405 probeError: probed.failure,
406 })
407 : buildCheckedAcpRegistrySnapshot({
408 ...input,
409 checkedAt,
410 inspection: inspected.success,
411 probe: probed.success,
412 });
413 },
414);
415
416export const checkAcpRegistryProviderReadiness = Effect.fn(
417 "AcpRegistryDriver.checkProviderReadiness",
418)(function* (
419 input: SnapshotIdentity & {
420 readonly settings: AcpRegistrySettings;
421 readonly environment: NodeJS.ProcessEnv;
422 },
423): Effect.fn.Return<ServerProvider, never, AcpRegistrySupport.AcpRegistryCatalog> {
424 const checkedAt = DateTime.formatIso(yield* DateTime.now);
425 if (!input.settings.enabled) {
426 return yield* buildInitialAcpRegistrySnapshot(input);
427 }
428 const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog;
429 const inspected = yield* Effect.result(catalog.inspect(input.settings, input.environment));
430 const snapshot = buildCheckedAcpRegistrySnapshot({
431 ...input,
432 checkedAt,
433 inspection: Result.isFailure(inspected)
434 ? {
435 status: "failed",
436 message: `Could not inspect ACP Registry agent: ${inspected.failure.message}`,
437 }
438 : inspected.success,
439 });
440 return inspected._tag === "Success" && inspected.success.status === "ready"
441 ? {
442 ...snapshot,
443 message: "Checking ACP authentication, models, and commands in the background...",
444 }
445 : snapshot;
446});
447
448export type AcpRegistryDriverEnv = AcpRegistryAdapterV2DriverEnv | ProviderHost.ProviderHost;
449
450export const AcpRegistryDriver: ProviderDriver<AcpRegistrySettings, AcpRegistryDriverEnv> = {
451 driverKind: DRIVER_KIND,
452 metadata: {
453 displayName: "ACP Registry",
454 supportsMultipleInstances: true,
455 hasDefaultInstance: false,
456 },
457 configSchema: AcpRegistrySettings,
458 defaultConfig: () => decodeSettings({}),
459 create: Effect.fn("AcpRegistryDriver.create")(function* ({
460 instanceId,
461 displayName,
462 accentColor,
463 environment,
464 enabled,
465 config,
466 }) {
467 const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog;
468 const runtimeCoordinator = yield* Effect.serviceOption(
469 AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
470 );
471 if (Option.isSome(runtimeCoordinator)) {
472 yield* runtimeCoordinator.value.clearAvailableCommands(instanceId);
473 yield* runtimeCoordinator.value.clearLiveConfiguration(instanceId);
474 yield* Effect.addFinalizer(() =>
475 runtimeCoordinator.value
476 .clearAvailableCommands(instanceId)
477 .pipe(Effect.andThen(runtimeCoordinator.value.clearLiveConfiguration(instanceId))),
478 );
479 }
480 const crypto = yield* Crypto.Crypto;
481 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
482 const hostEnvironment = yield* HostProcess.Environment;
483 const host = yield* ProviderHost.ProviderHost;
484 const continuationIdentity = defaultProviderContinuationIdentity({
485 driverKind: DRIVER_KIND,
486 instanceId,
487 });
488 const identity = {
489 instanceId,
490 displayName,
491 accentColor,
492 continuationKey: continuationIdentity.continuationKey,
493 };
494 const effectiveConfig = { ...config, enabled } satisfies AcpRegistrySettings;
495 const processEnvironment = yield* mergeProviderInstanceEnvironment(
496 environment,
497 hostEnvironment,
498 );
499 const orchestrationAdapter = yield* AcpRegistryAdapterV2Driver.create({
500 instanceId,
501 displayName,
502 accentColor,
503 environment,
504 enabled,
505 config,
506 }).pipe(
507 Effect.mapError(
508 (cause) =>
509 new ProviderDriverError({
510 driver: DRIVER_KIND,
511 instanceId,
512 detail: "Failed to build ACP Registry orchestration adapter.",
513 cause,
514 }),
515 ),
516 );
517 const readinessInput = {
518 ...identity,
519 settings: effectiveConfig,
520 environment: processEnvironment,
521 };
522 const confirmedAuthentication =
523 yield* AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({
524 cacheDir: host.paths.providerStatusCacheDir,
525 instanceId,
526 settings: effectiveConfig,
527 environment,
528 processEnvironment,
529 });
530 const withLiveRuntimeState = Effect.fn("AcpRegistryDriver.withLiveRuntimeState")(function* (
531 input: ServerProvider,
532 ) {
533 if (input.auth.status === "unauthenticated") yield* confirmedAuthentication.set(false);
534 const provider =
535 input.enabled &&
536 input.installed &&
537 input.auth.status === "unknown" &&
538 (yield* confirmedAuthentication.get)
539 ? { ...input, auth: { ...input.auth, status: "authenticated" as const } }
540 : input;
541 return yield* Option.isNone(runtimeCoordinator)
542 ? Effect.succeed(provider)
543 : Effect.all({
544 commands: runtimeCoordinator.value.getAvailableCommands(instanceId),
545 configuration: runtimeCoordinator.value.getLiveConfiguration(instanceId),
546 authAction: runtimeCoordinator.value.getUrlAuthAction(instanceId),
547 }).pipe(
548 Effect.map(({ commands, configuration, authAction }) => {
549 const withCommands = applyAcpRegistryAvailableCommands(provider, commands);
550 const withConfiguration = Option.match(configuration, {
551 onNone: () => withCommands,
552 onSome: (liveConfiguration) =>
553 applyAcpRegistryLiveConfiguration(
554 withCommands,
555 liveConfiguration,
556 effectiveConfig.customModels,
557 ),
558 });
559 return applyAcpRegistryUrlAuthAction(withConfiguration, authAction);
560 }),
561 );
562 });
563 const checkProvider = checkAcpRegistryProviderReadiness(readinessInput).pipe(
564 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
565 Effect.flatMap(withLiveRuntimeState),
566 );
567 const enrichProvider = checkAcpRegistryProviderStatus(
568 {
569 ...readinessInput,
570 cwd: host.paths.cwd,
571 },
572 probeAcpRegistryConfiguration,
573 ).pipe(
574 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
575 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
576 Effect.provideService(Crypto.Crypto, crypto),
577 );
578 const enrichmentCache = yield* Ref.make<{
579 readonly generation: number;
580 readonly entry: {
581 readonly provider: ServerProvider;
582 readonly expiresAt: number;
583 } | null;
584 }>({ generation: 0, entry: null });
585 const liveSnapshotSemaphore = yield* Semaphore.make(1);
586 const invalidateEnrichmentCache = Ref.update(enrichmentCache, (current) => ({
587 generation: current.generation + 1,
588 entry: null,
589 }));
590 const enrichProviderCached = Effect.fn("AcpRegistryDriver.enrichProviderCached")(function* (
591 baseSnapshot: ServerProvider,
592 ) {
593 const now = yield* Clock.currentTimeMillis;
594 const cacheState = yield* Ref.get(enrichmentCache);
595 const cached = cacheState.entry;
596 if (
597 cached !== null &&
598 cached.expiresAt > now &&
599 cached.provider.version === baseSnapshot.version
600 ) {
601 return {
602 provider: { ...cached.provider, checkedAt: baseSnapshot.checkedAt },
603 generation: cacheState.generation,
604 };
605 }
606 const enriched = yield* enrichProvider;
607 if (enriched.status === "ready") {
608 yield* Ref.update(enrichmentCache, (current) =>
609 current.generation === cacheState.generation
610 ? {
611 ...current,
612 entry: {
613 provider: enriched,
614 expiresAt: now + PROBE_SUCCESS_TTL_MS,
615 },
616 }
617 : current,
618 );
619 }
620 return { provider: enriched, generation: cacheState.generation };
621 });
622 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
623 const snapshot = yield* makeManagedServerProvider<
624 ProviderSnapshotSettings<AcpRegistrySettings>
625 >({
626 resolveMaintenance: () => Effect.succeed(MAINTENANCE),
627 getSettings: snapshotSettings.getSettings,
628 streamSettings: snapshotSettings.streamSettings,
629 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
630 initialSnapshot: () => checkProvider,
631 checkProvider,
632 enrichSnapshot: ({ snapshot, getSnapshot, publishSnapshot }) => {
633 if (!snapshot.installed) return Effect.void;
634 const publishEnrichment = (
635 Option.isSome(runtimeCoordinator)
636 ? runtimeCoordinator.value.runBackgroundProbe(
637 effectiveConfig.source === "local"
638 ? `local:${instanceId}`
639 : effectiveConfig.agentId,
640 enrichProviderCached(snapshot),
641 )
642 : enrichProviderCached(snapshot).pipe(Effect.map(Option.some))
643 ).pipe(
644 Effect.flatMap(
645 Option.match({
646 onNone: () => Effect.void,
647 onSome: ({ provider, generation }) =>
648 liveSnapshotSemaphore.withPermit(
649 Ref.get(enrichmentCache).pipe(
650 Effect.flatMap((current) =>
651 current.generation === generation
652 ? withLiveRuntimeState(provider).pipe(Effect.flatMap(publishSnapshot))
653 : Effect.void,
654 ),
655 ),
656 ),
657 }),
658 ),
659 );
660 if (Option.isNone(runtimeCoordinator)) return publishEnrichment;
661
662 const publishLiveCommands = runtimeCoordinator.value.watchAvailableCommands(
663 instanceId,
664 ({ slashCommands, skills }) =>
665 liveSnapshotSemaphore.withPermit(
666 getSnapshot.pipe(
667 Effect.flatMap((current) =>
668 publishSnapshot({
669 ...current,
670 slashCommands,
671 skills,
672 }),
673 ),
674 ),
675 ),
676 );
677 const publishLiveConfiguration = runtimeCoordinator.value.watchLiveConfiguration(
678 instanceId,
679 (configuration) =>
680 liveSnapshotSemaphore.withPermit(
681 getSnapshot.pipe(
682 Effect.flatMap((current) =>
683 publishSnapshot(
684 applyAcpRegistryLiveConfiguration(
685 current,
686 configuration,
687 effectiveConfig.customModels,
688 ),
689 ),
690 ),
691 ),
692 ),
693 );
694 const publishUrlAuthAction = runtimeCoordinator.value.watchUrlAuthAction(
695 instanceId,
696 (action) =>
697 liveSnapshotSemaphore.withPermit(
698 getSnapshot.pipe(
699 Effect.flatMap((current) =>
700 publishSnapshot(
701 applyAcpRegistryUrlAuthAction(current, Option.fromNullishOr(action)),
702 ),
703 ),
704 ),
705 ),
706 );
707 return Effect.all(
708 [publishEnrichment, publishLiveCommands, publishLiveConfiguration, publishUrlAuthAction],
709 {
710 concurrency: "unbounded",
711 discard: true,
712 },
713 );
714 },
715 }).pipe(
716 Effect.mapError(
717 (cause) =>
718 new ProviderDriverError({
719 driver: DRIVER_KIND,
720 instanceId,
721 detail: "Failed to build the ACP Registry provider snapshot.",
722 cause,
723 }),
724 ),
725 );
726
727 const provideAcpManagementServices = <A, E>(
728 effect: Effect.Effect<
729 A,
730 E,
731 | AcpRegistrySupport.AcpRegistryCatalog
732 | ChildProcessSpawner.ChildProcessSpawner
733 | Crypto.Crypto
734 >,
735 ): Effect.Effect<A, E> => {
736 const provided = effect.pipe(
737 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
738 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
739 Effect.provideService(Crypto.Crypto, crypto),
740 );
741 return Option.isSome(runtimeCoordinator)
742 ? provided.pipe(
743 Effect.provideService(
744 AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
745 runtimeCoordinator.value,
746 ),
747 )
748 : provided;
749 };
750
751 const clearLiveState = Option.isSome(runtimeCoordinator)
752 ? runtimeCoordinator.value
753 .clearLiveConfiguration(instanceId)
754 .pipe(Effect.andThen(runtimeCoordinator.value.clearAvailableCommands(instanceId)))
755 : Effect.void;
756 const controller = yield* AcpRegistryAuth.makeAcpRegistryAuth({
757 instanceId,
758 settings: effectiveConfig,
759 cwd: host.paths.cwd,
760 environment: processEnvironment,
761 onChanged: (authenticated) =>
762 confirmedAuthentication
763 .set(authenticated)
764 .pipe(
765 Effect.andThen(authenticated ? Effect.void : clearLiveState),
766 Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)),
767 Effect.andThen(snapshot.refresh),
768 Effect.asVoid,
769 ),
770 }).pipe(
771 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
772 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
773 Effect.provideService(Crypto.Crypto, crypto),
774 );
775 const auth = {
776 ...controller,
777 invalidate: (controller.invalidate ?? Effect.void).pipe(
778 Effect.andThen(confirmedAuthentication.set(false)),
779 Effect.andThen(clearLiveState),
780 Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)),
781 Effect.andThen(snapshot.refresh),
782 Effect.asVoid,
783 ),
784 };
785
786 return {
787 instanceId,
788 driverKind: DRIVER_KIND,
789 continuationIdentity,
790 displayName,
791 accentColor,
792 enabled,
793 auth,
794 snapshot: {
795 ...snapshot,
796 refresh: snapshot.refresh.pipe(Effect.tap(() => controller.refreshMethods ?? Effect.void)),
797 },
798 orchestrationAdapter,
799 textGeneration: makeUnsupportedTextGeneration(),
800 acpSessionManagement: {
801 listSessions: ({ cwd, cursor }) =>
802 provideAcpManagementServices(
803 listAcpRegistrySessions({
804 instanceId,
805 settings: effectiveConfig,
806 cwd,
807 environment: processEnvironment,
808 ...(cursor === undefined ? {} : { cursor }),
809 }),
810 ),
811 deleteSession: ({ cwd, sessionId }) =>
812 provideAcpManagementServices(
813 deleteAcpRegistrySession({
814 instanceId,
815 settings: effectiveConfig,
816 cwd,
817 environment: processEnvironment,
818 sessionId,
819 }),
820 ),
821 listProviders: (cwd) =>
822 provideAcpManagementServices(
823 listAcpRegistryProviders({
824 instanceId,
825 settings: effectiveConfig,
826 cwd,
827 environment: processEnvironment,
828 }),
829 ),
830 setProvider: ({ cwd, providerId, apiType, baseUrl, headers }) =>
831 provideAcpManagementServices(
832 setAcpRegistryProvider({
833 instanceId,
834 settings: effectiveConfig,
835 cwd,
836 environment: processEnvironment,
837 providerId,
838 apiType,
839 baseUrl,
840 ...(headers === undefined ? {} : { headers }),
841 }),
842 ).pipe(Effect.tap(() => liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache))),
843 disableProvider: ({ cwd, providerId }) =>
844 provideAcpManagementServices(
845 disableAcpRegistryProvider({
846 instanceId,
847 settings: effectiveConfig,
848 cwd,
849 environment: processEnvironment,
850 providerId,
851 }),
852 ).pipe(Effect.tap(() => liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache))),
853 logout: (cwd) => {
854 const logout = logoutAcpRegistry({
855 instanceId,
856 settings: effectiveConfig,
857 cwd,
858 environment: processEnvironment,
859 }).pipe(
860 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
861 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
862 Effect.provideService(Crypto.Crypto, crypto),
863 Effect.tap(() => confirmedAuthentication.set(false)),
864 Effect.tap(() =>
865 liveSnapshotSemaphore.withPermit(
866 invalidateEnrichmentCache.pipe(
867 Effect.andThen(
868 Option.isSome(runtimeCoordinator)
869 ? Effect.all(
870 [
871 runtimeCoordinator.value.clearAvailableCommands(instanceId),
872 runtimeCoordinator.value.clearLiveConfiguration(instanceId),
873 ],
874 { concurrency: "unbounded", discard: true },
875 )
876 : Effect.void,
877 ),
878 ),
879 ),
880 ),
881 );
882 return Option.isSome(runtimeCoordinator)
883 ? logout.pipe(
884 Effect.provideService(
885 AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
886 runtimeCoordinator.value,
887 ),
888 )
889 : logout;
890 },
891 },
892 } satisfies ProviderInstance;
893 }),
894};