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

driver.ts

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