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