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

driver.ts

1,103 lines40.4 KB

1import {
2 officialAcpRegistryIconUrlForAgentId,
3 ProviderDriverKind,
4 resolveOfficialAcpRegistryIconUrl,
5 TextGenerationError,
6 type AcpRegistryOperationError,
7 type AcpRegistryProbeModel,
8 type CustomModelSetting,
9 type ServerProvider,
10 type ServerProviderModel,
11} from "@t3tools/contracts";
12import { AcpRegistrySettings } from "../settings.ts";
13import * as HostProcess from "@t3tools/shared/HostProcess";
14import { createModelCapabilities } from "@t3tools/shared/model";
15import * as Clock from "effect/Clock";
16import * as Digest from "effect/crypto/Digest";
17import * as SecureRandom from "effect/crypto/SecureRandom";
18import * as DateTime from "effect/DateTime";
19import * as Effect from "effect/Effect";
20import * as Equal from "effect/Equal";
21import * as Option from "effect/Option";
22import * as Ref from "effect/Ref";
23import * as Result from "effect/Result";
24import * as Schema from "effect/Schema";
25import * as Semaphore from "effect/Semaphore";
26import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
27​
28import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
29import { AcpRegistryAdapterV2Driver, type AcpRegistryAdapterV2DriverEnv } from "./adapter.ts";
30import type { ProviderTextGeneration } from "@t3tools/provider-core/server/textGeneration";
31import { ProviderDriverError } from "@t3tools/provider-core/server/errors";
32import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
33import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
34import {
35 defaultProviderContinuationIdentity,
36 type ProviderDriver,
37 type ProviderInstance,
38} from "@t3tools/provider-core/server/driver";
39import {
40 providerModelsFromSettings,
41 providerProbeEnvironment,
42} from "@t3tools/provider-core/server/snapshotProbe";
43import { makeManualOnlyProviderMaintenanceCapabilities } from "@t3tools/provider-core/server/maintenanceResolver";
44import {
45 haveProviderSnapshotSettingsChanged,
46 makeProviderSnapshotSettingsSource,
47 type ProviderSnapshotSettings,
48} from "@t3tools/provider-core/server/snapshotSettings";
49import {
50 type AcpRegistryAvailableCommands,
51 type AcpRegistryConfigurationProbe,
52 type AcpRegistryConfigurationProbeResult,
53 type AcpRegistryLiveConfiguration,
54 deleteAcpRegistrySession,
55 disableAcpRegistryProvider,
56 listAcpRegistrySessions,
57 listAcpRegistryProviders,
58 logoutAcpRegistry,
59 probeAcpRegistryConfiguration,
60 setAcpRegistryProvider,
61} from "./probe.ts";
62import * as AcpRegistrySupport from "./AcpRegistrySupport.ts";
63import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts";
64import * as AcpRegistryAuth from "./auth.ts";
65import * as AcpRegistryAuthenticationState from "./authenticationState.ts";
66​
67const DRIVER_KIND = ProviderDriverKind.make("acpRegistry");
68const decodeSettings = Schema.decodeSync(AcpRegistrySettings);
69// Cache only successful authenticated probes so sign-in changes remain visible.
70const PROBE_SUCCESS_TTL_MS = 15 * 60 * 1_000;
71const PROBE_PROVISIONAL_TTL_MS = 30 * 1_000;
72​
73function acpRegistryProbeTtlMs(provider: ServerProvider): number {
74 const discoveredModels = provider.models.filter((model) => !model.isCustom);
75 return discoveredModels.length <= 1 ? PROBE_PROVISIONAL_TTL_MS : PROBE_SUCCESS_TTL_MS;
77​
78interface AcpRegistryEnrichmentCache {
79 readonly generation: number;
80 readonly entry: {
81 readonly provider: ServerProvider;
82 readonly expiresAt: number;
83 } | null;
85​
86export function isAcpRegistryCacheValid(
87 entry: NonNullable<AcpRegistryEnrichmentCache["entry"]>,
88 inspectedVersion: string | null,
89 local: boolean,
90 now: number,
91): boolean {
92 return (
93 entry.expiresAt > now &&
94 ((local && inspectedVersion === null) || entry.provider.version === inspectedVersion)
95 );
97​
98export function updateAcpRegistryEnrichmentCache(input: {
99 readonly cache: AcpRegistryEnrichmentCache;
100 readonly configuration: AcpRegistryLiveConfiguration;
101 readonly customModels: ReadonlyArray<CustomModelSetting>;
102 readonly now: number;
103}): AcpRegistryEnrichmentCache {
104 const { cache, configuration, customModels, now } = input;
105 if (cache.entry === null) {
106 // No probe has landed yet, but the live session published its
107 // configuration to the snapshot. Advance the cache epoch so a probe that
108 // was still in flight cannot overwrite that newer state when it lands.
109 return { ...cache, generation: cache.generation + 1 };
110 }
111 const provider = applyAcpRegistryLiveConfiguration(
112 cache.entry.provider,
113 configuration,
114 customModels,
115 );
116 if (Equal.equals(provider, cache.entry.provider)) return cache;
117 return {
118 ...cache,
119 // The live session advanced the provider past what an in-flight probe
120 // started from; bump the epoch so the probe discards its stale result
121 // instead of overwriting this entry and publishing it.
122 generation: cache.generation + 1,
123 entry: {
124 ...cache.entry,
125 provider,
126 expiresAt: now + acpRegistryProbeTtlMs(provider),
127 },
128 };
130const EMPTY_CAPABILITIES = createModelCapabilities({ optionDescriptors: [] });
131const MAINTENANCE = makeManualOnlyProviderMaintenanceCapabilities({
132 provider: DRIVER_KIND,
133 packageName: null,
134});
135​
136const makeUnsupportedTextGeneration = (): ProviderTextGeneration => {
137 const unsupported = (operation: string) =>
138 Effect.fail(
139 new TextGenerationError({
140 operation,
141 detail: "ACP Registry instances do not provide application text generation.",
142 }),
143 );
144 return {
145 generateCommitMessage: () => unsupported("generateCommitMessage"),
146 generatePrContent: () => unsupported("generatePrContent"),
147 generateBranchName: () => unsupported("generateBranchName"),
148 generateThreadTitle: () => unsupported("generateThreadTitle"),
149 generateReviewGuide: () => unsupported("generateReviewGuide"),
150 generateTranscriptionPostProcessing: () => unsupported("generateTranscriptionPostProcessing"),
151 };
152};
153​
154function modelsFromDiscovery(
155 discovery:
156 | Pick<
157 AcpRegistryLiveConfiguration,
158 "models" | "currentModelId" | "configOptions" | "modelOptionIds"
159 >
160 | undefined,
161 customModels: ReadonlyArray<CustomModelSetting>,
162 previousModels: ReadonlyArray<ServerProviderModel> = [],
163): ReadonlyArray<ServerProviderModel> {
164 const discovered = discovery?.models ?? [];
165 const capabilities =
166 discovery === undefined || discovery.configOptions.length === 0
167 ? EMPTY_CAPABILITIES
168 : createModelCapabilities({ optionDescriptors: discovery.configOptions });
169 // Model-specific options describe only the session's current model; other
170 // models keep the shared ones plus what an earlier session reported for them.
171 const modelOptionIds = new Set(discovery?.modelOptionIds ?? []);
172 const shared = (discovery?.configOptions ?? []).filter(
173 (descriptor) => !modelOptionIds.has(descriptor.id),
174 );
175 const sharedIds = new Set(shared.map((descriptor) => descriptor.id));
176 const capabilitiesFor = ({ id: slug, reasoningEffort }: AcpRegistryProbeModel) => {
177 if (slug === discovery?.currentModelId) return capabilities;
178 // The levels a model advertises replace the ones an earlier session reported.
179 const own = (
180 previousModels.find((model) => model.slug === slug)?.capabilities?.optionDescriptors ?? []
181 ).filter(
182 (descriptor) =>
183 !sharedIds.has(descriptor.id) &&
184 (reasoningEffort === undefined ||
185 descriptor.type !== "select" ||
186 descriptor.role !== "reasoning"),
187 );
188 const optionDescriptors = [...shared, ...own, ...(reasoningEffort ? [reasoningEffort] : [])];
189 return optionDescriptors.length === 0
190 ? EMPTY_CAPABILITIES
191 : createModelCapabilities({ optionDescriptors });
192 };
193 const builtInModels: ReadonlyArray<ServerProviderModel> =
194 discovered.length === 0
195 ? [
196 {
197 slug: "default",
198 name: "Default",
199 isCustom: false,
200 isDefault: true,
201 capabilities,
202 },
203 ]
204 : discovered.map((model) => ({
205 slug: model.id,
206 name: model.name,
207 isCustom: false,
208 ...(model.id === discovery?.currentModelId ? { isDefault: true } : {}),
209 capabilities: capabilitiesFor(model),
210 }));
211 return providerModelsFromSettings(builtInModels, customModels, capabilities);
213​
214function acpRegistrySnapshotReadiness(
215 inspection:
216 | AcpRegistrySupport.AcpRegistryInspection
217 | { readonly status: "failed"; readonly message: string },
218): Pick<ServerProvider, "installed" | "version" | "status" | "message"> {
219 switch (inspection.status) {
220 case "ready":
221 return { installed: true, version: inspection.version, status: "ready" };
222 case "unconfigured":
223 return {
224 installed: false,
225 version: null,
226 status: "warning",
227 message:
228 "Select an ACP Registry agent or configure a local ACP executable before starting a thread.",
229 };
230 case "not_found":
231 return {
232 installed: false,
233 version: null,
234 status: "error",
235 message: `ACP Registry does not contain agent '${inspection.agentId}'.`,
236 };
237 case "unsupported":
238 return {
239 installed: false,
240 version: inspection.version,
241 status: "error",
242 message: `ACP Registry agent '${inspection.agentId}' has no compatible distribution for this environment.`,
243 };
244 case "missing_runner":
245 return {
246 installed: false,
247 version: inspection.version,
248 status: "error",
249 message:
250 inspection.distribution === "local"
251 ? "Local ACP executable is not available on this environment's PATH."
252 : `ACP executable '${inspection.runner}' is not available on this environment's PATH.`,
253 };
254 case "unprepared":
255 return {
256 installed: false,
257 version: inspection.version,
258 status: "warning",
259 message: `ACP Registry agent '${inspection.agentId}' has not been prepared on this environment.`,
260 };
261 case "failed":
262 return {
263 installed: false,
264 version: null,
265 status: "error",
266 message: inspection.message,
267 };
268 }
270​
271interface SnapshotIdentity {
272 readonly instanceId: ProviderInstance["instanceId"];
273 readonly displayName: string | undefined;
274 readonly accentColor: string | undefined;
275 readonly continuationKey: string;
277​
278function baseSnapshot(
279 input: SnapshotIdentity & {
280 readonly settings: AcpRegistrySettings;
281 readonly checkedAt: string;
282 readonly installed: boolean;
283 readonly version: string | null;
284 readonly status: ServerProvider["status"];
285 readonly auth: ServerProvider["auth"];
286 readonly documentationUrl?: string;
287 readonly message?: string;
288 readonly probe?: AcpRegistryConfigurationProbeResult;
289 readonly probeError?: AcpRegistryOperationError;
290 },
291): ServerProvider {
292 const iconUrl =
293 input.settings.source === "local"
294 ? null
295 : (resolveOfficialAcpRegistryIconUrl(input.probe?.probe.icon) ??
296 officialAcpRegistryIconUrlForAgentId(input.settings.agentId));
297 return {
298 instanceId: input.instanceId,
299 driver: DRIVER_KIND,
300 ...(input.displayName ? { displayName: input.displayName } : {}),
301 ...(input.accentColor ? { accentColor: input.accentColor } : {}),
302 ...(iconUrl ? { iconUrl } : {}),
303 continuation: { groupKey: input.continuationKey },
304 supportsTextGeneration: false,
305 enabled: input.settings.enabled,
306 installed: input.installed,
307 version: input.version,
308 status: input.settings.enabled ? input.status : "disabled",
309 auth: { ...input.auth, canLogout: input.auth.canLogout ?? false },
310 checkedAt: input.checkedAt,
311 setup: {
312 canInstall: false,
313 ...(input.documentationUrl ? { documentationUrl: input.documentationUrl } : {}),
314 canAuthenticate:
315 input.installed &&
316 (input.probe
317 ? input.probe.probe.authMethods.length > 0
318 : input.settings.source === "local"
319 ? (input.probeError?.authMethods?.length ?? 0) > 0
320 : input.settings.agentId.length > 0),
321 },
322 ...(input.message ? { message: input.message } : {}),
323 models: modelsFromDiscovery(input.probe?.probe, input.settings.customModels),
324 ...(input.probe === undefined
325 ? {}
326 : {
327 nativeSessions: {
328 canList: input.probe.probe.sessionManagement.canList,
329 canLoad: input.probe.probe.sessionManagement.canLoad,
330 canResume: input.probe.probe.sessionManagement.canResume,
331 canDelete: input.probe.probe.sessionManagement.canDelete,
332 },
333 configurableProviders: input.probe.probe.sessionManagement.canConfigureProviders,
334 }),
335 slashCommands: input.probe?.slashCommands ?? [],
336 skills: input.probe?.skills ?? [],
337 };
339​
340export function applyAcpRegistryAvailableCommands(
341 provider: ServerProvider,
342 commands: Option.Option<AcpRegistryAvailableCommands>,
343): ServerProvider {
344 return Option.match(commands, {
345 onNone: () => provider,
346 onSome: ({ slashCommands, skills }) => ({ ...provider, slashCommands, skills }),
347 });
349​
350export function applyAcpRegistryLiveConfiguration(
351 provider: ServerProvider,
352 configuration: AcpRegistryLiveConfiguration,
353 customModels: ReadonlyArray<CustomModelSetting>,
354 previousModels: ReadonlyArray<ServerProviderModel> = provider.models,
355): ServerProvider {
356 const { message: _staleProbeMessage, ...snapshot } = provider;
357 // session/load may omit models (Kimi returns `{}`); keep the probed list
358 // and apply any live option descriptors to it.
359 const probedModels = provider.models.filter((model) => !model.isCustom);
360 // A cold-start session can report one placeholder model before its catalog
361 // settles, while the probe may already have observed the full catalog. A
362 // single model enumerated by an explicit select is not that fallback but
363 // the agent's deliberate statement, so it wins over the probe catalog.
364 const liveCatalogIsProvisional =
365 configuration.models.length === 1 &&
366 !configuration.modelsFromModelSelect &&
367 probedModels.length > 1;
368 const useLiveCatalog =
369 configuration.models.length > 1 ||
370 (configuration.models.length === 1 && !liveCatalogIsProvisional);
371 const selectedProbedModelId =
372 configuration.currentModelId !== null &&
373 probedModels.some((model) => model.slug === configuration.currentModelId)
374 ? configuration.currentModelId
375 : (probedModels.find((model) => model.isDefault)?.slug ?? null);
376 const discovery = useLiveCatalog
377 ? configuration
378 : {
379 ...configuration,
380 models: probedModels.map((model) => ({
381 id: model.slug,
382 name: model.name,
383 description: null,
384 })),
385 currentModelId: selectedProbedModelId,
386 };
387 return {
388 ...snapshot,
389 status: provider.enabled ? "ready" : provider.status,
390 models:
391 !useLiveCatalog && configuration.configOptions.length === 0
392 ? withAcpRegistryDefaultModel(provider.models, selectedProbedModelId)
393 : modelsFromDiscovery(
394 discovery,
395 customModels,
396 previousModels.filter((model) => !model.isCustom),
397 ),
398 };
400​
401function withAcpRegistryDefaultModel(
402 models: ReadonlyArray<ServerProviderModel>,
403 currentModelId: string | null,
404): ReadonlyArray<ServerProviderModel> {
405 if (currentModelId === null) return models;
406 let changed = false;
407 const next = models.map((model) => {
408 if (model.isCustom) return model;
409 const isDefault = model.slug === currentModelId;
410 if ((model.isDefault ?? false) === isDefault) return model;
411 changed = true;
412 const { isDefault: _previous, ...rest } = model;
413 return isDefault ? { ...rest, isDefault: true } : rest;
414 });
415 return changed ? next : models;
417​
418function applyAcpRegistryUrlAuthAction(
419 provider: ServerProvider,
420 action: Option.Option<NonNullable<ServerProvider["auth"]["action"]>>,
421): ServerProvider {
422 const { action: _previousAction, ...auth } = provider.auth;
423 return {
424 ...provider,
425 auth: Option.match(action, {
426 onNone: () => auth,
427 onSome: (nextAction) => ({ ...auth, action: nextAction }),
428 }),
429 };
431​
432const buildInitialAcpRegistrySnapshot = Effect.fn("AcpRegistryDriver.buildInitialSnapshot")(
433 function* (input: SnapshotIdentity & { readonly settings: AcpRegistrySettings }) {
434 const checkedAt = DateTime.formatIso(yield* DateTime.now);
435 return baseSnapshot({
436 ...input,
437 checkedAt,
438 installed: false,
439 version: null,
440 status: "warning",
441 auth: { status: "unknown" },
442 message: input.settings.enabled
443 ? "Checking ACP Registry agent readiness..."
444 : "ACP Registry is disabled in T3 Code settings.",
445 });
446 },
447);
448​
449export function buildCheckedAcpRegistrySnapshot(
450 input: SnapshotIdentity & {
451 readonly settings: AcpRegistrySettings;
452 readonly checkedAt: string;
453 readonly inspection:
454 | AcpRegistrySupport.AcpRegistryInspection
455 | { readonly status: "failed"; readonly message: string };
456 readonly probe?: AcpRegistryConfigurationProbeResult;
457 readonly probeError?: AcpRegistryOperationError;
458 },
459): ServerProvider {
460 const readiness = acpRegistrySnapshotReadiness(input.inspection);
461 const probeFailed = input.probeError !== undefined;
462 const advertisedAuthMethod =
463 input.probeError?.reason === "authentication_failed"
464 ? (input.probeError.authMethods?.find(
465 (method) => method.id === input.settings.authMethodId,
466 ) ?? input.probeError.authMethods?.[0])
467 : undefined;
468 const authenticationMessage = advertisedAuthMethod
469 ? advertisedAuthMethod.type === "terminal" && advertisedAuthMethod.command
470 ? `Sign in in provider settings using "${advertisedAuthMethod.name}". The login terminal runs on this environment.`
471 : advertisedAuthMethod.type === "env_var" &&
472 (advertisedAuthMethod.envVarNames?.length ?? 0) > 0
473 ? `Set ${advertisedAuthMethod.envVarNames!.join(", ")} under this instance's environment variables in provider settings. T3 Code will detect it on the next provider refresh.`
474 : `Sign in in provider settings using "${advertisedAuthMethod.name}".`
475 : undefined;
476 return baseSnapshot({
477 ...input,
478 ...(input.inspection.status === "ready" && input.inspection.documentationUrl
479 ? { documentationUrl: input.inspection.documentationUrl }
480 : {}),
481 installed: readiness.installed,
482 version:
483 input.settings.source === "local"
484 ? (input.probe?.probe.agentVersion ?? readiness.version)
485 : readiness.version,
486 // Failed discovery is a warning: an installed agent may still run real turns.
487 status: probeFailed ? "warning" : readiness.status,
488 auth: input.probe
489 ? {
490 // Discovery sessions and an empty auth-method list do not prove sign-in.
491 status: "unknown",
492 canLogout: input.probe.probe.sessionManagement.canLogout,
493 }
494 : input.probeError?.reason === "authentication_failed"
495 ? {
496 status: "unauthenticated",
497 ...(advertisedAuthMethod
498 ? { type: advertisedAuthMethod.type, label: advertisedAuthMethod.name }
499 : {}),
500 ...(input.probeError.authAction === undefined
501 ? {}
502 : { action: input.probeError.authAction }),
503 }
504 : { status: "unknown" },
505 ...(input.probeError
506 ? { message: authenticationMessage ?? input.probeError.message }
507 : readiness.message
508 ? { message: readiness.message }
509 : {}),
510 });
512​
513export const checkAcpRegistryProviderStatus = Effect.fn("AcpRegistryDriver.checkProviderStatus")(
514 function* <Requirements>(
515 input: SnapshotIdentity & {
516 readonly settings: AcpRegistrySettings;
517 readonly cwd: string;
518 readonly environment: NodeJS.ProcessEnv;
519 },
520 probeConfiguration: AcpRegistryConfigurationProbe<Requirements>,
521 ): Effect.fn.Return<ServerProvider, never, AcpRegistrySupport.AcpRegistryCatalog | Requirements> {
522 const checkedAt = DateTime.formatIso(yield* DateTime.now);
523 if (!input.settings.enabled) {
524 return yield* buildInitialAcpRegistrySnapshot(input);
525 }
526 const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog;
527 const inspected = yield* Effect.result(catalog.inspect(input.settings, input.environment));
528 if (Result.isFailure(inspected)) {
529 return buildCheckedAcpRegistrySnapshot({
530 ...input,
531 checkedAt,
532 inspection: {
533 status: "failed",
534 message: `Could not inspect ACP Registry agent: ${inspected.failure.message}`,
535 },
536 });
537 }
538 if (inspected.success.status !== "ready") {
539 return buildCheckedAcpRegistrySnapshot({
540 ...input,
541 checkedAt,
542 inspection: inspected.success,
543 });
544 }
545 const probed = yield* Effect.result(
546 probeConfiguration({
547 instanceId: input.instanceId,
548 settings: input.settings,
549 cwd: input.cwd,
550 environment: providerProbeEnvironment(input.environment),
551 }),
552 );
553 return Result.isFailure(probed)
554 ? buildCheckedAcpRegistrySnapshot({
555 ...input,
556 checkedAt,
557 inspection: inspected.success,
558 probeError: probed.failure,
559 })
560 : buildCheckedAcpRegistrySnapshot({
561 ...input,
562 checkedAt,
563 inspection: inspected.success,
564 probe: probed.success,
565 });
566 },
567);
568​
569export const checkAcpRegistryProviderReadiness = Effect.fn(
570 "AcpRegistryDriver.checkProviderReadiness",
571)(function* (
572 input: SnapshotIdentity & {
573 readonly settings: AcpRegistrySettings;
574 readonly environment: NodeJS.ProcessEnv;
575 },
576): Effect.fn.Return<ServerProvider, never, AcpRegistrySupport.AcpRegistryCatalog> {
577 const checkedAt = DateTime.formatIso(yield* DateTime.now);
578 if (!input.settings.enabled) {
579 return yield* buildInitialAcpRegistrySnapshot(input);
580 }
581 const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog;
582 const inspected = yield* Effect.result(catalog.inspect(input.settings, input.environment));
583 const snapshot = buildCheckedAcpRegistrySnapshot({
584 ...input,
585 checkedAt,
586 inspection: Result.isFailure(inspected)
587 ? {
588 status: "failed",
589 message: `Could not inspect ACP Registry agent: ${inspected.failure.message}`,
590 }
591 : inspected.success,
592 });
593 return inspected._tag === "Success" && inspected.success.status === "ready"
594 ? {
595 ...snapshot,
596 message: "Checking ACP authentication, models, and commands in the background...",
597 }
598 : snapshot;
599});
600​
601export type AcpRegistryDriverEnv =
602 | AcpRegistryAdapterV2DriverEnv
603 | Digest.Digest
604 | ProviderHost.ProviderHost;
605​
606export const AcpRegistryDriver: ProviderDriver<AcpRegistrySettings, AcpRegistryDriverEnv> = {
607 driverKind: DRIVER_KIND,
608 metadata: {
609 displayName: "ACP Registry",
610 supportsMultipleInstances: true,
611 hasDefaultInstance: false,
612 },
613 configSchema: AcpRegistrySettings,
614 defaultConfig: () => decodeSettings({}),
615 create: Effect.fn("AcpRegistryDriver.create")(function* ({
616 instanceId,
617 displayName,
618 accentColor,
619 environment,
620 enabled,
621 config,
622 }) {
623 const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog;
624 const runtimeCoordinator = yield* Effect.serviceOption(
625 AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
626 );
627 if (Option.isSome(runtimeCoordinator)) {
628 yield* runtimeCoordinator.value.clearAvailableCommands(instanceId);
629 yield* runtimeCoordinator.value.clearLiveConfiguration(instanceId);
630 yield* Effect.addFinalizer(() =>
631 runtimeCoordinator.value
632 .clearAvailableCommands(instanceId)
633 .pipe(Effect.andThen(runtimeCoordinator.value.clearLiveConfiguration(instanceId))),
634 );
635 }
636 const random = yield* SecureRandom.SecureRandom;
637 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
638 const hostEnvironment = yield* HostProcess.Environment;
639 const host = yield* ProviderHost.ProviderHost;
640 const continuationIdentity = defaultProviderContinuationIdentity({
641 driverKind: DRIVER_KIND,
642 instanceId,
643 });
644 const identity = {
645 instanceId,
646 displayName,
647 accentColor,
648 continuationKey: continuationIdentity.continuationKey,
649 };
650 const effectiveConfig = { ...config, enabled } satisfies AcpRegistrySettings;
651 const processEnvironment = yield* mergeProviderInstanceEnvironment(
652 environment,
653 hostEnvironment,
654 );
655 const orchestrationAdapter = yield* AcpRegistryAdapterV2Driver.create({
656 instanceId,
657 displayName,
658 accentColor,
659 environment,
660 enabled,
661 config,
662 }).pipe(
663 Effect.mapError(
664 (cause) =>
665 new ProviderDriverError({
666 driver: DRIVER_KIND,
667 instanceId,
668 detail: "Failed to build ACP Registry orchestration adapter.",
669 cause,
670 }),
671 ),
672 );
673 const readinessInput = {
674 ...identity,
675 settings: effectiveConfig,
676 environment: processEnvironment,
677 };
678 const confirmedAuthentication =
679 yield* AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({
680 cacheDir: host.paths.providerStatusCacheDir,
681 instanceId,
682 settings: effectiveConfig,
683 environment,
684 processEnvironment,
685 });
686 // Refreshes rebuild the snapshot from the probe, so per-model options
687 // learned from earlier sessions are kept here.
688 const learnedModels = yield* Ref.make<ReadonlyArray<ServerProviderModel>>([]);
689 const applyLiveConfiguration = (
690 provider: ServerProvider,
691 configuration: AcpRegistryLiveConfiguration,
692 ) =>
693 Ref.modify(learnedModels, (learned) => {
694 const next = applyAcpRegistryLiveConfiguration(
695 provider,
696 configuration,
697 effectiveConfig.customModels,
698 learned.length > 0 ? learned : provider.models,
699 );
700 return [next, next.models === provider.models ? learned : next.models];
701 });
702 const clearLearnedModels = Ref.set(learnedModels, []);
703 const withLiveRuntimeState = Effect.fn("AcpRegistryDriver.withLiveRuntimeState")(function* (
704 input: ServerProvider,
705 ) {
706 if (input.auth.status === "unauthenticated") yield* confirmedAuthentication.set(false);
707 const provider =
708 input.enabled &&
709 input.installed &&
710 input.auth.status === "unknown" &&
711 (yield* confirmedAuthentication.get)
712 ? { ...input, auth: { ...input.auth, status: "authenticated" as const } }
713 : input;
714 return yield* Option.isNone(runtimeCoordinator)
715 ? Effect.succeed(provider)
716 : Effect.all({
717 commands: runtimeCoordinator.value.getAvailableCommands(instanceId),
718 configuration: runtimeCoordinator.value.getLiveConfiguration(instanceId),
719 authAction: runtimeCoordinator.value.getUrlAuthAction(instanceId),
720 }).pipe(
721 Effect.flatMap(({ commands, configuration, authAction }) => {
722 const withCommands = applyAcpRegistryAvailableCommands(provider, commands);
723 return Option.match(configuration, {
724 onNone: () => Effect.succeed(withCommands),
725 onSome: (liveConfiguration) =>
726 applyLiveConfiguration(withCommands, liveConfiguration),
727 }).pipe(
728 Effect.map((withConfiguration) =>
729 applyAcpRegistryUrlAuthAction(withConfiguration, authAction),
730 ),
731 );
732 }),
733 );
734 });
735 // A local executable's version comes only from probing it, so readiness checks reuse the last report.
736 const reportedLocalVersion = yield* Ref.make<string | null>(null);
737 const checkProvider = checkAcpRegistryProviderReadiness(readinessInput).pipe(
738 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
739 Effect.flatMap((provider) =>
740 Ref.get(reportedLocalVersion).pipe(
741 Effect.map((version) =>
742 provider.installed && provider.version === null && version !== null
743 ? { ...provider, version }
744 : provider,
745 ),
746 ),
747 ),
748 Effect.flatMap(withLiveRuntimeState),
749 );
750 const enrichProvider = checkAcpRegistryProviderStatus(
751 {
752 ...readinessInput,
753 cwd: host.paths.cwd,
754 },
755 probeAcpRegistryConfiguration,
756 ).pipe(
757 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
758 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
759 Effect.provideService(SecureRandom.SecureRandom, random),
760 );
761 const enrichmentCache = yield* Ref.make<AcpRegistryEnrichmentCache>({
762 generation: 0,
763 entry: null,
764 });
765 const liveSnapshotSemaphore = yield* Semaphore.make(1);
766 const invalidateEnrichmentCache = Ref.update(enrichmentCache, (current) => ({
767 generation: current.generation + 1,
768 entry: null,
769 }));
770 const enrichProviderCached = Effect.fn("AcpRegistryDriver.enrichProviderCached")(function* (
771 baseSnapshot: ServerProvider,
772 ) {
773 const now = yield* Clock.currentTimeMillis;
774 const cacheState = yield* Ref.get(enrichmentCache);
775 const cached = cacheState.entry;
776 if (
777 cached !== null &&
778 isAcpRegistryCacheValid(
779 cached,
780 baseSnapshot.version,
781 effectiveConfig.source === "local",
782 now,
783 )
784 ) {
785 return {
786 provider: { ...cached.provider, checkedAt: baseSnapshot.checkedAt },
787 generation: cacheState.generation,
788 };
789 }
790 const enriched = yield* enrichProvider;
791 if (effectiveConfig.source === "local" && enriched.status === "ready") {
792 yield* Ref.set(reportedLocalVersion, enriched.version);
793 }
794 if (enriched.status === "ready") {
795 const completedAt = yield* Clock.currentTimeMillis;
796 yield* Ref.update(enrichmentCache, (current) =>
797 current.generation === cacheState.generation
798 ? {
799 ...current,
800 entry: {
801 provider: enriched,
802 expiresAt: completedAt + acpRegistryProbeTtlMs(enriched),
803 },
804 }
805 : current,
806 );
807 }
808 return { provider: enriched, generation: cacheState.generation };
809 });
810 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
811 const snapshot = yield* makeManagedServerProvider<
812 ProviderSnapshotSettings<AcpRegistrySettings>
813 >({
814 resolveMaintenance: () => Effect.succeed(MAINTENANCE),
815 getSettings: snapshotSettings.getSettings,
816 streamSettings: snapshotSettings.streamSettings,
817 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
818 // Inspection may fetch the registry when its disk cache is missing; creation must not wait on that.
819 initialSnapshot: () => buildInitialAcpRegistrySnapshot(readinessInput),
820 checkProvider,
821 enrichSnapshot: Effect.fn("enrichSnapshot")(function ({
822 snapshot,
823 getSnapshot,
824 publishSnapshot,
825 }) {
826 if (!snapshot.installed) return Effect.void;
827 const publishEnrichment = (
828 Option.isSome(runtimeCoordinator)
829 ? runtimeCoordinator.value.runBackgroundProbe(
830 effectiveConfig.source === "local"
831 ? `local:${instanceId}`
832 : effectiveConfig.agentId,
833 enrichProviderCached(snapshot),
834 )
835 : enrichProviderCached(snapshot).pipe(Effect.asSome)
836 ).pipe(
837 Effect.flatMap(
838 Option.match({
839 onNone: () => Effect.void,
840 onSome: ({ provider, generation }) =>
841 liveSnapshotSemaphore.withPermit(
842 Ref.get(enrichmentCache).pipe(
843 Effect.flatMap((current) =>
844 current.generation === generation
845 ? withLiveRuntimeState(provider).pipe(Effect.flatMap(publishSnapshot))
846 : Effect.void,
847 ),
848 ),
849 ),
850 }),
851 ),
852 );
853 if (Option.isNone(runtimeCoordinator)) return publishEnrichment;
854​
855 const publishLiveCommands = runtimeCoordinator.value.watchAvailableCommands(
856 instanceId,
857 ({ slashCommands, skills }) =>
858 liveSnapshotSemaphore.withPermit(
859 getSnapshot.pipe(
860 Effect.flatMap((current) =>
861 publishSnapshot({
862 ...current,
863 slashCommands,
864 skills,
865 }),
866 ),
867 ),
868 ),
869 );
870 const publishLiveConfiguration = runtimeCoordinator.value.watchLiveConfiguration(
871 instanceId,
872 (configuration) =>
873 liveSnapshotSemaphore.withPermit(
874 getSnapshot.pipe(
875 Effect.flatMap((current) => applyLiveConfiguration(current, configuration)),
876 Effect.tap(() =>
877 Clock.currentTimeMillis.pipe(
878 Effect.flatMap((now) =>
879 Ref.update(enrichmentCache, (cache) =>
880 updateAcpRegistryEnrichmentCache({
881 cache,
882 configuration,
883 customModels: effectiveConfig.customModels,
884 now,
885 }),
886 ),
887 ),
888 ),
889 ),
890 Effect.flatMap(publishSnapshot),
891 ),
892 ),
893 );
894 const publishUrlAuthAction = runtimeCoordinator.value.watchUrlAuthAction(
895 instanceId,
896 (action) =>
897 liveSnapshotSemaphore.withPermit(
898 getSnapshot.pipe(
899 Effect.flatMap((current) =>
900 publishSnapshot(
901 applyAcpRegistryUrlAuthAction(current, Option.fromNullishOr(action)),
902 ),
903 ),
904 ),
905 ),
906 );
907 return Effect.all(
908 [publishEnrichment, publishLiveCommands, publishLiveConfiguration, publishUrlAuthAction],
909 {
910 concurrency: "unbounded",
911 discard: true,
912 },
913 );
914 }),
915 }).pipe(
916 Effect.mapError(
917 (cause) =>
918 new ProviderDriverError({
919 driver: DRIVER_KIND,
920 instanceId,
921 detail: "Failed to build the ACP Registry provider snapshot.",
922 cause,
923 }),
924 ),
925 );
926​
927 const provideAcpManagementServices = <A, E>(
928 effect: Effect.Effect<
929 A,
930 E,
931 | AcpRegistrySupport.AcpRegistryCatalog
932 | ChildProcessSpawner.ChildProcessSpawner
933 | SecureRandom.SecureRandom
934 >,
935 ): Effect.Effect<A, E> => {
936 const provided = effect.pipe(
937 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
938 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
939 Effect.provideService(SecureRandom.SecureRandom, random),
940 );
941 return Option.isSome(runtimeCoordinator)
942 ? provided.pipe(
943 Effect.provideService(
944 AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
945 runtimeCoordinator.value,
946 ),
947 )
948 : provided;
949 };
950​
951 const clearLiveState = (
952 Option.isSome(runtimeCoordinator)
953 ? runtimeCoordinator.value
954 .clearLiveConfiguration(instanceId)
955 .pipe(Effect.andThen(runtimeCoordinator.value.clearAvailableCommands(instanceId)))
956 : Effect.void
957 ).pipe(Effect.andThen(clearLearnedModels));
958 const controller = yield* AcpRegistryAuth.makeAcpRegistryAuth({
959 instanceId,
960 settings: effectiveConfig,
961 cwd: host.paths.cwd,
962 environment: processEnvironment,
963 onChanged: (authenticated) =>
964 confirmedAuthentication
965 .set(authenticated)
966 .pipe(
967 Effect.andThen(authenticated ? Effect.void : clearLiveState),
968 Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)),
969 Effect.andThen(snapshot.refresh),
970 Effect.asVoid,
971 ),
972 }).pipe(
973 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
974 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
975 Effect.provideService(SecureRandom.SecureRandom, random),
976 );
977 const auth = {
978 ...controller,
979 invalidate: (controller.invalidate ?? Effect.void).pipe(
980 Effect.andThen(confirmedAuthentication.set(false)),
981 Effect.andThen(clearLiveState),
982 Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)),
983 Effect.andThen(snapshot.refresh),
984 Effect.asVoid,
985 ),
986 };
987​
988 return {
989 instanceId,
990 driverKind: DRIVER_KIND,
991 continuationIdentity,
992 displayName,
993 accentColor,
994 enabled,
995 auth,
996 snapshot: {
997 ...snapshot,
998 refresh: snapshot.refresh.pipe(Effect.tap(() => controller.refreshMethods ?? Effect.void)),
999 },
1000 invalidateCaches: (Option.isSome(runtimeCoordinator)
1001 ? runtimeCoordinator.value.clearLiveConfiguration(instanceId)
1002 : Effect.void
1003 ).pipe(
1004 Effect.andThen(clearLearnedModels),
1005 Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)),
1006 ),
1007 orchestrationAdapter,
1008 textGeneration: makeUnsupportedTextGeneration(),
1009 acpSessionManagement: {
1010 listSessions: ({ cwd, cursor }) =>
1011 provideAcpManagementServices(
1012 listAcpRegistrySessions({
1013 instanceId,
1014 settings: effectiveConfig,
1015 cwd,
1016 environment: processEnvironment,
1017 ...(cursor === undefined ? {} : { cursor }),
1018 }),
1019 ),
1020 deleteSession: ({ cwd, sessionId }) =>
1021 provideAcpManagementServices(
1022 deleteAcpRegistrySession({
1023 instanceId,
1024 settings: effectiveConfig,
1025 cwd,
1026 environment: processEnvironment,
1027 sessionId,
1028 }),
1029 ),
1030 listProviders: (cwd) =>
1031 provideAcpManagementServices(
1032 listAcpRegistryProviders({
1033 instanceId,
1034 settings: effectiveConfig,
1035 cwd,
1036 environment: processEnvironment,
1037 }),
1038 ),
1039 setProvider: ({ cwd, providerId, apiType, baseUrl, headers }) =>
1040 provideAcpManagementServices(
1041 setAcpRegistryProvider({
1042 instanceId,
1043 settings: effectiveConfig,
1044 cwd,
1045 environment: processEnvironment,
1046 providerId,
1047 apiType,
1048 baseUrl,
1049 ...(headers === undefined ? {} : { headers }),
1050 }),
1051 ).pipe(Effect.tap(() => liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache))),
1052 disableProvider: ({ cwd, providerId }) =>
1053 provideAcpManagementServices(
1054 disableAcpRegistryProvider({
1055 instanceId,
1056 settings: effectiveConfig,
1057 cwd,
1058 environment: processEnvironment,
1059 providerId,
1060 }),
1061 ).pipe(Effect.tap(() => liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache))),
1062 logout: (cwd) => {
1063 const logout = logoutAcpRegistry({
1064 instanceId,
1065 settings: effectiveConfig,
1066 cwd,
1067 environment: processEnvironment,
1068 }).pipe(
1069 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
1070 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1071 Effect.provideService(SecureRandom.SecureRandom, random),
1072 Effect.tap(() => confirmedAuthentication.set(false)),
1073 Effect.tap(() =>
1074 liveSnapshotSemaphore.withPermit(
1075 invalidateEnrichmentCache.pipe(
1076 Effect.andThen(
1077 Option.isSome(runtimeCoordinator)
1078 ? Effect.all(
1080 runtimeCoordinator.value.clearAvailableCommands(instanceId),
1081 runtimeCoordinator.value.clearLiveConfiguration(instanceId),
1082 ],
1083 { concurrency: "unbounded", discard: true },
1085 : Effect.void,
1086 ),
1087 ),
1088 ),
1089 ),
1090 );
1091 return Option.isSome(runtimeCoordinator)
1092 ? logout.pipe(
1093 Effect.provideService(
1094 AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
1095 runtimeCoordinator.value,
1096 ),
1098 : logout;
1099 },
1100 },
1101 } satisfies ProviderInstance;
1102 }),