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

AcpRegistryDriver.ts

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