The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | ACP_REGISTRY_MAX_AGENTS, |
| 3 | AcpRegistryOperationError, |
| 4 | AcpRegistryOperationErrorReason, |
| 5 | TrimmedNonEmptyString, |
| 6 | type AcpRegistryManagedBinaryUninstallInput, |
| 7 | type AcpRegistryManagedBinaryUninstallResult, |
| 8 | type AcpRegistryPrepareInput, |
| 9 | type AcpRegistryPrepareResult, |
| 10 | type AcpRegistrySearchInput, |
| 11 | type AcpRegistrySearchResult, |
| 12 | type AcpRegistryDistribution as AcpRegistryDistributionKind, |
| 13 | } from "@t3tools/contracts"; |
| 14 | import type { AcpRegistryDistributionPreference } from "../settings.ts"; |
| 15 | import type { AcpRegistrySettings } from "../settings.ts"; |
| 16 | import { cliArchiveTarCommand } from "@t3tools/shared/cliRelease"; |
| 17 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 18 | import { |
| 19 | mergePathEntries, |
| 20 | resolveSpawnCommand, |
| 21 | SpawnExecutableResolution, |
| 22 | } from "@t3tools/shared/shell"; |
| 23 | import * as Clock from "effect/Clock"; |
| 24 | import * as Context from "effect/Context"; |
| 25 | import * as Duration from "effect/Duration"; |
| 26 | import * as Digest from "effect/crypto/Digest"; |
| 27 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 28 | import * as Effect from "effect/Effect"; |
| 29 | import * as Hex from "effect/encoding/Hex"; |
| 30 | import * as FileSystem from "effect/FileSystem"; |
| 31 | import * as Layer from "effect/Layer"; |
| 32 | import * as Option from "effect/Option"; |
| 33 | import * as Path from "effect/Path"; |
| 34 | import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts"; |
| 35 | import * as PlatformError from "effect/PlatformError"; |
| 36 | import * as Ref from "effect/Ref"; |
| 37 | import * as Schedule from "effect/Schedule"; |
| 38 | import type * as Scope from "effect/Scope"; |
| 39 | import * as Schema from "effect/Schema"; |
| 40 | import * as Semaphore from "effect/Semaphore"; |
| 41 | import * as Stream from "effect/Stream"; |
| 42 | import { sha256 } from "@noble/hashes/sha2"; |
| 43 | import * as HttpClient from "effect/http/HttpClient"; |
| 44 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 45 | import * as HttpClientResponse from "effect/http/HttpClientResponse"; |
| 46 | import * as ChildProcess from "effect/process/ChildProcess"; |
| 47 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 48 | |
| 49 | import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText"; |
| 50 | import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; |
| 51 | import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; |
| 52 | |
| 53 | const ACP_REGISTRY_URL = "https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json"; |
| 54 | |
| 55 | const MAX_REGISTRY_BYTES = 1024 * 1024; |
| 56 | const MAX_ARCHIVE_BYTES = 1024 * 1024 * 1024; |
| 57 | const MAX_COMMAND_OUTPUT_BYTES = 1024 * 1024; |
| 58 | // Install errors become the provider status message; npm and uv print the actionable error last. |
| 59 | const MAX_COMMAND_ERROR_TAIL_CHARS = 1_000; |
| 60 | // Archive listings can exceed the output of package-manager commands. |
| 61 | const MAX_ARCHIVE_LISTING_BYTES = 64 * 1024 * 1024; |
| 62 | const MAX_PACKAGE_MANIFEST_BYTES = 1024 * 1024; |
| 63 | // Older clients omit the limit and validate responses against a 20-agent cap. |
| 64 | const DEFAULT_SEARCH_LIMIT = 20; |
| 65 | const REGISTRY_REQUEST_TIMEOUT = "30 seconds"; |
| 66 | // Searches reuse an index fetched this recently; prepare always fetches the latest. |
| 67 | const REGISTRY_SEARCH_MAX_AGE_MS = 5 * 60 * 1_000; |
| 68 | const ARCHIVE_REQUEST_TIMEOUT = "20 minutes"; |
| 69 | const PACKAGE_INSTALL_TIMEOUT = "20 minutes"; |
| 70 | const PACKAGE_QUERY_TIMEOUT = "30 seconds"; |
| 71 | |
| 72 | const BoundedAgentId = Schema.String.check( |
| 73 | Schema.isMaxLength(128), |
| 74 | Schema.isPattern(/^[a-z0-9][a-z0-9._-]*$/u), |
| 75 | ); |
| 76 | const BoundedName = TrimmedNonEmptyString.check(Schema.isMaxLength(160)); |
| 77 | // Versions become install directory names, so "." and ".." must not decode. |
| 78 | const BoundedVersion = TrimmedNonEmptyString.check( |
| 79 | Schema.isMaxLength(128), |
| 80 | Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9._+-]*$/u), |
| 81 | ); |
| 82 | const BoundedDescription = Schema.String.check(Schema.isMaxLength(1_024)); |
| 83 | const BoundedMetadata = Schema.String.check(Schema.isMaxLength(256)); |
| 84 | const BoundedArgument = Schema.String.check(Schema.isMaxLength(1_024)); |
| 85 | const PackageCommandName = Schema.String.check( |
| 86 | Schema.isMaxLength(128), |
| 87 | Schema.isPattern(/^[a-z0-9][a-z0-9._-]*$/iu), |
| 88 | ); |
| 89 | const isPackageCommandName = Schema.is(PackageCommandName); |
| 90 | const EXACT_RUNNER_VERSION = "v?[0-9]+\\.[0-9]+\\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?"; |
| 91 | const EXACT_NPX_PACKAGE = new RegExp( |
| 92 | `^(?:@[^/@\\s]+/[^@\\s]+|[a-z0-9][a-z0-9._-]*)@${EXACT_RUNNER_VERSION}$`, |
| 93 | "iu", |
| 94 | ); |
| 95 | const EXACT_UVX_PACKAGE = new RegExp(`^[a-z0-9][a-z0-9._-]*(?:@|==)${EXACT_RUNNER_VERSION}$`, "iu"); |
| 96 | const NpxPackage = Schema.String.check( |
| 97 | Schema.isMaxLength(256), |
| 98 | Schema.makeFilter( |
| 99 | (value) => |
| 100 | EXACT_NPX_PACKAGE.test(value) || "ACP Registry npx packages must include an exact version.", |
| 101 | ), |
| 102 | ); |
| 103 | const UvxPackage = Schema.String.check( |
| 104 | Schema.isMaxLength(256), |
| 105 | Schema.makeFilter( |
| 106 | (value) => |
| 107 | EXACT_UVX_PACKAGE.test(value) || "ACP Registry uvx packages must include an exact version.", |
| 108 | ), |
| 109 | ); |
| 110 | const HttpsUrl = Schema.String.check( |
| 111 | Schema.isMaxLength(2_048), |
| 112 | Schema.makeFilter((value) => { |
| 113 | try { |
| 114 | const url = new URL(value); |
| 115 | return ( |
| 116 | (url.protocol === "https:" && url.username.length === 0 && url.password.length === 0) || |
| 117 | "ACP Registry URLs must use HTTPS without embedded credentials." |
| 118 | ); |
| 119 | } catch { |
| 120 | return "ACP Registry URLs must be valid absolute URLs."; |
| 121 | } |
| 122 | }), |
| 123 | ); |
| 124 | |
| 125 | const AcpRegistryPackageDistributionFields = { |
| 126 | args: Schema.optionalKey(Schema.Array(BoundedArgument).check(Schema.isMaxLength(64))), |
| 127 | env: Schema.optionalKey(Schema.Record(BoundedMetadata, BoundedArgument)), |
| 128 | } as const; |
| 129 | const AcpRegistryNpxDistribution = Schema.Struct({ |
| 130 | package: NpxPackage, |
| 131 | ...AcpRegistryPackageDistributionFields, |
| 132 | }); |
| 133 | const AcpRegistryUvxDistribution = Schema.Struct({ |
| 134 | package: UvxPackage, |
| 135 | ...AcpRegistryPackageDistributionFields, |
| 136 | }); |
| 137 | |
| 138 | const AcpRegistryBinaryTarget = Schema.Struct({ |
| 139 | archive: HttpsUrl, |
| 140 | cmd: BoundedArgument, |
| 141 | sha256: Schema.optionalKey(Schema.String.check(Schema.isPattern(/^[a-f0-9]{64}$/iu))), |
| 142 | args: Schema.optionalKey(Schema.Array(BoundedArgument).check(Schema.isMaxLength(64))), |
| 143 | env: Schema.optionalKey(Schema.Record(BoundedMetadata, BoundedArgument)), |
| 144 | }); |
| 145 | |
| 146 | const AcpRegistryAgent = Schema.Struct({ |
| 147 | id: BoundedAgentId, |
| 148 | name: BoundedName, |
| 149 | version: BoundedVersion, |
| 150 | description: BoundedDescription, |
| 151 | authors: Schema.optionalKey(Schema.Array(BoundedMetadata).check(Schema.isMaxLength(16))), |
| 152 | license: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(128))), |
| 153 | website: Schema.optionalKey(HttpsUrl), |
| 154 | repository: Schema.optionalKey(HttpsUrl), |
| 155 | icon: Schema.optionalKey(HttpsUrl), |
| 156 | distribution: Schema.Struct({ |
| 157 | binary: Schema.optionalKey(Schema.Record(Schema.String, AcpRegistryBinaryTarget)), |
| 158 | npx: Schema.optionalKey(AcpRegistryNpxDistribution), |
| 159 | uvx: Schema.optionalKey(AcpRegistryUvxDistribution), |
| 160 | }), |
| 161 | }); |
| 162 | export type AcpRegistryAgent = typeof AcpRegistryAgent.Type; |
| 163 | |
| 164 | const NpmPackageManifest = Schema.Struct({ |
| 165 | name: Schema.String, |
| 166 | version: Schema.String, |
| 167 | bin: Schema.Union([BoundedArgument, Schema.Record(PackageCommandName, BoundedArgument)]), |
| 168 | }); |
| 169 | |
| 170 | const AcpRegistryPackageInstallReceipt = Schema.Struct({ |
| 171 | agentId: BoundedAgentId, |
| 172 | agentVersion: BoundedVersion, |
| 173 | distribution: Schema.Literals(["npx", "uvx"]), |
| 174 | packageSpec: Schema.String, |
| 175 | managerPath: Schema.String, |
| 176 | binDirectory: Schema.String, |
| 177 | executablePath: Schema.String, |
| 178 | packageRoot: Schema.optional(Schema.String), |
| 179 | packageVersion: Schema.optional(Schema.String), |
| 180 | }); |
| 181 | type AcpRegistryPackageInstallReceipt = typeof AcpRegistryPackageInstallReceipt.Type; |
| 182 | |
| 183 | const AcpRegistryIndexEnvelope = Schema.Struct({ |
| 184 | version: BoundedVersion, |
| 185 | agents: Schema.Array(Schema.Unknown).check(Schema.isMaxLength(ACP_REGISTRY_MAX_AGENTS)), |
| 186 | }); |
| 187 | export interface AcpRegistryIndex { |
| 188 | readonly version: string; |
| 189 | readonly agents: ReadonlyArray<AcpRegistryAgent>; |
| 190 | } |
| 191 | |
| 192 | const decodeRegistryIndexEnvelope = Schema.decodeUnknownEffect(AcpRegistryIndexEnvelope); |
| 193 | const decodeRegistryAgent = Schema.decodeUnknownOption(AcpRegistryAgent); |
| 194 | const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown)); |
| 195 | const decodeNpmPackageManifest = Schema.decodeUnknownEffect( |
| 196 | Schema.fromJsonString(NpmPackageManifest), |
| 197 | ); |
| 198 | const decodePackageInstallReceipt = Schema.decodeUnknownOption( |
| 199 | Schema.fromJsonString(AcpRegistryPackageInstallReceipt), |
| 200 | ); |
| 201 | const encodePackageInstallReceipt = Schema.encodeSync( |
| 202 | Schema.fromJsonString(AcpRegistryPackageInstallReceipt), |
| 203 | ); |
| 204 | const decodeHttpsUrl = Schema.decodeUnknownEffect(HttpsUrl); |
| 205 | const decodeBoundedAgentId = Schema.decodeUnknownEffect(BoundedAgentId); |
| 206 | |
| 207 | export const AcpRegistryErrorReason = AcpRegistryOperationErrorReason; |
| 208 | export type AcpRegistryErrorReason = typeof AcpRegistryErrorReason.Type; |
| 209 | |
| 210 | export class AcpRegistryError extends Schema.TaggedError<AcpRegistryError>()("AcpRegistryError", { |
| 211 | reason: AcpRegistryErrorReason, |
| 212 | detail: Schema.String, |
| 213 | cause: Schema.optional(Schema.Defect()), |
| 214 | }) { |
| 215 | override get message(): string { |
| 216 | return this.detail; |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | export function toAcpRegistryOperationError(error: AcpRegistryError): AcpRegistryOperationError { |
| 221 | return new AcpRegistryOperationError({ |
| 222 | reason: error.reason, |
| 223 | message: error.detail, |
| 224 | cause: error, |
| 225 | }); |
| 226 | } |
| 227 | |
| 228 | const isAcpRegistryError = Schema.is(AcpRegistryError); |
| 229 | |
| 230 | export type AcpRegistryPlatformTarget = |
| 231 | | "darwin-aarch64" |
| 232 | | "darwin-x86_64" |
| 233 | | "linux-aarch64" |
| 234 | | "linux-x86_64" |
| 235 | | "windows-aarch64" |
| 236 | | "windows-x86_64"; |
| 237 | |
| 238 | function resolveAcpRegistryPlatformTarget( |
| 239 | platform: NodeJS.Platform, |
| 240 | architecture: NodeJS.Architecture, |
| 241 | ): AcpRegistryPlatformTarget | undefined { |
| 242 | const os = |
| 243 | platform === "darwin" |
| 244 | ? "darwin" |
| 245 | : platform === "linux" |
| 246 | ? "linux" |
| 247 | : platform === "win32" |
| 248 | ? "windows" |
| 249 | : undefined; |
| 250 | const arch = architecture === "arm64" ? "aarch64" : architecture === "x64" ? "x86_64" : undefined; |
| 251 | return os && arch ? (`${os}-${arch}` as AcpRegistryPlatformTarget) : undefined; |
| 252 | } |
| 253 | |
| 254 | function resolveAcpRegistryPlatformTargetCandidates( |
| 255 | platformTarget: AcpRegistryPlatformTarget | undefined, |
| 256 | ): ReadonlyArray<AcpRegistryPlatformTarget> { |
| 257 | if (platformTarget === undefined) return []; |
| 258 | // Windows 11 ARM can emulate x86_64 binaries when no native build exists. |
| 259 | if (platformTarget === "windows-aarch64") { |
| 260 | return ["windows-aarch64", "windows-x86_64"]; |
| 261 | } |
| 262 | return [platformTarget]; |
| 263 | } |
| 264 | |
| 265 | interface ExactPackageSpec { |
| 266 | readonly name: string; |
| 267 | readonly version: string; |
| 268 | } |
| 269 | |
| 270 | function parseNpxPackageSpec(packageSpec: string): ExactPackageSpec { |
| 271 | const separator = packageSpec.lastIndexOf("@"); |
| 272 | return { |
| 273 | name: packageSpec.slice(0, separator), |
| 274 | version: packageSpec.slice(separator + 1).replace(/^v/iu, ""), |
| 275 | }; |
| 276 | } |
| 277 | |
| 278 | function parseUvxPackageSpec(packageSpec: string): ExactPackageSpec { |
| 279 | const equalsSeparator = packageSpec.lastIndexOf("=="); |
| 280 | const separator = equalsSeparator >= 0 ? equalsSeparator : packageSpec.lastIndexOf("@"); |
| 281 | const separatorLength = equalsSeparator >= 0 ? 2 : 1; |
| 282 | return { |
| 283 | name: packageSpec.slice(0, separator), |
| 284 | version: packageSpec.slice(separator + separatorLength).replace(/^v/iu, ""), |
| 285 | }; |
| 286 | } |
| 287 | |
| 288 | function packageManagerFor(distribution: AcpRegistryDistributionKind): "npm" | "uv" | undefined { |
| 289 | return distribution === "npx" ? "npm" : distribution === "uvx" ? "uv" : undefined; |
| 290 | } |
| 291 | |
| 292 | function packageCommandCandidates( |
| 293 | agent: AcpRegistryAgent, |
| 294 | packageName: string, |
| 295 | ): ReadonlyArray<string> { |
| 296 | const unscopedPackageName = packageName.split("/").pop() ?? packageName; |
| 297 | return Array.from( |
| 298 | new Set( |
| 299 | [agent.id, unscopedPackageName, unscopedPackageName.replace(/-acp$/u, "")].filter( |
| 300 | isPackageCommandName, |
| 301 | ), |
| 302 | ), |
| 303 | ); |
| 304 | } |
| 305 | |
| 306 | function readEnvironmentPath( |
| 307 | environment: NodeJS.ProcessEnv, |
| 308 | platform: NodeJS.Platform, |
| 309 | ): string | undefined { |
| 310 | if (platform !== "win32") return environment.PATH; |
| 311 | return ( |
| 312 | environment.PATH ?? |
| 313 | Object.entries(environment).find(([key]) => key.toLowerCase() === "path")?.[1] |
| 314 | ); |
| 315 | } |
| 316 | |
| 317 | // Windows env keys are case-insensitive, and an inherited NPM_CONFIG_PREFIX would win over ours. |
| 318 | function withoutNpmPrefix( |
| 319 | environment: NodeJS.ProcessEnv, |
| 320 | platform: NodeJS.Platform, |
| 321 | ): NodeJS.ProcessEnv { |
| 322 | if (platform !== "win32") return environment; |
| 323 | return Object.fromEntries( |
| 324 | Object.entries(environment).filter(([key]) => key.toLowerCase() !== "npm_config_prefix"), |
| 325 | ); |
| 326 | } |
| 327 | |
| 328 | function withPreferredPath( |
| 329 | environment: NodeJS.ProcessEnv, |
| 330 | directory: string, |
| 331 | platform: NodeJS.Platform, |
| 332 | ): NodeJS.ProcessEnv { |
| 333 | return { |
| 334 | ...environment, |
| 335 | PATH: mergePathEntries(directory, readEnvironmentPath(environment, platform), platform), |
| 336 | }; |
| 337 | } |
| 338 | |
| 339 | export const acpRegistryManagedBinaryDirectories = Effect.fn("acpRegistryManagedBinaryDirectories")( |
| 340 | function* (input: { |
| 341 | readonly cacheDir: string; |
| 342 | readonly toolsDir: string; |
| 343 | readonly platform: NodeJS.Platform; |
| 344 | readonly architecture: NodeJS.Architecture; |
| 345 | }): Effect.fn.Return<ReadonlyArray<string>, never, FileSystem.FileSystem | Path.Path> { |
| 346 | const fileSystem = yield* FileSystem.FileSystem; |
| 347 | const path = yield* Path.Path; |
| 348 | const target = resolveAcpRegistryPlatformTarget(input.platform, input.architecture); |
| 349 | const registryDirectory = path.join(input.cacheDir, "acp-registry"); |
| 350 | const installsDirectory = input.toolsDir; |
| 351 | const packageReceiptsDirectory = path.join(registryDirectory, "package-installs"); |
| 352 | const listDirectories = (directory: string) => |
| 353 | fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed((): Array<string> => [])); |
| 354 | const directories: Array<string> = []; |
| 355 | |
| 356 | for (const receiptFile of (yield* listDirectories(packageReceiptsDirectory)).toSorted()) { |
| 357 | const receipt = yield* fileSystem |
| 358 | .readFileString(path.join(packageReceiptsDirectory, receiptFile)) |
| 359 | .pipe( |
| 360 | Effect.map(decodePackageInstallReceipt), |
| 361 | Effect.orElseSucceed(() => Option.none()), |
| 362 | ); |
| 363 | if ( |
| 364 | Option.isSome(receipt) && |
| 365 | receipt.value.binDirectory === |
| 366 | path.join( |
| 367 | installsDirectory, |
| 368 | receipt.value.agentId, |
| 369 | encodeURIComponent(receipt.value.agentVersion), |
| 370 | receipt.value.distribution === "npx" ? "npm" : "python", |
| 371 | ...(receipt.value.distribution === "npx" && input.platform === "win32" ? [] : ["bin"]), |
| 372 | ) && |
| 373 | path.dirname(receipt.value.executablePath) === receipt.value.binDirectory && |
| 374 | (yield* fileSystem |
| 375 | .exists(receipt.value.executablePath) |
| 376 | .pipe(Effect.orElseSucceed(() => false))) |
| 377 | ) { |
| 378 | directories.push(receipt.value.binDirectory); |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | if (target === undefined) return Array.from(new Set(directories)); |
| 383 | const cachedAgents = yield* fileSystem |
| 384 | .readFileString(path.join(registryDirectory, "registry.json")) |
| 385 | .pipe( |
| 386 | Effect.flatMap(decodeJson), |
| 387 | Effect.flatMap(decodeRegistryIndexEnvelope), |
| 388 | Effect.map((envelope) => |
| 389 | envelope.agents.flatMap((candidate) => { |
| 390 | const decoded = decodeRegistryAgent(candidate); |
| 391 | return Option.isSome(decoded) ? [decoded.value] : []; |
| 392 | }), |
| 393 | ), |
| 394 | Effect.orElseSucceed((): ReadonlyArray<AcpRegistryAgent> => []), |
| 395 | ); |
| 396 | const cachedAgentByInstall = new Map( |
| 397 | cachedAgents.map( |
| 398 | (agent) => [`${agent.id}\0${encodeURIComponent(agent.version)}`, agent] as const, |
| 399 | ), |
| 400 | ); |
| 401 | for (const agent of (yield* listDirectories(installsDirectory)).toSorted()) { |
| 402 | const versions = (yield* listDirectories(path.join(installsDirectory, agent))).toSorted( |
| 403 | (left, right) => right.localeCompare(left, undefined, { numeric: true }), |
| 404 | ); |
| 405 | for (const version of versions) { |
| 406 | for (const candidateTarget of resolveAcpRegistryPlatformTargetCandidates(target)) { |
| 407 | const installRoot = path.join(installsDirectory, agent, version, candidateTarget); |
| 408 | if (yield* fileSystem.exists(installRoot).pipe(Effect.orElseSucceed(() => false))) { |
| 409 | const binaryTarget = cachedAgentByInstall.get(`${agent}\0${version}`)?.distribution |
| 410 | .binary?.[candidateTarget]; |
| 411 | const commandSegments = |
| 412 | binaryTarget === undefined |
| 413 | ? undefined |
| 414 | : normalizeRegistryCommandPath(binaryTarget.cmd); |
| 415 | const directory = |
| 416 | commandSegments === undefined |
| 417 | ? installRoot |
| 418 | : path.join(installRoot, ...commandSegments.slice(0, -1)); |
| 419 | if (yield* fileSystem.exists(directory).pipe(Effect.orElseSucceed(() => false))) { |
| 420 | directories.push(directory); |
| 421 | } |
| 422 | } |
| 423 | } |
| 424 | } |
| 425 | } |
| 426 | return Array.from(new Set(directories)); |
| 427 | }, |
| 428 | ); |
| 429 | |
| 430 | export interface ResolvedAcpRegistryDistribution { |
| 431 | readonly kind: AcpRegistryDistributionKind; |
| 432 | readonly args: ReadonlyArray<string>; |
| 433 | readonly env: Readonly<Record<string, string>>; |
| 434 | readonly binaryTarget?: typeof AcpRegistryBinaryTarget.Type; |
| 435 | readonly packageName?: string; |
| 436 | } |
| 437 | |
| 438 | export function resolveAcpRegistryDistribution(input: { |
| 439 | readonly agent: AcpRegistryAgent; |
| 440 | readonly preference: AcpRegistryDistributionPreference; |
| 441 | readonly platformTarget: AcpRegistryPlatformTarget | undefined; |
| 442 | }): ResolvedAcpRegistryDistribution | undefined { |
| 443 | const { agent, platformTarget } = input; |
| 444 | const binary = resolveAcpRegistryPlatformTargetCandidates(platformTarget) |
| 445 | .map((candidate) => agent.distribution.binary?.[candidate]) |
| 446 | .find((entry) => entry !== undefined); |
| 447 | const candidates: ReadonlyArray<AcpRegistryDistributionKind> = |
| 448 | input.preference === "auto" ? ["binary", "npx", "uvx"] : [input.preference]; |
| 449 | |
| 450 | for (const kind of candidates) { |
| 451 | if (kind === "binary" && binary) { |
| 452 | return { |
| 453 | kind, |
| 454 | args: binary.args ?? [], |
| 455 | env: binary.env ?? {}, |
| 456 | binaryTarget: binary, |
| 457 | }; |
| 458 | } |
| 459 | if (kind === "npx" && agent.distribution.npx) { |
| 460 | return { |
| 461 | kind, |
| 462 | args: agent.distribution.npx.args ?? [], |
| 463 | env: agent.distribution.npx.env ?? {}, |
| 464 | packageName: agent.distribution.npx.package, |
| 465 | }; |
| 466 | } |
| 467 | if (kind === "uvx" && agent.distribution.uvx) { |
| 468 | return { |
| 469 | kind, |
| 470 | args: agent.distribution.uvx.args ?? [], |
| 471 | env: agent.distribution.uvx.env ?? {}, |
| 472 | packageName: agent.distribution.uvx.package, |
| 473 | }; |
| 474 | } |
| 475 | } |
| 476 | return undefined; |
| 477 | } |
| 478 | |
| 479 | export interface ResolvedAcpRegistryAgent { |
| 480 | readonly agent?: AcpRegistryAgent; |
| 481 | readonly distribution: AcpRegistryDistributionKind | "local"; |
| 482 | readonly spawn: AcpSessionRuntime.AcpSpawnInput; |
| 483 | } |
| 484 | |
| 485 | export type AcpRegistryInspection = |
| 486 | | { readonly status: "unconfigured" } |
| 487 | | { readonly status: "not_found"; readonly agentId: string } |
| 488 | | { |
| 489 | readonly status: "unsupported"; |
| 490 | readonly agentId: string; |
| 491 | readonly version: string; |
| 492 | } |
| 493 | | { |
| 494 | readonly status: "missing_runner"; |
| 495 | readonly agentId: string; |
| 496 | readonly version: string; |
| 497 | readonly distribution: AcpRegistryDistributionKind; |
| 498 | readonly runner: string; |
| 499 | } |
| 500 | | { |
| 501 | readonly status: "missing_runner"; |
| 502 | readonly version: null; |
| 503 | readonly distribution: "local"; |
| 504 | } |
| 505 | | { |
| 506 | readonly status: "unprepared"; |
| 507 | readonly agentId: string; |
| 508 | readonly version: string; |
| 509 | readonly distribution: "binary"; |
| 510 | } |
| 511 | | { |
| 512 | readonly status: "ready"; |
| 513 | readonly agentId: string; |
| 514 | readonly version: string | null; |
| 515 | readonly distribution: AcpRegistryDistributionKind | "local"; |
| 516 | readonly documentationUrl?: string; |
| 517 | }; |
| 518 | |
| 519 | export class AcpRegistryCatalog extends Context.Service< |
| 520 | AcpRegistryCatalog, |
| 521 | { |
| 522 | readonly search: ( |
| 523 | input: AcpRegistrySearchInput, |
| 524 | ) => Effect.Effect<AcpRegistrySearchResult, AcpRegistryError>; |
| 525 | readonly prepare: ( |
| 526 | input: AcpRegistryPrepareInput, |
| 527 | ) => Effect.Effect<AcpRegistryPrepareResult, AcpRegistryError>; |
| 528 | readonly inspect: ( |
| 529 | settings: AcpRegistrySettings, |
| 530 | environment?: NodeJS.ProcessEnv, |
| 531 | ) => Effect.Effect<AcpRegistryInspection, AcpRegistryError>; |
| 532 | readonly resolve: ( |
| 533 | settings: AcpRegistrySettings, |
| 534 | cwd: string, |
| 535 | environment?: NodeJS.ProcessEnv, |
| 536 | ) => Effect.Effect<ResolvedAcpRegistryAgent, AcpRegistryError, Scope.Scope>; |
| 537 | readonly uninstallManagedBinary: ( |
| 538 | input: AcpRegistryManagedBinaryUninstallInput, |
| 539 | ) => Effect.Effect<AcpRegistryManagedBinaryUninstallResult, AcpRegistryError>; |
| 540 | } |
| 541 | >()("@t3tools/provider-acp-registry/server/AcpRegistrySupport/AcpRegistryCatalog") {} |
| 542 | |
| 543 | const layer = (options: AcpRegistryCatalogOptions) => |
| 544 | Layer.effect(AcpRegistryCatalog, makeAcpRegistryCatalog(options)); |
| 545 | |
| 546 | export const layerFromHost = Layer.merge( |
| 547 | Layer.unwrap( |
| 548 | Effect.gen(function* () { |
| 549 | const { paths } = yield* ProviderHost.ProviderHost; |
| 550 | const path = yield* Path.Path; |
| 551 | return layer({ |
| 552 | cacheDir: paths.providerStatusCacheDir, |
| 553 | toolsDir: path.join(paths.baseDir, "tools"), |
| 554 | // Beside the built-in driver's runtime temp, short for Windows' 260-character path limit. |
| 555 | runtimeTempDir: path.join(paths.stateDir, "antigravity-tmp", "acp-registry"), |
| 556 | }); |
| 557 | }), |
| 558 | ), |
| 559 | AcpRegistryRuntimeCoordinator.layer, |
| 560 | ); |
| 561 | |
| 562 | export interface AcpRegistryCatalogOptions { |
| 563 | readonly cacheDir: string; |
| 564 | readonly toolsDir: string; |
| 565 | /** Owns the temp files of agents whose unpacker cannot clean up after a kill. */ |
| 566 | readonly runtimeTempDir?: string; |
| 567 | readonly registryUrl?: string; |
| 568 | } |
| 569 | |
| 570 | // Unpacks about 140 MB into TEMP on every launch and cannot remove it when the process is killed. |
| 571 | const UNPACKING_AGENT_IDS: ReadonlySet<string> = new Set(["antigravity-acp"]); |
| 572 | |
| 573 | const INSTALL_LOCK_RETRY_COUNT = 300; |
| 574 | const INSTALL_LOCK_RETRY_DELAY = "100 millis"; |
| 575 | const INSTALL_LOCK_STALE_MS = 5 * 60 * 1_000; |
| 576 | const PREPARED_BINARY_RESERVATION_MS = 30 * 1_000; |
| 577 | |
| 578 | function isAlreadyExists(error: PlatformError.PlatformError): boolean { |
| 579 | return error.reason._tag === "AlreadyExists"; |
| 580 | } |
| 581 | |
| 582 | function normalizeRegistryCommandPath(command: string): ReadonlyArray<string> | undefined { |
| 583 | const normalized = command.trim().replaceAll("\\", "/").replace(/^\.\//u, ""); |
| 584 | const segments = normalized.split("/").filter((segment) => segment.length > 0); |
| 585 | if ( |
| 586 | segments.length === 0 || |
| 587 | normalized.startsWith("/") || |
| 588 | /^[a-zA-Z]:/u.test(normalized) || |
| 589 | segments.some((segment) => segment === "." || segment === "..") |
| 590 | ) { |
| 591 | return undefined; |
| 592 | } |
| 593 | return segments; |
| 594 | } |
| 595 | |
| 596 | function validateArchiveEntries(output: string): boolean { |
| 597 | return output |
| 598 | .split(/\r?\n/u) |
| 599 | .map((entry) => entry.trim()) |
| 600 | .filter((entry) => entry.length > 0) |
| 601 | .every((entry) => entry === "./" || normalizeRegistryCommandPath(entry) !== undefined); |
| 602 | } |
| 603 | |
| 604 | type ArchiveKind = "raw" | "tar_bz2" | "tar_gz" | "zip"; |
| 605 | |
| 606 | function archiveKind(url: string): ArchiveKind { |
| 607 | const pathname = new URL(url).pathname.toLowerCase(); |
| 608 | if (pathname.endsWith(".tar.gz") || pathname.endsWith(".tgz")) return "tar_gz"; |
| 609 | if (pathname.endsWith(".tar.bz2") || pathname.endsWith(".tbz2")) return "tar_bz2"; |
| 610 | if (pathname.endsWith(".zip")) return "zip"; |
| 611 | return "raw"; |
| 612 | } |
| 613 | |
| 614 | function archiveFileName(kind: ArchiveKind): string { |
| 615 | switch (kind) { |
| 616 | case "tar_gz": |
| 617 | return "agent.tar.gz"; |
| 618 | case "tar_bz2": |
| 619 | return "agent.tar.bz2"; |
| 620 | case "zip": |
| 621 | return "agent.zip"; |
| 622 | case "raw": |
| 623 | return "agent.bin"; |
| 624 | } |
| 625 | } |
| 626 | |
| 627 | function compareText(left: string, right: string): number { |
| 628 | return left < right ? -1 : left > right ? 1 : 0; |
| 629 | } |
| 630 | |
| 631 | function searchRank(agent: AcpRegistryAgent, query: string): number | undefined { |
| 632 | const normalized = query.trim().toLowerCase(); |
| 633 | if (normalized.length === 0) return 100; |
| 634 | |
| 635 | const id = agent.id.toLowerCase(); |
| 636 | const name = agent.name.toLowerCase(); |
| 637 | const authors = (agent.authors ?? []).join(" ").toLowerCase(); |
| 638 | const description = agent.description.toLowerCase(); |
| 639 | const terms = normalized.split(/\s+/u); |
| 640 | if (id === normalized || name === normalized) return 0; |
| 641 | if (id.startsWith(normalized) || name.startsWith(normalized)) return 10; |
| 642 | |
| 643 | const identityTokens = `${id} ${name}`.split(/[^a-z0-9]+/u).filter(Boolean); |
| 644 | if (terms.every((term) => identityTokens.some((token) => token.startsWith(term)))) return 20; |
| 645 | if (terms.every((term) => id.includes(term) || name.includes(term))) return 30; |
| 646 | if (terms.every((term) => authors.includes(term))) return 40; |
| 647 | if (terms.every((term) => `${id} ${name} ${authors} ${description}`.includes(term))) return 50; |
| 648 | return undefined; |
| 649 | } |
| 650 | |
| 651 | export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(function* ( |
| 652 | input: AcpRegistryCatalogOptions, |
| 653 | ): Effect.fn.Return< |
| 654 | AcpRegistryCatalog["Service"], |
| 655 | never, |
| 656 | | ChildProcessSpawner.ChildProcessSpawner |
| 657 | | SecureRandom.SecureRandom |
| 658 | | Digest.Digest |
| 659 | | FileSystem.FileSystem |
| 660 | | HttpClient.HttpClient |
| 661 | | Path.Path |
| 662 | | ProviderHost.ProviderHost |
| 663 | > { |
| 664 | const random = yield* SecureRandom.SecureRandom; |
| 665 | const digester = yield* Digest.Digest; |
| 666 | const sha256Hex = (data: Uint8Array) => |
| 667 | digester.digest(Digest.sha256, data).pipe(Effect.map(Hex.encode), Effect.orDie); |
| 668 | const fileSystem = yield* FileSystem.FileSystem; |
| 669 | const path = yield* Path.Path; |
| 670 | const httpClient = yield* HttpClient.HttpClient; |
| 671 | const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 672 | const { settings: hostSettings } = yield* ProviderHost.ProviderHost; |
| 673 | const platform = yield* HostProcess.Platform; |
| 674 | const architecture = yield* HostProcess.Architecture; |
| 675 | const hostEnvironment = yield* HostProcess.Environment; |
| 676 | const resolveExecutable = yield* SpawnExecutableResolution; |
| 677 | const platformTarget = resolveAcpRegistryPlatformTarget(platform, architecture); |
| 678 | const registryUrl = input.registryUrl ?? ACP_REGISTRY_URL; |
| 679 | const registryDirectory = path.join(input.cacheDir, "acp-registry"); |
| 680 | const registryCachePath = path.join(registryDirectory, "registry.json"); |
| 681 | const installsDirectory = input.toolsDir; |
| 682 | const agentInstallRoot = (agent: AcpRegistryAgent) => |
| 683 | path.join(installsDirectory, agent.id, encodeURIComponent(agent.version)); |
| 684 | const packageInstallRoot = (agent: AcpRegistryAgent, distribution: "npx" | "uvx") => |
| 685 | path.join(agentInstallRoot(agent), distribution === "npx" ? "npm" : "python"); |
| 686 | const packageBinDirectory = (agent: AcpRegistryAgent, distribution: "npx" | "uvx") => |
| 687 | distribution === "npx" && platform === "win32" |
| 688 | ? packageInstallRoot(agent, distribution) |
| 689 | : path.join(packageInstallRoot(agent, distribution), "bin"); |
| 690 | const packageReceiptsDirectory = path.join(registryDirectory, "package-installs"); |
| 691 | const registryRef = yield* Ref.make<AcpRegistryIndex | undefined>(undefined); |
| 692 | // When the network last served registryRef; unset while it holds the disk cache. |
| 693 | const registryFetchedAtMs = yield* Ref.make<number | undefined>(undefined); |
| 694 | const registryRevision = yield* Ref.make(0); |
| 695 | const registrySemaphore = yield* Semaphore.make(1); |
| 696 | // Long installs must only block operations on the same agent. |
| 697 | const installPermits = new Map<string, Semaphore.Semaphore>(); |
| 698 | const withInstallPermit = (agentId: string) => { |
| 699 | const permit = installPermits.get(agentId) ?? Semaphore.makeUnsafe(1); |
| 700 | installPermits.set(agentId, permit); |
| 701 | return permit.withPermits(1); |
| 702 | }; |
| 703 | const preparedBinaryReservations = yield* Ref.make<ReadonlyMap<string, number>>(new Map()); |
| 704 | |
| 705 | const runtimeTempDir = input.runtimeTempDir; |
| 706 | if (runtimeTempDir !== undefined) { |
| 707 | // Move leftovers of a previous server aside so the slow delete cannot race new runs. |
| 708 | const parent = path.dirname(runtimeTempDir); |
| 709 | const prefix = `${path.basename(runtimeTempDir)}.old-`; |
| 710 | const retire = Effect.gen(function* () { |
| 711 | if (yield* fileSystem.exists(runtimeTempDir)) { |
| 712 | yield* fileSystem.makeTempDirectory({ directory: parent, prefix }).pipe( |
| 713 | Effect.flatMap((retired) => |
| 714 | fileSystem.rename(runtimeTempDir, path.join(retired, "runtime")), |
| 715 | ), |
| 716 | Effect.catch(() => fileSystem.remove(runtimeTempDir, { recursive: true, force: true })), |
| 717 | ); |
| 718 | } |
| 719 | return yield* fileSystem.readDirectory(parent); |
| 720 | }).pipe(Effect.orElseSucceed((): ReadonlyArray<string> => [])); |
| 721 | const retired = (yield* retire).filter((entry) => entry.startsWith(prefix)); |
| 722 | yield* Effect.forkDetach( |
| 723 | Effect.forEach( |
| 724 | retired, |
| 725 | (entry) => |
| 726 | fileSystem |
| 727 | .remove(path.join(parent, entry), { recursive: true, force: true }) |
| 728 | .pipe( |
| 729 | Effect.catch(() => |
| 730 | Effect.logWarning("Could not remove leftover ACP agent temp files."), |
| 731 | ), |
| 732 | ), |
| 733 | { discard: true }, |
| 734 | ), |
| 735 | ); |
| 736 | } |
| 737 | |
| 738 | // One directory per process, removed after it exits; the next server start sweeps what Windows kept. |
| 739 | const acquireRuntimeTempEnvironment = Effect.fn("AcpRegistryCatalog.acquireRuntimeTemp")( |
| 740 | function* (root: string, environment: NodeJS.ProcessEnv) { |
| 741 | const directory = yield* Effect.acquireRelease( |
| 742 | fileSystem.makeDirectory(root, { recursive: true }).pipe( |
| 743 | Effect.andThen(fileSystem.makeTempDirectory({ directory: root, prefix: "run-" })), |
| 744 | Effect.mapError( |
| 745 | (cause) => |
| 746 | new AcpRegistryError({ |
| 747 | reason: "install_failed", |
| 748 | detail: "Could not create a temp directory for the ACP agent.", |
| 749 | cause, |
| 750 | }), |
| 751 | ), |
| 752 | ), |
| 753 | (directory) => { |
| 754 | const remove = fileSystem.remove(directory, { recursive: true, force: true }); |
| 755 | // Windows keeps a killed process's files locked for a few seconds after it exits. |
| 756 | const retry = remove.pipe( |
| 757 | Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 30 }), |
| 758 | Effect.catch(() => Effect.logWarning("Could not remove an ACP agent temp directory.")), |
| 759 | ); |
| 760 | return remove.pipe(Effect.catch(() => Effect.asVoid(Effect.forkDetach(retry)))); |
| 761 | }, |
| 762 | ); |
| 763 | if (platform !== "win32") return { ...environment, TMPDIR: directory }; |
| 764 | // Windows env keys are case-insensitive; drop aliases so ours win. |
| 765 | const rest = Object.fromEntries( |
| 766 | Object.entries(environment).filter(([key]) => !["temp", "tmp"].includes(key.toLowerCase())), |
| 767 | ); |
| 768 | return { ...rest, TEMP: directory, TMP: directory }; |
| 769 | }, |
| 770 | ); |
| 771 | |
| 772 | const managerBinDirectory = Effect.fn("AcpRegistryCatalog.managerBinDirectory")(function* ( |
| 773 | runner: string, |
| 774 | ) { |
| 775 | const linkedTarget = yield* fileSystem.readLink(runner).pipe(Effect.option); |
| 776 | if (Option.isNone(linkedTarget)) return path.dirname(runner); |
| 777 | const target = path.isAbsolute(linkedTarget.value) |
| 778 | ? linkedTarget.value |
| 779 | : path.resolve(path.dirname(runner), linkedTarget.value); |
| 780 | // Wrapper symlinks may identify the toolchain bin directory; npm-cli.js points inside npm instead. |
| 781 | return path.basename(target) === path.basename(runner) |
| 782 | ? path.dirname(target) |
| 783 | : path.dirname(runner); |
| 784 | }); |
| 785 | |
| 786 | const reservePreparedBinary = Effect.fn("AcpRegistryCatalog.reservePreparedBinary")(function* ( |
| 787 | agentId: string, |
| 788 | ) { |
| 789 | const now = yield* Clock.currentTimeMillis; |
| 790 | yield* Ref.update(preparedBinaryReservations, (current) => { |
| 791 | const next = new Map(Array.from(current).filter(([, expiresAt]) => expiresAt > now)); |
| 792 | next.set(agentId, now + PREPARED_BINARY_RESERVATION_MS); |
| 793 | return next; |
| 794 | }); |
| 795 | }); |
| 796 | |
| 797 | const consumePreparedBinaryReservation = (agentId: string) => |
| 798 | Ref.update(preparedBinaryReservations, (current) => { |
| 799 | if (!current.has(agentId)) return current; |
| 800 | const next = new Map(current); |
| 801 | next.delete(agentId); |
| 802 | return next; |
| 803 | }); |
| 804 | |
| 805 | const hasPreparedBinaryReservation = Effect.fn("AcpRegistryCatalog.hasPreparedBinaryReservation")( |
| 806 | function* (agentId: string) { |
| 807 | const now = yield* Clock.currentTimeMillis; |
| 808 | return yield* Ref.modify(preparedBinaryReservations, (current) => { |
| 809 | const expiresAt = current.get(agentId); |
| 810 | if (expiresAt === undefined || expiresAt <= now) { |
| 811 | if (expiresAt === undefined) return [false, current] as const; |
| 812 | const next = new Map(current); |
| 813 | next.delete(agentId); |
| 814 | return [false, next] as const; |
| 815 | } |
| 816 | return [true, current] as const; |
| 817 | }); |
| 818 | }, |
| 819 | ); |
| 820 | |
| 821 | const assertHttpsUrl = Effect.fn("AcpRegistryCatalog.assertHttpsUrl")(function* ( |
| 822 | value: string, |
| 823 | detail: string, |
| 824 | ) { |
| 825 | const valid = yield* decodeHttpsUrl(value).pipe(Effect.option); |
| 826 | if (Option.isNone(valid)) { |
| 827 | return yield* new AcpRegistryError({ reason: "registry_unavailable", detail }); |
| 828 | } |
| 829 | return value; |
| 830 | }); |
| 831 | |
| 832 | const decodeRegistryText = Effect.fn("AcpRegistryCatalog.decodeRegistryText")(function* ( |
| 833 | text: string, |
| 834 | ) { |
| 835 | const decoded = yield* decodeJson(text).pipe( |
| 836 | Effect.mapError( |
| 837 | (cause) => |
| 838 | new AcpRegistryError({ |
| 839 | reason: "registry_unavailable", |
| 840 | detail: "ACP Registry returned invalid JSON.", |
| 841 | cause, |
| 842 | }), |
| 843 | ), |
| 844 | ); |
| 845 | const envelope = yield* decodeRegistryIndexEnvelope(decoded).pipe( |
| 846 | Effect.mapError( |
| 847 | (cause) => |
| 848 | new AcpRegistryError({ |
| 849 | reason: "registry_unavailable", |
| 850 | detail: "ACP Registry returned an invalid index.", |
| 851 | cause, |
| 852 | }), |
| 853 | ), |
| 854 | ); |
| 855 | const agents = envelope.agents.flatMap((candidate) => { |
| 856 | const decodedAgent = decodeRegistryAgent(candidate); |
| 857 | return Option.isSome(decodedAgent) ? [decodedAgent.value] : []; |
| 858 | }); |
| 859 | const discarded = envelope.agents.length - agents.length; |
| 860 | if (discarded > 0) { |
| 861 | yield* Effect.logWarning("ignored invalid ACP Registry entries", { discarded }); |
| 862 | } |
| 863 | return { version: envelope.version, agents } satisfies AcpRegistryIndex; |
| 864 | }); |
| 865 | |
| 866 | const readCachedRegistry = fileSystem |
| 867 | .readFileString(registryCachePath) |
| 868 | .pipe(Effect.flatMap(decodeRegistryText), Effect.option); |
| 869 | |
| 870 | const writeRegistryCache = (text: string) => |
| 871 | random.uuidV4().pipe( |
| 872 | Effect.flatMap((id) => { |
| 873 | const temporaryPath = `${registryCachePath}.${process.pid}-${id}.tmp`; |
| 874 | return fileSystem |
| 875 | .makeDirectory(registryDirectory, { recursive: true }) |
| 876 | .pipe( |
| 877 | Effect.andThen(fileSystem.writeFileString(temporaryPath, text)), |
| 878 | Effect.andThen(fileSystem.rename(temporaryPath, registryCachePath)), |
| 879 | Effect.ensuring(fileSystem.remove(temporaryPath, { force: true }).pipe(Effect.ignore)), |
| 880 | ); |
| 881 | }), |
| 882 | Effect.ignore, |
| 883 | ); |
| 884 | |
| 885 | const fetchRegistry = Effect.fn("AcpRegistryCatalog.fetchRegistry")(function* () { |
| 886 | yield* assertHttpsUrl(registryUrl, "ACP Registry index URL must use HTTPS."); |
| 887 | const response = yield* httpClient.execute(HttpClientRequest.get(registryUrl)).pipe( |
| 888 | Effect.flatMap(HttpClientResponse.filterStatusOk), |
| 889 | Effect.mapError( |
| 890 | (cause) => |
| 891 | new AcpRegistryError({ |
| 892 | reason: "registry_unavailable", |
| 893 | detail: `Could not fetch ACP Registry index from ${registryUrl}.`, |
| 894 | cause, |
| 895 | }), |
| 896 | ), |
| 897 | Effect.timeoutOrElse({ |
| 898 | duration: REGISTRY_REQUEST_TIMEOUT, |
| 899 | orElse: () => |
| 900 | Effect.fail( |
| 901 | new AcpRegistryError({ |
| 902 | reason: "registry_unavailable", |
| 903 | detail: "Timed out fetching ACP Registry index.", |
| 904 | }), |
| 905 | ), |
| 906 | }), |
| 907 | ); |
| 908 | const collected = yield* collectUint8StreamText({ |
| 909 | stream: response.stream, |
| 910 | maxBytes: MAX_REGISTRY_BYTES + 1, |
| 911 | }).pipe( |
| 912 | Effect.mapError( |
| 913 | (cause) => |
| 914 | new AcpRegistryError({ |
| 915 | reason: "registry_unavailable", |
| 916 | detail: "Could not read ACP Registry response body.", |
| 917 | cause, |
| 918 | }), |
| 919 | ), |
| 920 | Effect.timeoutOrElse({ |
| 921 | duration: REGISTRY_REQUEST_TIMEOUT, |
| 922 | orElse: () => |
| 923 | Effect.fail( |
| 924 | new AcpRegistryError({ |
| 925 | reason: "registry_unavailable", |
| 926 | detail: "Timed out reading ACP Registry response body.", |
| 927 | }), |
| 928 | ), |
| 929 | }), |
| 930 | ); |
| 931 | if (collected.truncated || collected.bytes > MAX_REGISTRY_BYTES) { |
| 932 | return yield* new AcpRegistryError({ |
| 933 | reason: "registry_unavailable", |
| 934 | detail: `ACP Registry index exceeds ${MAX_REGISTRY_BYTES} bytes.`, |
| 935 | }); |
| 936 | } |
| 937 | if (collected.invalidUtf8) { |
| 938 | return yield* new AcpRegistryError({ |
| 939 | reason: "registry_unavailable", |
| 940 | detail: "ACP Registry index is not valid UTF-8.", |
| 941 | }); |
| 942 | } |
| 943 | const registry = yield* decodeRegistryText(collected.text); |
| 944 | yield* writeRegistryCache(collected.text); |
| 945 | return registry; |
| 946 | }); |
| 947 | |
| 948 | const refreshRegistry = Effect.fn("AcpRegistryCatalog.refreshRegistry")(function* () { |
| 949 | const observedRevision = yield* Ref.get(registryRevision); |
| 950 | return yield* registrySemaphore.withPermits(1)( |
| 951 | Effect.gen(function* () { |
| 952 | const currentRevision = yield* Ref.get(registryRevision); |
| 953 | const current = yield* Ref.get(registryRef); |
| 954 | if (current !== undefined && currentRevision !== observedRevision) return current; |
| 955 | |
| 956 | const { registry, fetched } = yield* fetchRegistry().pipe( |
| 957 | Effect.map((registry) => ({ registry, fetched: true })), |
| 958 | Effect.catch((networkError) => |
| 959 | readCachedRegistry.pipe( |
| 960 | Effect.flatMap( |
| 961 | Option.match({ |
| 962 | onNone: () => Effect.fail(networkError), |
| 963 | onSome: (registry) => Effect.succeed({ registry, fetched: false }), |
| 964 | }), |
| 965 | ), |
| 966 | ), |
| 967 | ), |
| 968 | ); |
| 969 | yield* Ref.set(registryRef, registry); |
| 970 | yield* Ref.set(registryFetchedAtMs, fetched ? yield* Clock.currentTimeMillis : undefined); |
| 971 | yield* Ref.update(registryRevision, (revision) => revision + 1); |
| 972 | return registry; |
| 973 | }), |
| 974 | ); |
| 975 | }); |
| 976 | |
| 977 | const recentRegistry = Effect.fn("AcpRegistryCatalog.recentRegistry")(function* () { |
| 978 | const current = yield* Ref.get(registryRef); |
| 979 | const fetchedAtMs = yield* Ref.get(registryFetchedAtMs); |
| 980 | const now = yield* Clock.currentTimeMillis; |
| 981 | // A clock moved back makes the stamp untrustworthy, so it counts as stale. |
| 982 | if ( |
| 983 | current !== undefined && |
| 984 | fetchedAtMs !== undefined && |
| 985 | now >= fetchedAtMs && |
| 986 | now - fetchedAtMs < REGISTRY_SEARCH_MAX_AGE_MS |
| 987 | ) { |
| 988 | return current; |
| 989 | } |
| 990 | return yield* refreshRegistry(); |
| 991 | }); |
| 992 | |
| 993 | const loadRegistry = Effect.fn("AcpRegistryCatalog.loadRegistry")(function* () { |
| 994 | const current = yield* Ref.get(registryRef); |
| 995 | if (current !== undefined) return current; |
| 996 | |
| 997 | const cached = yield* readCachedRegistry; |
| 998 | if (Option.isNone(cached)) return yield* refreshRegistry(); |
| 999 | yield* Ref.set(registryRef, cached.value); |
| 1000 | return cached.value; |
| 1001 | }); |
| 1002 | |
| 1003 | const runCommand = Effect.fn("AcpRegistryCatalog.runCommand")(function* ( |
| 1004 | command: string, |
| 1005 | args: ReadonlyArray<string>, |
| 1006 | options: { |
| 1007 | readonly cwd?: string; |
| 1008 | readonly env?: NodeJS.ProcessEnv; |
| 1009 | readonly timeout?: Duration.Input; |
| 1010 | readonly truncatedOutputReason?: AcpRegistryErrorReason; |
| 1011 | readonly maxStdoutBytes?: number; |
| 1012 | } = {}, |
| 1013 | ) { |
| 1014 | const collect = Effect.gen(function* () { |
| 1015 | const resolved = yield* resolveSpawnCommand( |
| 1016 | command, |
| 1017 | args, |
| 1018 | options.env === undefined ? {} : { env: options.env }, |
| 1019 | ); |
| 1020 | const child = yield* spawner.spawn( |
| 1021 | ChildProcess.make(resolved.command, resolved.args, { |
| 1022 | ...(options.cwd ? { cwd: options.cwd } : {}), |
| 1023 | ...(options.env === undefined ? {} : { env: options.env }), |
| 1024 | shell: resolved.shell, |
| 1025 | }), |
| 1026 | ); |
| 1027 | yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore)); |
| 1028 | const [stdout, stderr, exitCode] = yield* Effect.all( |
| 1029 | [ |
| 1030 | collectUint8StreamText({ |
| 1031 | stream: child.stdout, |
| 1032 | maxBytes: options.maxStdoutBytes ?? MAX_COMMAND_OUTPUT_BYTES, |
| 1033 | }), |
| 1034 | child.stderr.pipe( |
| 1035 | Stream.decodeText(), |
| 1036 | Stream.runFold( |
| 1037 | () => "", |
| 1038 | (tail, text) => `${tail}${text}`.slice(-MAX_COMMAND_ERROR_TAIL_CHARS), |
| 1039 | ), |
| 1040 | ), |
| 1041 | child.exitCode, |
| 1042 | ], |
| 1043 | { concurrency: "unbounded" }, |
| 1044 | ); |
| 1045 | if (Number(exitCode) !== 0) { |
| 1046 | return yield* new AcpRegistryError({ |
| 1047 | reason: "install_failed", |
| 1048 | detail: `ACP Registry install command '${command}' exited with code ${Number(exitCode)}: ${stderr.trim()}`, |
| 1049 | }); |
| 1050 | } |
| 1051 | // Truncated listings would bypass archive traversal validation. |
| 1052 | if (stdout.truncated) { |
| 1053 | return yield* new AcpRegistryError({ |
| 1054 | reason: options.truncatedOutputReason ?? "archive_invalid", |
| 1055 | detail: `ACP Registry install command '${command}' produced more output than expected.`, |
| 1056 | }); |
| 1057 | } |
| 1058 | return stdout.text; |
| 1059 | }); |
| 1060 | const scoped = collect.pipe( |
| 1061 | Effect.scoped, |
| 1062 | Effect.mapError((cause) => |
| 1063 | isAcpRegistryError(cause) |
| 1064 | ? cause |
| 1065 | : new AcpRegistryError({ |
| 1066 | reason: "install_failed", |
| 1067 | detail: `Could not run ACP Registry install command '${command}'.`, |
| 1068 | cause, |
| 1069 | }), |
| 1070 | ), |
| 1071 | ); |
| 1072 | return yield* options.timeout === undefined |
| 1073 | ? scoped |
| 1074 | : scoped.pipe( |
| 1075 | Effect.timeoutOrElse({ |
| 1076 | duration: options.timeout, |
| 1077 | orElse: () => |
| 1078 | Effect.fail( |
| 1079 | new AcpRegistryError({ |
| 1080 | reason: "install_failed", |
| 1081 | detail: `Timed out running ACP Registry install command '${command}'.`, |
| 1082 | }), |
| 1083 | ), |
| 1084 | }), |
| 1085 | ); |
| 1086 | }); |
| 1087 | |
| 1088 | const packageReceiptPath = (agentId: string, distribution: "npx" | "uvx", managerPath: string) => |
| 1089 | sha256Hex(new TextEncoder().encode(`${distribution}\0${managerPath}`)).pipe( |
| 1090 | Effect.map((digest) => |
| 1091 | path.join(packageReceiptsDirectory, `${agentId}-${digest.slice(0, 16)}.json`), |
| 1092 | ), |
| 1093 | ); |
| 1094 | |
| 1095 | const readPackageReceipt = Effect.fn("AcpRegistryCatalog.readPackageReceipt")(function* ( |
| 1096 | agent: AcpRegistryAgent, |
| 1097 | distribution: "npx" | "uvx", |
| 1098 | packageSpec: string, |
| 1099 | managerPath: string, |
| 1100 | ) { |
| 1101 | const receipt = yield* fileSystem |
| 1102 | .readFileString(yield* packageReceiptPath(agent.id, distribution, managerPath)) |
| 1103 | .pipe( |
| 1104 | Effect.map(decodePackageInstallReceipt), |
| 1105 | Effect.orElseSucceed(() => Option.none()), |
| 1106 | ); |
| 1107 | if ( |
| 1108 | Option.isNone(receipt) || |
| 1109 | receipt.value.agentId !== agent.id || |
| 1110 | receipt.value.agentVersion !== agent.version || |
| 1111 | receipt.value.distribution !== distribution || |
| 1112 | receipt.value.packageSpec !== packageSpec || |
| 1113 | receipt.value.managerPath !== managerPath || |
| 1114 | receipt.value.binDirectory !== packageBinDirectory(agent, distribution) || |
| 1115 | path.dirname(receipt.value.executablePath) !== receipt.value.binDirectory |
| 1116 | ) { |
| 1117 | return Option.none<AcpRegistryPackageInstallReceipt>(); |
| 1118 | } |
| 1119 | const executableExists = yield* fileSystem |
| 1120 | .exists(receipt.value.executablePath) |
| 1121 | .pipe(Effect.orElseSucceed(() => false)); |
| 1122 | if (!executableExists) return Option.none<AcpRegistryPackageInstallReceipt>(); |
| 1123 | |
| 1124 | if (distribution === "npx") { |
| 1125 | const packageIdentity = parseNpxPackageSpec(packageSpec); |
| 1126 | if (receipt.value.packageRoot === undefined || receipt.value.packageVersion === undefined) { |
| 1127 | return Option.none<AcpRegistryPackageInstallReceipt>(); |
| 1128 | } |
| 1129 | const manifest = yield* fileSystem |
| 1130 | .readFileString(path.join(receipt.value.packageRoot, "package.json")) |
| 1131 | .pipe(Effect.flatMap(decodeNpmPackageManifest), Effect.option); |
| 1132 | if ( |
| 1133 | Option.isNone(manifest) || |
| 1134 | manifest.value.name !== packageIdentity.name || |
| 1135 | manifest.value.version !== packageIdentity.version || |
| 1136 | receipt.value.packageVersion !== packageIdentity.version |
| 1137 | ) { |
| 1138 | return Option.none<AcpRegistryPackageInstallReceipt>(); |
| 1139 | } |
| 1140 | } |
| 1141 | return receipt; |
| 1142 | }); |
| 1143 | |
| 1144 | const writePackageReceipt = Effect.fn("AcpRegistryCatalog.writePackageReceipt")( |
| 1145 | function* (receipt: AcpRegistryPackageInstallReceipt) { |
| 1146 | const receiptPath = yield* packageReceiptPath( |
| 1147 | receipt.agentId, |
| 1148 | receipt.distribution, |
| 1149 | receipt.managerPath, |
| 1150 | ); |
| 1151 | const temporaryPath = `${receiptPath}.${process.pid}.tmp`; |
| 1152 | yield* fileSystem.makeDirectory(packageReceiptsDirectory, { recursive: true }); |
| 1153 | yield* fileSystem.remove(temporaryPath, { force: true }); |
| 1154 | yield* fileSystem.writeFileString(temporaryPath, `${encodePackageInstallReceipt(receipt)}\n`); |
| 1155 | yield* fileSystem.remove(receiptPath, { force: true }); |
| 1156 | yield* fileSystem.rename(temporaryPath, receiptPath); |
| 1157 | }, |
| 1158 | Effect.mapError((cause) => |
| 1159 | isAcpRegistryError(cause) |
| 1160 | ? cause |
| 1161 | : new AcpRegistryError({ |
| 1162 | reason: "install_failed", |
| 1163 | detail: "Could not record the globally installed ACP Registry command.", |
| 1164 | cause, |
| 1165 | }), |
| 1166 | ), |
| 1167 | ); |
| 1168 | |
| 1169 | const parsePackageManagerPath = Effect.fn("AcpRegistryCatalog.parsePackageManagerPath")( |
| 1170 | function* (managerPath: string, output: string) { |
| 1171 | const lines = output |
| 1172 | .split(/\r?\n/u) |
| 1173 | .map((line) => line.trim()) |
| 1174 | .filter((line) => line.length > 0); |
| 1175 | if (lines.length !== 1 || !path.isAbsolute(lines[0]!)) { |
| 1176 | return yield* new AcpRegistryError({ |
| 1177 | reason: "install_failed", |
| 1178 | detail: `ACP Registry package manager '${managerPath}' returned an invalid global path.`, |
| 1179 | }); |
| 1180 | } |
| 1181 | return lines[0]!; |
| 1182 | }, |
| 1183 | ); |
| 1184 | |
| 1185 | const npmCommandName = ( |
| 1186 | agent: AcpRegistryAgent, |
| 1187 | packageName: string, |
| 1188 | manifest: typeof NpmPackageManifest.Type, |
| 1189 | ): string | undefined => { |
| 1190 | const packageBaseName = packageName.split("/").pop() ?? packageName; |
| 1191 | if (typeof manifest.bin === "string") return packageBaseName; |
| 1192 | const entries = Object.entries(manifest.bin).toSorted(([left], [right]) => |
| 1193 | compareText(left, right), |
| 1194 | ); |
| 1195 | if (entries.length === 1) return entries[0]![0]; |
| 1196 | if (manifest.bin[packageBaseName] !== undefined) return packageBaseName; |
| 1197 | if (manifest.bin[agent.id] !== undefined) return agent.id; |
| 1198 | return new Set(entries.map(([, commandPath]) => commandPath)).size === 1 |
| 1199 | ? entries[0]?.[0] |
| 1200 | : undefined; |
| 1201 | }; |
| 1202 | |
| 1203 | const discoverNpmGlobalPackage = Effect.fn("AcpRegistryCatalog.discoverNpmGlobalPackage")( |
| 1204 | function* ( |
| 1205 | agent: AcpRegistryAgent, |
| 1206 | packageSpec: string, |
| 1207 | managerPath: string, |
| 1208 | environment: NodeJS.ProcessEnv, |
| 1209 | ) { |
| 1210 | const packageIdentity = parseNpxPackageSpec(packageSpec); |
| 1211 | const commandOptions = { |
| 1212 | env: environment, |
| 1213 | timeout: PACKAGE_QUERY_TIMEOUT, |
| 1214 | truncatedOutputReason: "install_failed" as const, |
| 1215 | } as const; |
| 1216 | const globalRoot = yield* runCommand(managerPath, ["root", "--global"], commandOptions).pipe( |
| 1217 | Effect.flatMap((output) => parsePackageManagerPath(managerPath, output)), |
| 1218 | ); |
| 1219 | const globalPrefix = yield* runCommand( |
| 1220 | managerPath, |
| 1221 | ["prefix", "--global"], |
| 1222 | commandOptions, |
| 1223 | ).pipe(Effect.flatMap((output) => parsePackageManagerPath(managerPath, output))); |
| 1224 | const packageRoot = path.join(globalRoot, ...packageIdentity.name.split("/")); |
| 1225 | const manifestPath = path.join(packageRoot, "package.json"); |
| 1226 | const manifestInfo = yield* fileSystem.stat(manifestPath).pipe(Effect.option); |
| 1227 | if (Option.isNone(manifestInfo) || manifestInfo.value.size > MAX_PACKAGE_MANIFEST_BYTES) { |
| 1228 | return Option.none<AcpRegistryPackageInstallReceipt>(); |
| 1229 | } |
| 1230 | const manifest = yield* fileSystem |
| 1231 | .readFileString(manifestPath) |
| 1232 | .pipe(Effect.flatMap(decodeNpmPackageManifest), Effect.option); |
| 1233 | if ( |
| 1234 | Option.isNone(manifest) || |
| 1235 | manifest.value.name !== packageIdentity.name || |
| 1236 | manifest.value.version !== packageIdentity.version |
| 1237 | ) { |
| 1238 | return Option.none<AcpRegistryPackageInstallReceipt>(); |
| 1239 | } |
| 1240 | const commandName = npmCommandName(agent, packageIdentity.name, manifest.value); |
| 1241 | if (commandName === undefined) return Option.none<AcpRegistryPackageInstallReceipt>(); |
| 1242 | const binDirectory = platform === "win32" ? globalPrefix : path.join(globalPrefix, "bin"); |
| 1243 | const executablePath = resolveExecutable( |
| 1244 | path.join(binDirectory, commandName), |
| 1245 | platform, |
| 1246 | environment, |
| 1247 | ); |
| 1248 | return executablePath === undefined |
| 1249 | ? Option.none<AcpRegistryPackageInstallReceipt>() |
| 1250 | : Option.some<AcpRegistryPackageInstallReceipt>({ |
| 1251 | agentId: agent.id, |
| 1252 | agentVersion: agent.version, |
| 1253 | distribution: "npx" as const, |
| 1254 | packageSpec, |
| 1255 | managerPath, |
| 1256 | binDirectory, |
| 1257 | executablePath, |
| 1258 | packageRoot, |
| 1259 | packageVersion: manifest.value.version, |
| 1260 | }); |
| 1261 | }, |
| 1262 | ); |
| 1263 | |
| 1264 | const discoverUvGlobalPackage = Effect.fn("AcpRegistryCatalog.discoverUvGlobalPackage")( |
| 1265 | function* ( |
| 1266 | agent: AcpRegistryAgent, |
| 1267 | packageSpec: string, |
| 1268 | managerPath: string, |
| 1269 | environment: NodeJS.ProcessEnv, |
| 1270 | ) { |
| 1271 | const packageIdentity = parseUvxPackageSpec(packageSpec); |
| 1272 | const installedTools = yield* runCommand(managerPath, ["tool", "list"], { |
| 1273 | env: environment, |
| 1274 | timeout: PACKAGE_QUERY_TIMEOUT, |
| 1275 | truncatedOutputReason: "install_failed", |
| 1276 | }); |
| 1277 | const normalizedPackageName = packageIdentity.name.toLowerCase().replace(/[._-]+/gu, "-"); |
| 1278 | const exactVersionInstalled = installedTools.split(/\r?\n/u).some((line) => { |
| 1279 | const match = /^(\S+) v(\S+)(?:\s|$)/u.exec(line); |
| 1280 | return ( |
| 1281 | match?.[1]?.toLowerCase().replace(/[._-]+/gu, "-") === normalizedPackageName && |
| 1282 | match[2] === packageIdentity.version |
| 1283 | ); |
| 1284 | }); |
| 1285 | if (!exactVersionInstalled) return Option.none<AcpRegistryPackageInstallReceipt>(); |
| 1286 | const binDirectory = yield* runCommand(managerPath, ["tool", "dir", "--bin"], { |
| 1287 | env: environment, |
| 1288 | timeout: PACKAGE_QUERY_TIMEOUT, |
| 1289 | truncatedOutputReason: "install_failed", |
| 1290 | }).pipe(Effect.flatMap((output) => parsePackageManagerPath(managerPath, output))); |
| 1291 | const managedBinEnvironment = { ...environment, PATH: binDirectory }; |
| 1292 | const executablePath = packageCommandCandidates(agent, packageIdentity.name) |
| 1293 | .map((candidate) => resolveExecutable(candidate, platform, managedBinEnvironment)) |
| 1294 | .find((candidate): candidate is string => candidate !== undefined); |
| 1295 | return executablePath === undefined |
| 1296 | ? Option.none<AcpRegistryPackageInstallReceipt>() |
| 1297 | : Option.some<AcpRegistryPackageInstallReceipt>({ |
| 1298 | agentId: agent.id, |
| 1299 | agentVersion: agent.version, |
| 1300 | distribution: "uvx" as const, |
| 1301 | packageSpec, |
| 1302 | managerPath, |
| 1303 | binDirectory, |
| 1304 | executablePath, |
| 1305 | packageVersion: packageIdentity.version, |
| 1306 | }); |
| 1307 | }, |
| 1308 | ); |
| 1309 | |
| 1310 | const ensureGlobalPackage = Effect.fn("AcpRegistryCatalog.ensureGlobalPackage")(function* ( |
| 1311 | agent: AcpRegistryAgent, |
| 1312 | distribution: "npx" | "uvx", |
| 1313 | packageSpec: string, |
| 1314 | environment: NodeJS.ProcessEnv, |
| 1315 | ) { |
| 1316 | const managerName = packageManagerFor(distribution)!; |
| 1317 | const managerPath = resolveExecutable(managerName, platform, environment); |
| 1318 | if (managerPath === undefined) { |
| 1319 | return yield* new AcpRegistryError({ |
| 1320 | reason: "runner_unavailable", |
| 1321 | detail: `ACP Registry agent ${agent.id} requires '${managerName}', but it is not available on this environment's PATH.`, |
| 1322 | }); |
| 1323 | } |
| 1324 | const receipt = yield* readPackageReceipt(agent, distribution, packageSpec, managerPath); |
| 1325 | if (Option.isSome(receipt) && distribution === "npx") return receipt.value; |
| 1326 | |
| 1327 | const packageRoot = packageInstallRoot(agent, distribution); |
| 1328 | yield* fileSystem.makeDirectory(packageRoot, { recursive: true }).pipe( |
| 1329 | Effect.mapError( |
| 1330 | (cause) => |
| 1331 | new AcpRegistryError({ |
| 1332 | reason: "install_failed", |
| 1333 | detail: `Could not create the managed install directory for ${agent.id}.`, |
| 1334 | cause, |
| 1335 | }), |
| 1336 | ), |
| 1337 | ); |
| 1338 | const packageEnvironment = |
| 1339 | distribution === "npx" |
| 1340 | ? { ...withoutNpmPrefix(environment, platform), npm_config_prefix: packageRoot } |
| 1341 | : { |
| 1342 | ...environment, |
| 1343 | UV_TOOL_DIR: packageRoot, |
| 1344 | UV_TOOL_BIN_DIR: packageBinDirectory(agent, distribution), |
| 1345 | }; |
| 1346 | if (Option.isSome(receipt)) { |
| 1347 | const installed = yield* discoverUvGlobalPackage( |
| 1348 | agent, |
| 1349 | packageSpec, |
| 1350 | managerPath, |
| 1351 | packageEnvironment, |
| 1352 | ); |
| 1353 | if (Option.isSome(installed)) return installed.value; |
| 1354 | } |
| 1355 | |
| 1356 | const discover = |
| 1357 | distribution === "npx" |
| 1358 | ? () => discoverNpmGlobalPackage(agent, packageSpec, managerPath, packageEnvironment) |
| 1359 | : () => discoverUvGlobalPackage(agent, packageSpec, managerPath, packageEnvironment); |
| 1360 | const existing = yield* discover(); |
| 1361 | if (Option.isSome(existing)) { |
| 1362 | yield* writePackageReceipt(existing.value); |
| 1363 | return existing.value; |
| 1364 | } |
| 1365 | |
| 1366 | const managerDirectory = yield* managerBinDirectory(managerPath); |
| 1367 | const installEnvironment = withPreferredPath(packageEnvironment, managerDirectory, platform); |
| 1368 | if (distribution === "npx") { |
| 1369 | yield* runCommand(managerPath, ["install", "--global", packageSpec], { |
| 1370 | env: installEnvironment, |
| 1371 | timeout: PACKAGE_INSTALL_TIMEOUT, |
| 1372 | truncatedOutputReason: "install_failed", |
| 1373 | }); |
| 1374 | } else { |
| 1375 | yield* runCommand(managerPath, ["tool", "install", "--force", packageSpec], { |
| 1376 | env: installEnvironment, |
| 1377 | timeout: PACKAGE_INSTALL_TIMEOUT, |
| 1378 | truncatedOutputReason: "install_failed", |
| 1379 | }); |
| 1380 | } |
| 1381 | |
| 1382 | if (distribution === "npx") { |
| 1383 | const installed = yield* discoverNpmGlobalPackage( |
| 1384 | agent, |
| 1385 | packageSpec, |
| 1386 | managerPath, |
| 1387 | packageEnvironment, |
| 1388 | ); |
| 1389 | if (Option.isNone(installed)) { |
| 1390 | return yield* new AcpRegistryError({ |
| 1391 | reason: "install_failed", |
| 1392 | detail: `ACP Registry installed ${packageSpec}, but could not resolve its global command.`, |
| 1393 | }); |
| 1394 | } |
| 1395 | yield* writePackageReceipt(installed.value); |
| 1396 | return installed.value; |
| 1397 | } |
| 1398 | |
| 1399 | const installed = yield* discoverUvGlobalPackage( |
| 1400 | agent, |
| 1401 | packageSpec, |
| 1402 | managerPath, |
| 1403 | packageEnvironment, |
| 1404 | ); |
| 1405 | if (Option.isNone(installed)) { |
| 1406 | return yield* new AcpRegistryError({ |
| 1407 | reason: "install_failed", |
| 1408 | detail: `ACP Registry installed ${packageSpec}, but could not resolve its global command.`, |
| 1409 | }); |
| 1410 | } |
| 1411 | yield* writePackageReceipt(installed.value); |
| 1412 | return installed.value; |
| 1413 | }); |
| 1414 | |
| 1415 | const acquireInstallLock = Effect.fn("AcpRegistryCatalog.acquireInstallLock")(function* ( |
| 1416 | lockPath: string, |
| 1417 | ) { |
| 1418 | for (let attempt = 0; attempt < INSTALL_LOCK_RETRY_COUNT; attempt += 1) { |
| 1419 | const acquired = yield* fileSystem.writeFileString(lockPath, "", { flag: "wx" }).pipe( |
| 1420 | Effect.as(true), |
| 1421 | Effect.catchIf( |
| 1422 | (error) => isAlreadyExists(error), |
| 1423 | () => Effect.succeed(false), |
| 1424 | ), |
| 1425 | ); |
| 1426 | if (acquired) return; |
| 1427 | const now = yield* Clock.currentTimeMillis; |
| 1428 | const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option); |
| 1429 | const mtime = Option.flatMap(lockInfo, (info) => info.mtime); |
| 1430 | if (Option.isSome(mtime) && now - mtime.value.getTime() > INSTALL_LOCK_STALE_MS) { |
| 1431 | yield* fileSystem.remove(lockPath, { force: true }); |
| 1432 | continue; |
| 1433 | } |
| 1434 | yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY); |
| 1435 | } |
| 1436 | return yield* new AcpRegistryError({ |
| 1437 | reason: "install_failed", |
| 1438 | detail: `Timed out waiting for ACP Registry install lock ${lockPath}.`, |
| 1439 | }); |
| 1440 | }); |
| 1441 | |
| 1442 | const assertExecutableInRoot = Effect.fn("AcpRegistryCatalog.assertExecutableInRoot")(function* ( |
| 1443 | root: string, |
| 1444 | executablePath: string, |
| 1445 | options?: { readonly makeExecutable?: boolean }, |
| 1446 | ) { |
| 1447 | const rootRealPath = yield* fileSystem.realPath(root); |
| 1448 | const executableRealPath = yield* fileSystem.realPath(executablePath); |
| 1449 | const relative = path.relative(rootRealPath, executableRealPath); |
| 1450 | if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) { |
| 1451 | return yield* new AcpRegistryError({ |
| 1452 | reason: "archive_invalid", |
| 1453 | detail: "ACP Registry archive command resolves outside its installation directory.", |
| 1454 | }); |
| 1455 | } |
| 1456 | // chmod follows symlinks, so only change the mode once the real path is known to be inside. |
| 1457 | if (options?.makeExecutable && platform !== "win32") { |
| 1458 | yield* fileSystem.chmod(executableRealPath, 0o755); |
| 1459 | } |
| 1460 | const info = yield* fileSystem.stat(executableRealPath); |
| 1461 | const hasExecutableMode = platform === "win32" || (info.mode & 0o111) !== 0; |
| 1462 | if (info.type !== "File" || !hasExecutableMode) { |
| 1463 | return yield* new AcpRegistryError({ |
| 1464 | reason: "archive_invalid", |
| 1465 | detail: "ACP Registry archive command is not a regular executable file.", |
| 1466 | }); |
| 1467 | } |
| 1468 | return executableRealPath; |
| 1469 | }); |
| 1470 | |
| 1471 | const binaryPaths = (agent: AcpRegistryAgent, target: typeof AcpRegistryBinaryTarget.Type) => { |
| 1472 | const commandSegments = normalizeRegistryCommandPath(target.cmd); |
| 1473 | const matchedPlatformTarget = |
| 1474 | resolveAcpRegistryPlatformTargetCandidates(platformTarget).find( |
| 1475 | (candidate) => agent.distribution.binary?.[candidate] === target, |
| 1476 | ) ?? platformTarget; |
| 1477 | if (matchedPlatformTarget === undefined || commandSegments === undefined) return undefined; |
| 1478 | const installRoot = path.join(agentInstallRoot(agent), matchedPlatformTarget); |
| 1479 | return { |
| 1480 | commandSegments, |
| 1481 | installRoot, |
| 1482 | platformTarget: matchedPlatformTarget, |
| 1483 | executablePath: path.join(installRoot, ...commandSegments), |
| 1484 | }; |
| 1485 | }; |
| 1486 | |
| 1487 | const hasInstalledBinaryVersion = Effect.fn("AcpRegistryCatalog.hasInstalledBinaryVersion")( |
| 1488 | function* (agentId: string) { |
| 1489 | const agentRoot = path.join(installsDirectory, agentId); |
| 1490 | const versions = yield* fileSystem |
| 1491 | .readDirectory(agentRoot) |
| 1492 | .pipe(Effect.orElseSucceed((): Array<string> => [])); |
| 1493 | for (const version of versions) { |
| 1494 | for (const candidateTarget of resolveAcpRegistryPlatformTargetCandidates(platformTarget)) { |
| 1495 | if ( |
| 1496 | yield* fileSystem |
| 1497 | .exists(path.join(agentRoot, version, candidateTarget)) |
| 1498 | .pipe(Effect.orElseSucceed(() => false)) |
| 1499 | ) { |
| 1500 | return true; |
| 1501 | } |
| 1502 | } |
| 1503 | } |
| 1504 | return false; |
| 1505 | }, |
| 1506 | ); |
| 1507 | |
| 1508 | const installBinary = Effect.fn("AcpRegistryCatalog.installBinary")(function* ( |
| 1509 | agent: AcpRegistryAgent, |
| 1510 | target: typeof AcpRegistryBinaryTarget.Type, |
| 1511 | ) { |
| 1512 | if (platformTarget === undefined) { |
| 1513 | return yield* new AcpRegistryError({ |
| 1514 | reason: "unsupported_platform", |
| 1515 | detail: `ACP Registry does not support platform ${platform}-${architecture}.`, |
| 1516 | }); |
| 1517 | } |
| 1518 | const paths = binaryPaths(agent, target); |
| 1519 | if (paths === undefined) { |
| 1520 | return yield* new AcpRegistryError({ |
| 1521 | reason: "archive_invalid", |
| 1522 | detail: `ACP Registry agent ${agent.id} declares an unsafe command path '${target.cmd}'.`, |
| 1523 | }); |
| 1524 | } |
| 1525 | const { commandSegments, installRoot, executablePath } = paths; |
| 1526 | if (yield* fileSystem.exists(executablePath).pipe(Effect.orElseSucceed(() => false))) { |
| 1527 | return yield* assertExecutableInRoot(installRoot, executablePath).pipe( |
| 1528 | Effect.mapError((cause) => |
| 1529 | isAcpRegistryError(cause) |
| 1530 | ? cause |
| 1531 | : new AcpRegistryError({ |
| 1532 | reason: "install_failed", |
| 1533 | detail: `Could not validate cached ACP Registry agent ${agent.id}.`, |
| 1534 | cause, |
| 1535 | }), |
| 1536 | ), |
| 1537 | ); |
| 1538 | } |
| 1539 | |
| 1540 | yield* fileSystem.makeDirectory(path.dirname(installRoot), { recursive: true }).pipe( |
| 1541 | Effect.mapError( |
| 1542 | (cause) => |
| 1543 | new AcpRegistryError({ |
| 1544 | reason: "install_failed", |
| 1545 | detail: `Could not create ACP Registry cache for ${agent.id}.`, |
| 1546 | cause, |
| 1547 | }), |
| 1548 | ), |
| 1549 | ); |
| 1550 | const lockPath = `${installRoot}.lock`; |
| 1551 | yield* acquireInstallLock(lockPath).pipe( |
| 1552 | Effect.mapError((cause) => |
| 1553 | isAcpRegistryError(cause) |
| 1554 | ? cause |
| 1555 | : new AcpRegistryError({ |
| 1556 | reason: "install_failed", |
| 1557 | detail: `Could not acquire install lock for ACP Registry agent ${agent.id}.`, |
| 1558 | cause, |
| 1559 | }), |
| 1560 | ), |
| 1561 | ); |
| 1562 | |
| 1563 | return yield* Effect.gen(function* () { |
| 1564 | if (yield* fileSystem.exists(executablePath).pipe(Effect.orElseSucceed(() => false))) { |
| 1565 | return yield* assertExecutableInRoot(installRoot, executablePath); |
| 1566 | } |
| 1567 | const temporaryRoot = yield* fileSystem.makeTempDirectoryScoped({ |
| 1568 | directory: path.dirname(installRoot), |
| 1569 | prefix: `.${agent.id}-install-`, |
| 1570 | }); |
| 1571 | const extractionRoot = path.join(temporaryRoot, "extracted"); |
| 1572 | yield* fileSystem.makeDirectory(extractionRoot, { recursive: true }); |
| 1573 | const kind = archiveKind(target.archive); |
| 1574 | const archivePath = path.join(temporaryRoot, archiveFileName(kind)); |
| 1575 | const response = yield* httpClient.execute(HttpClientRequest.get(target.archive)).pipe( |
| 1576 | Effect.flatMap(HttpClientResponse.filterStatusOk), |
| 1577 | Effect.mapError( |
| 1578 | (cause) => |
| 1579 | new AcpRegistryError({ |
| 1580 | reason: "download_failed", |
| 1581 | detail: `Could not download ACP Registry agent ${agent.id} ${agent.version}.`, |
| 1582 | cause, |
| 1583 | }), |
| 1584 | ), |
| 1585 | Effect.timeoutOrElse({ |
| 1586 | duration: ARCHIVE_REQUEST_TIMEOUT, |
| 1587 | orElse: () => |
| 1588 | Effect.fail( |
| 1589 | new AcpRegistryError({ |
| 1590 | reason: "download_failed", |
| 1591 | detail: `Timed out downloading ACP Registry agent ${agent.id} ${agent.version}.`, |
| 1592 | }), |
| 1593 | ), |
| 1594 | }), |
| 1595 | ); |
| 1596 | // Stream hashes to avoid buffering large archives; Effect Crypto requires a whole buffer. |
| 1597 | const hash = sha256.create(); |
| 1598 | let downloadedBytes = 0; |
| 1599 | yield* response.stream.pipe( |
| 1600 | Stream.tap((chunk) => { |
| 1601 | if (downloadedBytes + chunk.byteLength > MAX_ARCHIVE_BYTES) { |
| 1602 | return Effect.fail( |
| 1603 | new AcpRegistryError({ |
| 1604 | reason: "archive_invalid", |
| 1605 | detail: `ACP Registry agent ${agent.id} archive exceeds ${MAX_ARCHIVE_BYTES} bytes.`, |
| 1606 | }), |
| 1607 | ); |
| 1608 | } |
| 1609 | downloadedBytes += chunk.byteLength; |
| 1610 | hash.update(chunk); |
| 1611 | return Effect.void; |
| 1612 | }), |
| 1613 | Stream.run(fileSystem.sink(archivePath)), |
| 1614 | Effect.mapError((cause) => |
| 1615 | isAcpRegistryError(cause) |
| 1616 | ? cause |
| 1617 | : new AcpRegistryError({ |
| 1618 | reason: "download_failed", |
| 1619 | detail: `Could not save ACP Registry agent ${agent.id} ${agent.version}.`, |
| 1620 | cause, |
| 1621 | }), |
| 1622 | ), |
| 1623 | Effect.timeoutOrElse({ |
| 1624 | duration: ARCHIVE_REQUEST_TIMEOUT, |
| 1625 | orElse: () => |
| 1626 | Effect.fail( |
| 1627 | new AcpRegistryError({ |
| 1628 | reason: "download_failed", |
| 1629 | detail: `Timed out reading ACP Registry agent ${agent.id} download.`, |
| 1630 | }), |
| 1631 | ), |
| 1632 | }), |
| 1633 | ); |
| 1634 | if (target.sha256 !== undefined) { |
| 1635 | const actual = Hex.encode(hash.digest()); |
| 1636 | if (actual !== target.sha256.toLowerCase()) { |
| 1637 | return yield* new AcpRegistryError({ |
| 1638 | reason: "checksum_mismatch", |
| 1639 | detail: `ACP Registry agent ${agent.id} download did not match its declared SHA-256.`, |
| 1640 | }); |
| 1641 | } |
| 1642 | } |
| 1643 | |
| 1644 | if (kind === "raw") { |
| 1645 | const targetPath = path.join(extractionRoot, ...commandSegments); |
| 1646 | yield* fileSystem.makeDirectory(path.dirname(targetPath), { recursive: true }); |
| 1647 | yield* fileSystem.rename(archivePath, targetPath); |
| 1648 | } else { |
| 1649 | const tarCommand = |
| 1650 | platformTarget === "windows-aarch64" && |
| 1651 | paths.platformTarget === "windows-x86_64" && |
| 1652 | kind === "zip" |
| 1653 | ? cliArchiveTarCommand(platform, hostEnvironment) |
| 1654 | : "tar"; |
| 1655 | const listArgs = |
| 1656 | kind === "tar_gz" |
| 1657 | ? ["-tzf", archivePath] |
| 1658 | : kind === "tar_bz2" |
| 1659 | ? ["-tjf", archivePath] |
| 1660 | : platform === "win32" |
| 1661 | ? ["-tf", archivePath] |
| 1662 | : undefined; |
| 1663 | const listingOptions = { maxStdoutBytes: MAX_ARCHIVE_LISTING_BYTES }; |
| 1664 | const entries = |
| 1665 | listArgs === undefined |
| 1666 | ? yield* runCommand("unzip", ["-Z1", archivePath], listingOptions) |
| 1667 | : yield* runCommand(tarCommand, listArgs, listingOptions); |
| 1668 | if (!validateArchiveEntries(entries)) { |
| 1669 | return yield* new AcpRegistryError({ |
| 1670 | reason: "archive_invalid", |
| 1671 | detail: `ACP Registry agent ${agent.id} archive contains an unsafe path.`, |
| 1672 | }); |
| 1673 | } |
| 1674 | if (kind === "zip" && platform !== "win32") { |
| 1675 | yield* runCommand("unzip", ["-q", archivePath, "-d", extractionRoot]); |
| 1676 | } else { |
| 1677 | const extractFlag = kind === "tar_gz" ? "-xzf" : kind === "tar_bz2" ? "-xjf" : "-xf"; |
| 1678 | yield* runCommand(tarCommand, [extractFlag, archivePath, "-C", extractionRoot]); |
| 1679 | } |
| 1680 | } |
| 1681 | |
| 1682 | const stagedExecutable = path.join(extractionRoot, ...commandSegments); |
| 1683 | if (!(yield* fileSystem.exists(stagedExecutable).pipe(Effect.orElseSucceed(() => false)))) { |
| 1684 | return yield* new AcpRegistryError({ |
| 1685 | reason: "archive_invalid", |
| 1686 | detail: `ACP Registry archive for ${agent.id} did not contain '${target.cmd}'.`, |
| 1687 | }); |
| 1688 | } |
| 1689 | yield* assertExecutableInRoot(extractionRoot, stagedExecutable, { makeExecutable: true }); |
| 1690 | yield* fileSystem.remove(installRoot, { recursive: true, force: true }); |
| 1691 | yield* fileSystem.rename(extractionRoot, installRoot); |
| 1692 | return yield* assertExecutableInRoot(installRoot, executablePath); |
| 1693 | }).pipe( |
| 1694 | Effect.scoped, |
| 1695 | Effect.ensuring(fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore)), |
| 1696 | Effect.mapError((cause) => |
| 1697 | isAcpRegistryError(cause) |
| 1698 | ? cause |
| 1699 | : new AcpRegistryError({ |
| 1700 | reason: "install_failed", |
| 1701 | detail: `Could not install ACP Registry agent ${agent.id}.`, |
| 1702 | cause, |
| 1703 | }), |
| 1704 | ), |
| 1705 | ); |
| 1706 | }); |
| 1707 | |
| 1708 | const findAgent = Effect.fn("AcpRegistryCatalog.findAgent")(function* ( |
| 1709 | registry: AcpRegistryIndex, |
| 1710 | agentId: string, |
| 1711 | ) { |
| 1712 | const agent = registry.agents.find((candidate) => candidate.id === agentId.trim()); |
| 1713 | if (agent === undefined) { |
| 1714 | return yield* new AcpRegistryError({ |
| 1715 | reason: "agent_not_found", |
| 1716 | detail: `ACP Registry does not contain agent '${agentId.trim()}'.`, |
| 1717 | }); |
| 1718 | } |
| 1719 | return agent; |
| 1720 | }); |
| 1721 | |
| 1722 | const compatibleDistribution = Effect.fn("AcpRegistryCatalog.compatibleDistribution")(function* ( |
| 1723 | agent: AcpRegistryAgent, |
| 1724 | preference: AcpRegistryDistributionPreference, |
| 1725 | ) { |
| 1726 | const distribution = resolveAcpRegistryDistribution({ |
| 1727 | agent, |
| 1728 | preference, |
| 1729 | platformTarget, |
| 1730 | }); |
| 1731 | if (distribution === undefined) { |
| 1732 | return yield* new AcpRegistryError({ |
| 1733 | reason: platformTarget === undefined ? "unsupported_platform" : "unsupported_distribution", |
| 1734 | detail: `ACP Registry agent ${agent.id} has no ${preference === "auto" ? "compatible" : preference} distribution for ${platform}-${architecture}.`, |
| 1735 | }); |
| 1736 | } |
| 1737 | return distribution; |
| 1738 | }); |
| 1739 | |
| 1740 | const search: AcpRegistryCatalog["Service"]["search"] = Effect.fn("AcpRegistryCatalog.search")( |
| 1741 | function* (input) { |
| 1742 | const registry = yield* recentRegistry(); |
| 1743 | const ranked = registry.agents.flatMap((agent) => { |
| 1744 | const distribution = resolveAcpRegistryDistribution({ |
| 1745 | agent, |
| 1746 | preference: "auto", |
| 1747 | platformTarget, |
| 1748 | }); |
| 1749 | const rank = searchRank(agent, input.query); |
| 1750 | const packageManager = |
| 1751 | distribution === undefined ? undefined : packageManagerFor(distribution.kind); |
| 1752 | const packageManagerAvailable = |
| 1753 | packageManager === undefined || |
| 1754 | resolveExecutable(packageManager, platform, hostEnvironment) !== undefined; |
| 1755 | return distribution === undefined || rank === undefined || !packageManagerAvailable |
| 1756 | ? [] |
| 1757 | : [{ agent, distribution, rank }]; |
| 1758 | }); |
| 1759 | ranked.sort( |
| 1760 | (left, right) => |
| 1761 | left.rank - right.rank || |
| 1762 | compareText(left.agent.name.toLowerCase(), right.agent.name.toLowerCase()) || |
| 1763 | compareText(left.agent.id, right.agent.id), |
| 1764 | ); |
| 1765 | const limit = input.limit ?? DEFAULT_SEARCH_LIMIT; |
| 1766 | return { |
| 1767 | agents: ranked.slice(0, limit).map(({ agent, distribution }) => ({ |
| 1768 | id: agent.id, |
| 1769 | name: agent.name, |
| 1770 | version: agent.version, |
| 1771 | description: agent.description, |
| 1772 | authors: agent.authors ?? [], |
| 1773 | license: agent.license ?? null, |
| 1774 | website: agent.website ?? null, |
| 1775 | repository: agent.repository ?? null, |
| 1776 | icon: agent.icon ?? null, |
| 1777 | distribution: distribution.kind, |
| 1778 | integrity: |
| 1779 | distribution.kind === "binary" && distribution.binaryTarget?.sha256 !== undefined |
| 1780 | ? "sha256" |
| 1781 | : "registry", |
| 1782 | })), |
| 1783 | } satisfies AcpRegistrySearchResult; |
| 1784 | }, |
| 1785 | ); |
| 1786 | |
| 1787 | const prepare: AcpRegistryCatalog["Service"]["prepare"] = Effect.fn("AcpRegistryCatalog.prepare")( |
| 1788 | function* (input) { |
| 1789 | const registry = yield* refreshRegistry(); |
| 1790 | const agent = yield* findAgent(registry, input.agentId); |
| 1791 | const distribution = yield* compatibleDistribution(agent, "auto"); |
| 1792 | if (distribution.kind === "binary") { |
| 1793 | // Only explicit command overrides may use PATH copies with different ACP capabilities. |
| 1794 | yield* withInstallPermit(agent.id)( |
| 1795 | installBinary(agent, distribution.binaryTarget!).pipe( |
| 1796 | Effect.tap(() => reservePreparedBinary(agent.id)), |
| 1797 | ), |
| 1798 | ); |
| 1799 | } else { |
| 1800 | yield* withInstallPermit(agent.id)( |
| 1801 | ensureGlobalPackage(agent, distribution.kind, distribution.packageName!, hostEnvironment), |
| 1802 | ); |
| 1803 | } |
| 1804 | return { |
| 1805 | agentId: agent.id, |
| 1806 | version: agent.version, |
| 1807 | distribution: distribution.kind, |
| 1808 | prepared: true, |
| 1809 | } satisfies AcpRegistryPrepareResult; |
| 1810 | }, |
| 1811 | ); |
| 1812 | |
| 1813 | const validateLocalExecutable = (command: string) => |
| 1814 | platform === "win32" && /\.(?:cmd|bat)$/iu.test(command) |
| 1815 | ? Effect.fail( |
| 1816 | new AcpRegistryError({ |
| 1817 | reason: "runner_unavailable", |
| 1818 | detail: |
| 1819 | "Local ACP commands launch without a shell. For a Windows batch wrapper, configure the underlying executable (for example node.exe) and pass the script path as an argument.", |
| 1820 | }), |
| 1821 | ) |
| 1822 | : Effect.void; |
| 1823 | |
| 1824 | const inspect: AcpRegistryCatalog["Service"]["inspect"] = Effect.fn("AcpRegistryCatalog.inspect")( |
| 1825 | function* (settings, environment) { |
| 1826 | if (settings.source === "local") { |
| 1827 | const command = settings.commandPath.trim(); |
| 1828 | if (!command) return { status: "unconfigured" } as const; |
| 1829 | const executable = resolveExecutable(command, platform, environment ?? hostEnvironment); |
| 1830 | if (executable !== undefined) yield* validateLocalExecutable(executable); |
| 1831 | return executable === undefined |
| 1832 | ? ({ |
| 1833 | status: "missing_runner", |
| 1834 | version: null, |
| 1835 | distribution: "local", |
| 1836 | } as const) |
| 1837 | : ({ status: "ready", agentId: command, version: null, distribution: "local" } as const); |
| 1838 | } |
| 1839 | const agentId = settings.agentId.trim(); |
| 1840 | if (agentId.length === 0) return { status: "unconfigured" } as const; |
| 1841 | const registry = yield* loadRegistry(); |
| 1842 | const agent = registry.agents.find((candidate) => candidate.id === agentId); |
| 1843 | if (agent === undefined) return { status: "not_found", agentId } as const; |
| 1844 | const documentationUrl = agent.website ?? agent.repository; |
| 1845 | const distribution = resolveAcpRegistryDistribution({ |
| 1846 | agent, |
| 1847 | preference: settings.distribution, |
| 1848 | platformTarget, |
| 1849 | }); |
| 1850 | if (distribution === undefined) { |
| 1851 | return { status: "unsupported", agentId, version: agent.version } as const; |
| 1852 | } |
| 1853 | |
| 1854 | const commandOverride = settings.commandPath.trim(); |
| 1855 | if (commandOverride.length > 0) { |
| 1856 | const available = |
| 1857 | resolveExecutable(commandOverride, platform, environment ?? hostEnvironment) !== |
| 1858 | undefined; |
| 1859 | return available |
| 1860 | ? ({ |
| 1861 | status: "ready", |
| 1862 | agentId, |
| 1863 | version: null, |
| 1864 | distribution: distribution.kind, |
| 1865 | ...(documentationUrl ? { documentationUrl } : {}), |
| 1866 | } as const) |
| 1867 | : ({ |
| 1868 | status: "missing_runner", |
| 1869 | agentId, |
| 1870 | version: agent.version, |
| 1871 | distribution: distribution.kind, |
| 1872 | runner: commandOverride, |
| 1873 | } as const); |
| 1874 | } |
| 1875 | |
| 1876 | if (distribution.kind === "binary") { |
| 1877 | return yield* withInstallPermit(agent.id)( |
| 1878 | Effect.gen(function* () { |
| 1879 | const paths = binaryPaths(agent, distribution.binaryTarget!); |
| 1880 | if (paths === undefined) { |
| 1881 | return { status: "unsupported", agentId, version: agent.version } as const; |
| 1882 | } |
| 1883 | yield* consumePreparedBinaryReservation(agent.id); |
| 1884 | const exists = yield* fileSystem |
| 1885 | .exists(paths.executablePath) |
| 1886 | .pipe(Effect.orElseSucceed(() => false)); |
| 1887 | // Any prepared version keeps the agent ready; resolve installs the current one on demand. |
| 1888 | if (!exists && !(yield* hasInstalledBinaryVersion(agent.id))) { |
| 1889 | return { |
| 1890 | status: "unprepared", |
| 1891 | agentId, |
| 1892 | version: agent.version, |
| 1893 | distribution: "binary", |
| 1894 | } as const; |
| 1895 | } |
| 1896 | if (exists) { |
| 1897 | yield* assertExecutableInRoot(paths.installRoot, paths.executablePath).pipe( |
| 1898 | Effect.mapError((cause) => |
| 1899 | isAcpRegistryError(cause) |
| 1900 | ? cause |
| 1901 | : new AcpRegistryError({ |
| 1902 | reason: "install_failed", |
| 1903 | detail: `Could not validate cached ACP Registry agent ${agent.id}.`, |
| 1904 | cause, |
| 1905 | }), |
| 1906 | ), |
| 1907 | ); |
| 1908 | } |
| 1909 | return { |
| 1910 | status: "ready", |
| 1911 | agentId, |
| 1912 | version: agent.version, |
| 1913 | distribution: "binary", |
| 1914 | ...(documentationUrl ? { documentationUrl } : {}), |
| 1915 | } as const; |
| 1916 | }), |
| 1917 | ); |
| 1918 | } |
| 1919 | |
| 1920 | const runner = packageManagerFor(distribution.kind)!; |
| 1921 | const available = |
| 1922 | resolveExecutable(runner, platform, environment ?? hostEnvironment) !== undefined; |
| 1923 | return available |
| 1924 | ? ({ |
| 1925 | status: "ready", |
| 1926 | agentId, |
| 1927 | version: agent.version, |
| 1928 | distribution: distribution.kind, |
| 1929 | ...(documentationUrl ? { documentationUrl } : {}), |
| 1930 | } as const) |
| 1931 | : ({ |
| 1932 | status: "missing_runner", |
| 1933 | agentId, |
| 1934 | version: agent.version, |
| 1935 | distribution: distribution.kind, |
| 1936 | runner, |
| 1937 | } as const); |
| 1938 | }, |
| 1939 | ); |
| 1940 | |
| 1941 | const resolve: AcpRegistryCatalog["Service"]["resolve"] = Effect.fn("AcpRegistryCatalog.resolve")( |
| 1942 | function* (settings, cwd, environment) { |
| 1943 | if (settings.source === "local") { |
| 1944 | const executable = settings.commandPath.trim(); |
| 1945 | if (!executable) { |
| 1946 | return yield* new AcpRegistryError({ |
| 1947 | reason: "agent_not_configured", |
| 1948 | detail: "Local ACP provider requires an executable.", |
| 1949 | }); |
| 1950 | } |
| 1951 | const env = environment ?? hostEnvironment; |
| 1952 | const command = resolveExecutable(executable, platform, env); |
| 1953 | if (command === undefined) { |
| 1954 | return yield* new AcpRegistryError({ |
| 1955 | reason: "runner_unavailable", |
| 1956 | detail: "Local ACP executable is not available on this environment's PATH.", |
| 1957 | }); |
| 1958 | } |
| 1959 | yield* validateLocalExecutable(command); |
| 1960 | return { |
| 1961 | distribution: "local", |
| 1962 | spawn: { command, args: settings.commandArgs, cwd, env, shell: false }, |
| 1963 | } satisfies ResolvedAcpRegistryAgent; |
| 1964 | } |
| 1965 | const agentId = settings.agentId.trim(); |
| 1966 | if (agentId.length === 0) { |
| 1967 | return yield* new AcpRegistryError({ |
| 1968 | reason: "agent_not_configured", |
| 1969 | detail: "ACP Registry provider requires a registry agent ID.", |
| 1970 | }); |
| 1971 | } |
| 1972 | const registry = yield* loadRegistry(); |
| 1973 | const agent = yield* findAgent(registry, agentId); |
| 1974 | const distribution = yield* compatibleDistribution(agent, settings.distribution); |
| 1975 | |
| 1976 | let command: string; |
| 1977 | let args: ReadonlyArray<string>; |
| 1978 | let commandBinDirectory: string | undefined; |
| 1979 | const effectiveEnvironment = environment ?? hostEnvironment; |
| 1980 | const commandOverride = settings.commandPath.trim(); |
| 1981 | if (commandOverride.length > 0) { |
| 1982 | const resolvedOverride = resolveExecutable(commandOverride, platform, effectiveEnvironment); |
| 1983 | if (resolvedOverride === undefined) { |
| 1984 | return yield* new AcpRegistryError({ |
| 1985 | reason: "runner_unavailable", |
| 1986 | detail: `ACP Registry agent ${agent.id} requires '${commandOverride}', but it is not available on this provider instance's PATH.`, |
| 1987 | }); |
| 1988 | } |
| 1989 | command = resolvedOverride; |
| 1990 | args = distribution.args; |
| 1991 | } else if (distribution.kind === "npx" || distribution.kind === "uvx") { |
| 1992 | const installed = yield* withInstallPermit(agent.id)( |
| 1993 | ensureGlobalPackage( |
| 1994 | agent, |
| 1995 | distribution.kind, |
| 1996 | distribution.packageName!, |
| 1997 | effectiveEnvironment, |
| 1998 | ), |
| 1999 | ); |
| 2000 | command = installed.executablePath; |
| 2001 | args = distribution.args; |
| 2002 | commandBinDirectory = installed.binDirectory; |
| 2003 | } else { |
| 2004 | const target = distribution.binaryTarget!; |
| 2005 | command = yield* withInstallPermit(agent.id)( |
| 2006 | installBinary(agent, target).pipe( |
| 2007 | Effect.tap(() => consumePreparedBinaryReservation(agent.id)), |
| 2008 | ), |
| 2009 | ); |
| 2010 | args = distribution.args; |
| 2011 | } |
| 2012 | |
| 2013 | const baseSpawnEnvironment = { |
| 2014 | ...effectiveEnvironment, |
| 2015 | ...distribution.env, |
| 2016 | }; |
| 2017 | const pathEnvironment = |
| 2018 | commandBinDirectory === undefined |
| 2019 | ? baseSpawnEnvironment |
| 2020 | : withPreferredPath(baseSpawnEnvironment, commandBinDirectory, platform); |
| 2021 | const spawnEnvironment = |
| 2022 | runtimeTempDir !== undefined && UNPACKING_AGENT_IDS.has(agent.id) |
| 2023 | ? yield* acquireRuntimeTempEnvironment(runtimeTempDir, pathEnvironment) |
| 2024 | : pathEnvironment; |
| 2025 | |
| 2026 | return { |
| 2027 | agent, |
| 2028 | distribution: distribution.kind, |
| 2029 | spawn: { |
| 2030 | command, |
| 2031 | args, |
| 2032 | cwd, |
| 2033 | env: spawnEnvironment, |
| 2034 | }, |
| 2035 | } satisfies ResolvedAcpRegistryAgent; |
| 2036 | }, |
| 2037 | ); |
| 2038 | |
| 2039 | const uninstallManagedBinary: AcpRegistryCatalog["Service"]["uninstallManagedBinary"] = (input) => |
| 2040 | hostSettings |
| 2041 | .withSnapshot((settings) => |
| 2042 | withInstallPermit(input.agentId)( |
| 2043 | Effect.gen(function* () { |
| 2044 | const safeAgentId = yield* decodeBoundedAgentId(input.agentId).pipe( |
| 2045 | Effect.mapError( |
| 2046 | (cause) => |
| 2047 | new AcpRegistryError({ |
| 2048 | reason: "install_failed", |
| 2049 | detail: "ACP Registry managed binary uninstall received an invalid agent ID.", |
| 2050 | cause, |
| 2051 | }), |
| 2052 | ), |
| 2053 | ); |
| 2054 | const isReferenced = Object.values(settings.providerInstances).some((instance) => { |
| 2055 | if ( |
| 2056 | instance.driver !== "acpRegistry" || |
| 2057 | instance.config === null || |
| 2058 | typeof instance.config !== "object" |
| 2059 | ) |
| 2060 | return false; |
| 2061 | const config = instance.config as Record<string, unknown>; |
| 2062 | return ( |
| 2063 | config.source !== "local" && |
| 2064 | typeof config.agentId === "string" && |
| 2065 | config.agentId.trim() === safeAgentId |
| 2066 | ); |
| 2067 | }); |
| 2068 | if (isReferenced) { |
| 2069 | yield* consumePreparedBinaryReservation(safeAgentId); |
| 2070 | return { agentId: safeAgentId, removed: false }; |
| 2071 | } |
| 2072 | if (yield* hasPreparedBinaryReservation(safeAgentId)) { |
| 2073 | return { agentId: safeAgentId, removed: false }; |
| 2074 | } |
| 2075 | const agentRoot = path.join(installsDirectory, safeAgentId); |
| 2076 | const existed = yield* fileSystem.exists(agentRoot).pipe( |
| 2077 | Effect.mapError( |
| 2078 | (cause) => |
| 2079 | new AcpRegistryError({ |
| 2080 | reason: "install_failed", |
| 2081 | detail: `Could not inspect the managed binary cache for ACP Registry agent ${safeAgentId}.`, |
| 2082 | cause, |
| 2083 | }), |
| 2084 | ), |
| 2085 | ); |
| 2086 | if (!existed) return { agentId: safeAgentId, removed: false }; |
| 2087 | |
| 2088 | let removed = false; |
| 2089 | yield* Effect.gen(function* () { |
| 2090 | for (const version of yield* fileSystem.readDirectory(agentRoot)) { |
| 2091 | const versionRoot = path.join(agentRoot, version); |
| 2092 | for (const entry of yield* fileSystem.readDirectory(versionRoot)) { |
| 2093 | if (!/^(?:darwin|linux|windows)-(?:aarch64|x86_64)$/u.test(entry)) continue; |
| 2094 | yield* fileSystem.remove(path.join(versionRoot, entry), { |
| 2095 | recursive: true, |
| 2096 | force: true, |
| 2097 | }); |
| 2098 | removed = true; |
| 2099 | } |
| 2100 | if ((yield* fileSystem.readDirectory(versionRoot)).length === 0) |
| 2101 | yield* fileSystem.remove(versionRoot, { recursive: true }); |
| 2102 | } |
| 2103 | if ((yield* fileSystem.readDirectory(agentRoot)).length === 0) |
| 2104 | yield* fileSystem.remove(agentRoot, { recursive: true }); |
| 2105 | }).pipe( |
| 2106 | Effect.mapError( |
| 2107 | (cause) => |
| 2108 | new AcpRegistryError({ |
| 2109 | reason: "install_failed", |
| 2110 | detail: `Could not remove managed binaries for ACP Registry agent ${safeAgentId}.`, |
| 2111 | cause, |
| 2112 | }), |
| 2113 | ), |
| 2114 | ); |
| 2115 | return { agentId: safeAgentId, removed }; |
| 2116 | }), |
| 2117 | ), |
| 2118 | ) |
| 2119 | .pipe( |
| 2120 | Effect.catchTags({ |
| 2121 | ServerSettingsError: (cause) => |
| 2122 | new AcpRegistryError({ |
| 2123 | reason: "install_failed", |
| 2124 | detail: |
| 2125 | "Could not read provider settings while checking managed ACP binary references.", |
| 2126 | cause, |
| 2127 | }), |
| 2128 | }), |
| 2129 | ); |
| 2130 | |
| 2131 | return AcpRegistryCatalog.of({ |
| 2132 | search, |
| 2133 | prepare, |
| 2134 | inspect, |
| 2135 | resolve, |
| 2136 | uninstallManagedBinary, |
| 2137 | }); |
| 2138 | }); |