The best way to control Claude Code, Codex and more from any computer or phone

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