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