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