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