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

AcpRegistryDriver.ts

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