Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AcpRegistryDriver.ts

911 lines34.0 KB

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