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

driver.ts

902 lines32.6 KB

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