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

driver.ts

901 lines33.5 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​
122export function 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: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
468 Effect.gen(function* () {
469 const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog;
470 const runtimeCoordinator = yield* Effect.serviceOption(
471 AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
472 );
473 if (Option.isSome(runtimeCoordinator)) {
474 yield* runtimeCoordinator.value.clearAvailableCommands(instanceId);
475 yield* runtimeCoordinator.value.clearLiveConfiguration(instanceId);
476 yield* Effect.addFinalizer(() =>
477 runtimeCoordinator.value
478 .clearAvailableCommands(instanceId)
479 .pipe(Effect.andThen(runtimeCoordinator.value.clearLiveConfiguration(instanceId))),
480 );
481 }
482 const crypto = yield* Crypto.Crypto;
483 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
484 const hostEnvironment = yield* HostProcess.Environment;
485 const host = yield* ProviderHost.ProviderHost;
486 const continuationIdentity = defaultProviderContinuationIdentity({
487 driverKind: DRIVER_KIND,
488 instanceId,
489 });
490 const identity = {
491 instanceId,
492 displayName,
493 accentColor,
494 continuationKey: continuationIdentity.continuationKey,
495 };
496 const effectiveConfig = { ...config, enabled } satisfies AcpRegistrySettings;
497 const processEnvironment = yield* mergeProviderInstanceEnvironment(
498 environment,
499 hostEnvironment,
500 );
501 const orchestrationAdapter = yield* AcpRegistryAdapterV2Driver.create({
502 instanceId,
503 displayName,
504 accentColor,
505 environment,
506 enabled,
507 config,
508 }).pipe(
509 Effect.mapError(
510 (cause) =>
511 new ProviderDriverError({
512 driver: DRIVER_KIND,
513 instanceId,
514 detail: "Failed to build ACP Registry orchestration adapter.",
515 cause,
516 }),
517 ),
518 );
519 const readinessInput = {
520 ...identity,
521 settings: effectiveConfig,
522 environment: processEnvironment,
523 };
524 const confirmedAuthentication =
525 yield* AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({
526 cacheDir: host.paths.providerStatusCacheDir,
527 instanceId,
528 settings: effectiveConfig,
529 environment,
530 processEnvironment,
531 });
532 const withLiveRuntimeState = (input: ServerProvider) =>
533 Effect.gen(function* () {
534 if (input.auth.status === "unauthenticated") yield* confirmedAuthentication.set(false);
535 const provider =
536 input.enabled &&
537 input.installed &&
538 input.auth.status === "unknown" &&
539 (yield* confirmedAuthentication.get)
540 ? { ...input, auth: { ...input.auth, status: "authenticated" as const } }
541 : input;
542 return yield* Option.isNone(runtimeCoordinator)
543 ? Effect.succeed(provider)
544 : Effect.all({
545 commands: runtimeCoordinator.value.getAvailableCommands(instanceId),
546 configuration: runtimeCoordinator.value.getLiveConfiguration(instanceId),
547 authAction: runtimeCoordinator.value.getUrlAuthAction(instanceId),
548 }).pipe(
549 Effect.map(({ commands, configuration, authAction }) => {
550 const withCommands = applyAcpRegistryAvailableCommands(provider, commands);
551 const withConfiguration = Option.match(configuration, {
552 onNone: () => withCommands,
553 onSome: (liveConfiguration) =>
554 applyAcpRegistryLiveConfiguration(
555 withCommands,
556 liveConfiguration,
557 effectiveConfig.customModels,
558 ),
559 });
560 return applyAcpRegistryUrlAuthAction(withConfiguration, authAction);
561 }),
562 );
563 });
564 const checkProvider = checkAcpRegistryProviderReadiness(readinessInput).pipe(
565 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
566 Effect.flatMap(withLiveRuntimeState),
567 );
568 const enrichProvider = checkAcpRegistryProviderStatus(
569 {
570 ...readinessInput,
571 cwd: host.paths.cwd,
572 },
573 probeAcpRegistryConfiguration,
574 ).pipe(
575 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
576 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
577 Effect.provideService(Crypto.Crypto, crypto),
578 );
579 const enrichmentCache = yield* Ref.make<{
580 readonly generation: number;
581 readonly entry: {
582 readonly provider: ServerProvider;
583 readonly expiresAt: number;
584 } | null;
585 }>({ generation: 0, entry: null });
586 const liveSnapshotSemaphore = yield* Semaphore.make(1);
587 const invalidateEnrichmentCache = Ref.update(enrichmentCache, (current) => ({
588 generation: current.generation + 1,
589 entry: null,
590 }));
591 const enrichProviderCached = (baseSnapshot: ServerProvider) =>
592 Effect.gen(function* () {
593 const now = yield* Clock.currentTimeMillis;
594 const cacheState = yield* Ref.get(enrichmentCache);
595 const cached = cacheState.entry;
596 if (
597 cached !== null &&
598 cached.expiresAt > now &&
599 cached.provider.version === baseSnapshot.version
600 ) {
601 return {
602 provider: { ...cached.provider, checkedAt: baseSnapshot.checkedAt },
603 generation: cacheState.generation,
604 };
605 }
606 const enriched = yield* enrichProvider;
607 if (enriched.status === "ready") {
608 yield* Ref.update(enrichmentCache, (current) =>
609 current.generation === cacheState.generation
610 ? {
611 ...current,
612 entry: {
613 provider: enriched,
614 expiresAt: now + PROBE_SUCCESS_TTL_MS,
615 },
616 }
617 : current,
618 );
619 }
620 return { provider: enriched, generation: cacheState.generation };
621 });
622 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
623 const snapshot = yield* makeManagedServerProvider<
624 ProviderSnapshotSettings<AcpRegistrySettings>
625 >({
626 resolveMaintenance: () => Effect.succeed(MAINTENANCE),
627 getSettings: snapshotSettings.getSettings,
628 streamSettings: snapshotSettings.streamSettings,
629 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
630 initialSnapshot: () => checkProvider,
631 checkProvider,
632 enrichSnapshot: ({ snapshot, getSnapshot, publishSnapshot }) => {
633 if (!snapshot.installed) return Effect.void;
634 const publishEnrichment = (
635 Option.isSome(runtimeCoordinator)
636 ? runtimeCoordinator.value.runBackgroundProbe(
637 effectiveConfig.source === "local"
638 ? `local:${instanceId}`
639 : effectiveConfig.agentId,
640 enrichProviderCached(snapshot),
641 )
642 : enrichProviderCached(snapshot).pipe(Effect.map(Option.some))
643 ).pipe(
644 Effect.flatMap(
645 Option.match({
646 onNone: () => Effect.void,
647 onSome: ({ provider, generation }) =>
648 liveSnapshotSemaphore.withPermit(
649 Ref.get(enrichmentCache).pipe(
650 Effect.flatMap((current) =>
651 current.generation === generation
652 ? withLiveRuntimeState(provider).pipe(Effect.flatMap(publishSnapshot))
653 : Effect.void,
654 ),
655 ),
656 ),
657 }),
658 ),
659 );
660 if (Option.isNone(runtimeCoordinator)) return publishEnrichment;
661​
662 const publishLiveCommands = runtimeCoordinator.value.watchAvailableCommands(
663 instanceId,
664 ({ slashCommands, skills }) =>
665 liveSnapshotSemaphore.withPermit(
666 getSnapshot.pipe(
667 Effect.flatMap((current) =>
668 publishSnapshot({
669 ...current,
670 slashCommands,
671 skills,
672 }),
673 ),
674 ),
675 ),
676 );
677 const publishLiveConfiguration = runtimeCoordinator.value.watchLiveConfiguration(
678 instanceId,
679 (configuration) =>
680 liveSnapshotSemaphore.withPermit(
681 getSnapshot.pipe(
682 Effect.flatMap((current) =>
683 publishSnapshot(
684 applyAcpRegistryLiveConfiguration(
685 current,
686 configuration,
687 effectiveConfig.customModels,
688 ),
689 ),
690 ),
691 ),
692 ),
693 );
694 const publishUrlAuthAction = runtimeCoordinator.value.watchUrlAuthAction(
695 instanceId,
696 (action) =>
697 liveSnapshotSemaphore.withPermit(
698 getSnapshot.pipe(
699 Effect.flatMap((current) =>
700 publishSnapshot(
701 applyAcpRegistryUrlAuthAction(current, Option.fromNullishOr(action)),
702 ),
703 ),
704 ),
705 ),
706 );
707 return Effect.all(
708 [
709 publishEnrichment,
710 publishLiveCommands,
711 publishLiveConfiguration,
712 publishUrlAuthAction,
713 ],
714 {
715 concurrency: "unbounded",
716 discard: true,
717 },
718 );
719 },
720 }).pipe(
721 Effect.mapError(
722 (cause) =>
723 new ProviderDriverError({
724 driver: DRIVER_KIND,
725 instanceId,
726 detail: "Failed to build the ACP Registry provider snapshot.",
727 cause,
728 }),
729 ),
730 );
731​
732 const provideAcpManagementServices = <A, E>(
733 effect: Effect.Effect<
734 A,
735 E,
736 | AcpRegistrySupport.AcpRegistryCatalog
737 | ChildProcessSpawner.ChildProcessSpawner
738 | Crypto.Crypto
739 >,
740 ): Effect.Effect<A, E> => {
741 const provided = effect.pipe(
742 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
743 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
744 Effect.provideService(Crypto.Crypto, crypto),
745 );
746 return Option.isSome(runtimeCoordinator)
747 ? provided.pipe(
748 Effect.provideService(
749 AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
750 runtimeCoordinator.value,
751 ),
752 )
753 : provided;
754 };
755​
756 const clearLiveState = Option.isSome(runtimeCoordinator)
757 ? runtimeCoordinator.value
758 .clearLiveConfiguration(instanceId)
759 .pipe(Effect.andThen(runtimeCoordinator.value.clearAvailableCommands(instanceId)))
760 : Effect.void;
761 const controller = yield* AcpRegistryAuth.makeAcpRegistryAuth({
762 instanceId,
763 settings: effectiveConfig,
764 cwd: host.paths.cwd,
765 environment: processEnvironment,
766 onChanged: (authenticated) =>
767 confirmedAuthentication
768 .set(authenticated)
769 .pipe(
770 Effect.andThen(authenticated ? Effect.void : clearLiveState),
771 Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)),
772 Effect.andThen(snapshot.refresh),
773 Effect.asVoid,
774 ),
775 }).pipe(
776 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
777 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
778 Effect.provideService(Crypto.Crypto, crypto),
779 );
780 const auth = {
781 ...controller,
782 invalidate: (controller.invalidate ?? Effect.void).pipe(
783 Effect.andThen(confirmedAuthentication.set(false)),
784 Effect.andThen(clearLiveState),
785 Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)),
786 Effect.andThen(snapshot.refresh),
787 Effect.asVoid,
788 ),
789 };
790​
791 return {
792 instanceId,
793 driverKind: DRIVER_KIND,
794 continuationIdentity,
795 displayName,
796 accentColor,
797 enabled,
798 auth,
799 snapshot: {
800 ...snapshot,
801 refresh: snapshot.refresh.pipe(
802 Effect.tap(() => controller.refreshMethods ?? Effect.void),
803 ),
804 },
805 orchestrationAdapter,
806 textGeneration: makeUnsupportedTextGeneration(),
807 acpSessionManagement: {
808 listSessions: ({ cwd, cursor }) =>
809 provideAcpManagementServices(
810 listAcpRegistrySessions({
811 instanceId,
812 settings: effectiveConfig,
813 cwd,
814 environment: processEnvironment,
815 ...(cursor === undefined ? {} : { cursor }),
816 }),
817 ),
818 deleteSession: ({ cwd, sessionId }) =>
819 provideAcpManagementServices(
820 deleteAcpRegistrySession({
821 instanceId,
822 settings: effectiveConfig,
823 cwd,
824 environment: processEnvironment,
825 sessionId,
826 }),
827 ),
828 listProviders: (cwd) =>
829 provideAcpManagementServices(
830 listAcpRegistryProviders({
831 instanceId,
832 settings: effectiveConfig,
833 cwd,
834 environment: processEnvironment,
835 }),
836 ),
837 setProvider: ({ cwd, providerId, apiType, baseUrl, headers }) =>
838 provideAcpManagementServices(
839 setAcpRegistryProvider({
840 instanceId,
841 settings: effectiveConfig,
842 cwd,
843 environment: processEnvironment,
844 providerId,
845 apiType,
846 baseUrl,
847 ...(headers === undefined ? {} : { headers }),
848 }),
849 ).pipe(Effect.tap(() => liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache))),
850 disableProvider: ({ cwd, providerId }) =>
851 provideAcpManagementServices(
852 disableAcpRegistryProvider({
853 instanceId,
854 settings: effectiveConfig,
855 cwd,
856 environment: processEnvironment,
857 providerId,
858 }),
859 ).pipe(Effect.tap(() => liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache))),
860 logout: (cwd) => {
861 const logout = logoutAcpRegistry({
862 instanceId,
863 settings: effectiveConfig,
864 cwd,
865 environment: processEnvironment,
866 }).pipe(
867 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
868 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
869 Effect.provideService(Crypto.Crypto, crypto),
870 Effect.tap(() => confirmedAuthentication.set(false)),
871 Effect.tap(() =>
872 liveSnapshotSemaphore.withPermit(
873 invalidateEnrichmentCache.pipe(
874 Effect.andThen(
875 Option.isSome(runtimeCoordinator)
876 ? Effect.all(
877 [
878 runtimeCoordinator.value.clearAvailableCommands(instanceId),
879 runtimeCoordinator.value.clearLiveConfiguration(instanceId),
880 ],
881 { concurrency: "unbounded", discard: true },
882 )
883 : Effect.void,
884 ),
885 ),
886 ),
887 ),
888 );
889 return Option.isSome(runtimeCoordinator)
890 ? logout.pipe(
891 Effect.provideService(
892 AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
893 runtimeCoordinator.value,
894 ),
895 )
896 : logout;
897 },
898 },
899 } satisfies ProviderInstance;
900 }),
901};