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

driver.ts

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