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: Effect.fn("enrichSnapshot")(function ({
633 snapshot,
634 getSnapshot,
635 publishSnapshot,
636 }) {
637 if (!snapshot.installed) return Effect.void;
638 const publishEnrichment = (
639 Option.isSome(runtimeCoordinator)
640 ? runtimeCoordinator.value.runBackgroundProbe(
641 effectiveConfig.source === "local"
642 ? `local:${instanceId}`
643 : effectiveConfig.agentId,
644 enrichProviderCached(snapshot),
645 )
646 : enrichProviderCached(snapshot).pipe(Effect.asSome)
647 ).pipe(
648 Effect.flatMap(
649 Option.match({
650 onNone: () => Effect.void,
651 onSome: ({ provider, generation }) =>
652 liveSnapshotSemaphore.withPermit(
653 Ref.get(enrichmentCache).pipe(
654 Effect.flatMap((current) =>
655 current.generation === generation
656 ? withLiveRuntimeState(provider).pipe(Effect.flatMap(publishSnapshot))
657 : Effect.void,
658 ),
659 ),
660 ),
661 }),
662 ),
663 );
664 if (Option.isNone(runtimeCoordinator)) return publishEnrichment;
665
666 const publishLiveCommands = runtimeCoordinator.value.watchAvailableCommands(
667 instanceId,
668 ({ slashCommands, skills }) =>
669 liveSnapshotSemaphore.withPermit(
670 getSnapshot.pipe(
671 Effect.flatMap((current) =>
672 publishSnapshot({
673 ...current,
674 slashCommands,
675 skills,
676 }),
677 ),
678 ),
679 ),
680 );
681 const publishLiveConfiguration = runtimeCoordinator.value.watchLiveConfiguration(
682 instanceId,
683 (configuration) =>
684 liveSnapshotSemaphore.withPermit(
685 getSnapshot.pipe(
686 Effect.flatMap((current) =>
687 publishSnapshot(
688 applyAcpRegistryLiveConfiguration(
689 current,
690 configuration,
691 effectiveConfig.customModels,
692 ),
693 ),
694 ),
695 ),
696 ),
697 );
698 const publishUrlAuthAction = runtimeCoordinator.value.watchUrlAuthAction(
699 instanceId,
700 (action) =>
701 liveSnapshotSemaphore.withPermit(
702 getSnapshot.pipe(
703 Effect.flatMap((current) =>
704 publishSnapshot(
705 applyAcpRegistryUrlAuthAction(current, Option.fromNullishOr(action)),
706 ),
707 ),
708 ),
709 ),
710 );
711 return Effect.all(
712 [publishEnrichment, publishLiveCommands, publishLiveConfiguration, publishUrlAuthAction],
713 {
714 concurrency: "unbounded",
715 discard: true,
716 },
717 );
718 }),
719 }).pipe(
720 Effect.mapError(
721 (cause) =>
722 new ProviderDriverError({
723 driver: DRIVER_KIND,
724 instanceId,
725 detail: "Failed to build the ACP Registry provider snapshot.",
726 cause,
727 }),
728 ),
729 );
730
731 const provideAcpManagementServices = <A, E>(
732 effect: Effect.Effect<
733 A,
734 E,
735 | AcpRegistrySupport.AcpRegistryCatalog
736 | ChildProcessSpawner.ChildProcessSpawner
737 | Crypto.Crypto
738 >,
739 ): Effect.Effect<A, E> => {
740 const provided = effect.pipe(
741 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
742 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
743 Effect.provideService(Crypto.Crypto, crypto),
744 );
745 return Option.isSome(runtimeCoordinator)
746 ? provided.pipe(
747 Effect.provideService(
748 AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
749 runtimeCoordinator.value,
750 ),
751 )
752 : provided;
753 };
754
755 const clearLiveState = Option.isSome(runtimeCoordinator)
756 ? runtimeCoordinator.value
757 .clearLiveConfiguration(instanceId)
758 .pipe(Effect.andThen(runtimeCoordinator.value.clearAvailableCommands(instanceId)))
759 : Effect.void;
760 const controller = yield* AcpRegistryAuth.makeAcpRegistryAuth({
761 instanceId,
762 settings: effectiveConfig,
763 cwd: host.paths.cwd,
764 environment: processEnvironment,
765 onChanged: (authenticated) =>
766 confirmedAuthentication
767 .set(authenticated)
768 .pipe(
769 Effect.andThen(authenticated ? Effect.void : clearLiveState),
770 Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)),
771 Effect.andThen(snapshot.refresh),
772 Effect.asVoid,
773 ),
774 }).pipe(
775 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
776 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
777 Effect.provideService(Crypto.Crypto, crypto),
778 );
779 const auth = {
780 ...controller,
781 invalidate: (controller.invalidate ?? Effect.void).pipe(
782 Effect.andThen(confirmedAuthentication.set(false)),
783 Effect.andThen(clearLiveState),
784 Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)),
785 Effect.andThen(snapshot.refresh),
786 Effect.asVoid,
787 ),
788 };
789
790 return {
791 instanceId,
792 driverKind: DRIVER_KIND,
793 continuationIdentity,
794 displayName,
795 accentColor,
796 enabled,
797 auth,
798 snapshot: {
799 ...snapshot,
800 refresh: snapshot.refresh.pipe(Effect.tap(() => controller.refreshMethods ?? Effect.void)),
801 },
802 orchestrationAdapter,
803 textGeneration: makeUnsupportedTextGeneration(),
804 acpSessionManagement: {
805 listSessions: ({ cwd, cursor }) =>
806 provideAcpManagementServices(
807 listAcpRegistrySessions({
808 instanceId,
809 settings: effectiveConfig,
810 cwd,
811 environment: processEnvironment,
812 ...(cursor === undefined ? {} : { cursor }),
813 }),
814 ),
815 deleteSession: ({ cwd, sessionId }) =>
816 provideAcpManagementServices(
817 deleteAcpRegistrySession({
818 instanceId,
819 settings: effectiveConfig,
820 cwd,
821 environment: processEnvironment,
822 sessionId,
823 }),
824 ),
825 listProviders: (cwd) =>
826 provideAcpManagementServices(
827 listAcpRegistryProviders({
828 instanceId,
829 settings: effectiveConfig,
830 cwd,
831 environment: processEnvironment,
832 }),
833 ),
834 setProvider: ({ cwd, providerId, apiType, baseUrl, headers }) =>
835 provideAcpManagementServices(
836 setAcpRegistryProvider({
837 instanceId,
838 settings: effectiveConfig,
839 cwd,
840 environment: processEnvironment,
841 providerId,
842 apiType,
843 baseUrl,
844 ...(headers === undefined ? {} : { headers }),
845 }),
846 ).pipe(Effect.tap(() => liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache))),
847 disableProvider: ({ cwd, providerId }) =>
848 provideAcpManagementServices(
849 disableAcpRegistryProvider({
850 instanceId,
851 settings: effectiveConfig,
852 cwd,
853 environment: processEnvironment,
854 providerId,
855 }),
856 ).pipe(Effect.tap(() => liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache))),
857 logout: (cwd) => {
858 const logout = logoutAcpRegistry({
859 instanceId,
860 settings: effectiveConfig,
861 cwd,
862 environment: processEnvironment,
863 }).pipe(
864 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
865 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
866 Effect.provideService(Crypto.Crypto, crypto),
867 Effect.tap(() => confirmedAuthentication.set(false)),
868 Effect.tap(() =>
869 liveSnapshotSemaphore.withPermit(
870 invalidateEnrichmentCache.pipe(
871 Effect.andThen(
872 Option.isSome(runtimeCoordinator)
873 ? Effect.all(
874 [
875 runtimeCoordinator.value.clearAvailableCommands(instanceId),
876 runtimeCoordinator.value.clearLiveConfiguration(instanceId),
877 ],
878 { concurrency: "unbounded", discard: true },
879 )
880 : Effect.void,
881 ),
882 ),
883 ),
884 ),
885 );
886 return Option.isSome(runtimeCoordinator)
887 ? logout.pipe(
888 Effect.provideService(
889 AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
890 runtimeCoordinator.value,
891 ),
892 )
893 : logout;
894 },
895 },
896 } satisfies ProviderInstance;
897 }),
898};