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