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