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

AcpRegistrySupport.ts

633 lines21.8 KB

1import {
2 type AcpRegistryDistributionPreference,
3 type AcpRegistrySettings,
4} from "@t3tools/contracts";
5import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
6import * as Clock from "effect/Clock";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as PlatformError from "effect/PlatformError";
12import * as Ref from "effect/Ref";
13import * as Schema from "effect/Schema";
14import * as Semaphore from "effect/Semaphore";
15import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
16import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
17​
18import { collectUint8StreamText } from "../../stream/collectUint8StreamText.ts";
19import type { AcpSpawnInput } from "./AcpSessionRuntime.ts";
20​
21export const ACP_REGISTRY_URL =
22 "https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json";
23​
24const AcpRegistryPackageDistribution = Schema.Struct({
25 package: Schema.String,
26 args: Schema.optionalKey(Schema.Array(Schema.String)),
27 env: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),
28});
29​
30const AcpRegistryBinaryTarget = Schema.Struct({
31 archive: Schema.String,
32 cmd: Schema.String,
33 args: Schema.optionalKey(Schema.Array(Schema.String)),
34 env: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),
35});
36​
37const AcpRegistryAgent = Schema.Struct({
38 id: Schema.String,
39 name: Schema.String,
40 version: Schema.String,
41 description: Schema.String,
42 distribution: Schema.Struct({
43 binary: Schema.optionalKey(Schema.Record(Schema.String, AcpRegistryBinaryTarget)),
44 npx: Schema.optionalKey(AcpRegistryPackageDistribution),
45 uvx: Schema.optionalKey(AcpRegistryPackageDistribution),
46 }),
47});
48export type AcpRegistryAgent = typeof AcpRegistryAgent.Type;
49​
50const AcpRegistryIndex = Schema.Struct({
51 version: Schema.String,
52 agents: Schema.Array(AcpRegistryAgent),
53});
54export type AcpRegistryIndex = typeof AcpRegistryIndex.Type;
55​
56const decodeRegistryIndex = Schema.decodeUnknownEffect(AcpRegistryIndex);
57const decodeJson = Schema.decodeUnknownEffect(Schema.UnknownFromJsonString);
58​
59export const AcpRegistryErrorReason = Schema.Literals([
60 "agent_not_configured",
61 "agent_not_found",
62 "archive_invalid",
63 "download_failed",
64 "install_failed",
65 "registry_unavailable",
66 "unsupported_distribution",
67 "unsupported_platform",
68]);
69export type AcpRegistryErrorReason = typeof AcpRegistryErrorReason.Type;
70​
71export class AcpRegistryError extends Schema.TaggedErrorClass<AcpRegistryError>()(
72 "AcpRegistryError",
73 {
74 reason: AcpRegistryErrorReason,
75 detail: Schema.String,
76 cause: Schema.optional(Schema.Defect()),
77 },
78) {
79 override get message(): string {
80 return this.detail;
81 }
83​
84const isAcpRegistryError = Schema.is(AcpRegistryError);
85​
86export type AcpRegistryPlatformTarget =
87 | "darwin-aarch64"
88 | "darwin-x86_64"
89 | "linux-aarch64"
90 | "linux-x86_64"
91 | "windows-aarch64"
92 | "windows-x86_64";
93​
94export function resolveAcpRegistryPlatformTarget(
95 platform: NodeJS.Platform,
96 architecture: NodeJS.Architecture,
97): AcpRegistryPlatformTarget | undefined {
98 const os =
99 platform === "darwin"
100 ? "darwin"
101 : platform === "linux"
102 ? "linux"
103 : platform === "win32"
104 ? "windows"
105 : undefined;
106 const arch = architecture === "arm64" ? "aarch64" : architecture === "x64" ? "x86_64" : undefined;
107 return os && arch ? (`${os}-${arch}` as AcpRegistryPlatformTarget) : undefined;
109​
110export type AcpRegistryDistributionKind = "binary" | "npx" | "uvx";
111​
112export interface ResolvedAcpRegistryDistribution {
113 readonly kind: AcpRegistryDistributionKind;
114 readonly args: ReadonlyArray<string>;
115 readonly env: Readonly<Record<string, string>>;
116 readonly binaryTarget?: typeof AcpRegistryBinaryTarget.Type;
117 readonly packageName?: string;
119​
120export function resolveAcpRegistryDistribution(input: {
121 readonly agent: AcpRegistryAgent;
122 readonly preference: AcpRegistryDistributionPreference;
123 readonly platformTarget: AcpRegistryPlatformTarget | undefined;
124}): ResolvedAcpRegistryDistribution | undefined {
125 const { agent, platformTarget } = input;
126 const binary = platformTarget ? agent.distribution.binary?.[platformTarget] : undefined;
127 const candidates: ReadonlyArray<AcpRegistryDistributionKind> =
128 input.preference === "auto" ? ["binary", "npx", "uvx"] : [input.preference];
129​
130 for (const kind of candidates) {
131 if (kind === "binary" && binary) {
132 return {
133 kind,
134 args: binary.args ?? [],
135 env: binary.env ?? {},
136 binaryTarget: binary,
137 };
138 }
139 if (kind === "npx" && agent.distribution.npx) {
140 return {
141 kind,
142 args: agent.distribution.npx.args ?? [],
143 env: agent.distribution.npx.env ?? {},
144 packageName: agent.distribution.npx.package,
145 };
146 }
147 if (kind === "uvx" && agent.distribution.uvx) {
148 return {
149 kind,
150 args: agent.distribution.uvx.args ?? [],
151 env: agent.distribution.uvx.env ?? {},
152 packageName: agent.distribution.uvx.package,
153 };
154 }
155 }
156 return undefined;
158​
159export interface ResolvedAcpRegistryAgent {
160 readonly agent: AcpRegistryAgent;
161 readonly distribution: AcpRegistryDistributionKind;
162 readonly spawn: AcpSpawnInput;
164​
165export interface AcpRegistryResolverShape {
166 readonly resolve: (
167 settings: AcpRegistrySettings,
168 cwd: string,
169 environment?: NodeJS.ProcessEnv,
170 ) => Effect.Effect<ResolvedAcpRegistryAgent, AcpRegistryError>;
172​
173const INSTALL_LOCK_RETRY_COUNT = 300;
174const INSTALL_LOCK_RETRY_DELAY = "100 millis";
175const INSTALL_LOCK_STALE_MS = 5 * 60 * 1_000;
176const MAX_ARCHIVE_BYTES = 512 * 1024 * 1024;
177​
178function isAlreadyExists(error: PlatformError.PlatformError): boolean {
179 return error.reason._tag === "AlreadyExists";
181​
182function normalizeRegistryCommandPath(command: string): ReadonlyArray<string> | undefined {
183 const normalized = command.trim().replaceAll("\\", "/").replace(/^\.\//u, "");
184 const segments = normalized.split("/").filter((segment) => segment.length > 0);
185 if (
186 segments.length === 0 ||
187 normalized.startsWith("/") ||
188 /^[a-zA-Z]:/u.test(normalized) ||
189 segments.some((segment) => segment === "." || segment === "..")
190 ) {
191 return undefined;
192 }
193 return segments;
195​
196function validateArchiveEntries(output: string): boolean {
197 return output
198 .split(/\r?\n/u)
199 .map((entry) => entry.trim())
200 .filter((entry) => entry.length > 0)
201 .every((entry) => normalizeRegistryCommandPath(entry) !== undefined);
203​
204type ArchiveKind = "raw" | "tar_bz2" | "tar_gz" | "zip";
205​
206function archiveKind(url: string): ArchiveKind {
207 const pathname = new URL(url).pathname.toLowerCase();
208 if (pathname.endsWith(".tar.gz") || pathname.endsWith(".tgz")) return "tar_gz";
209 if (pathname.endsWith(".tar.bz2") || pathname.endsWith(".tbz2")) return "tar_bz2";
210 if (pathname.endsWith(".zip")) return "zip";
211 return "raw";
213​
214function archiveFileName(kind: ArchiveKind): string {
215 switch (kind) {
216 case "tar_gz":
217 return "agent.tar.gz";
218 case "tar_bz2":
219 return "agent.tar.bz2";
220 case "zip":
221 return "agent.zip";
222 case "raw":
223 return "agent.bin";
224 }
226​
227export const makeAcpRegistryResolver = Effect.fn("AcpRegistryResolver.make")(function* (input: {
228 readonly cacheDir: string;
229 readonly registryUrl?: string;
230}): Effect.fn.Return<
231 AcpRegistryResolverShape,
232 never,
233 | ChildProcessSpawner.ChildProcessSpawner
234 | FileSystem.FileSystem
235 | HttpClient.HttpClient
236 | Path.Path
237> {
238 const fileSystem = yield* FileSystem.FileSystem;
239 const path = yield* Path.Path;
240 const httpClient = yield* HttpClient.HttpClient;
241 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
242 const platform = yield* HostProcessPlatform;
243 const architecture = yield* HostProcessArchitecture;
244 const platformTarget = resolveAcpRegistryPlatformTarget(platform, architecture);
245 const registryUrl = input.registryUrl ?? ACP_REGISTRY_URL;
246 const registryDirectory = path.join(input.cacheDir, "acp-registry");
247 const registryCachePath = path.join(registryDirectory, "registry.json");
248 const installsDirectory = path.join(registryDirectory, "agents");
249 const registryRef = yield* Ref.make<AcpRegistryIndex | undefined>(undefined);
250 const registrySemaphore = yield* Semaphore.make(1);
251 const installSemaphore = yield* Semaphore.make(1);
252​
253 const decodeRegistryText = Effect.fn("AcpRegistryResolver.decodeRegistryText")(function* (
254 text: string,
255 ) {
256 const decoded = yield* decodeJson(text).pipe(
257 Effect.mapError(
258 (cause) =>
259 new AcpRegistryError({
260 reason: "registry_unavailable",
261 detail: "ACP Registry returned invalid JSON.",
262 cause,
263 }),
264 ),
265 );
266 return yield* decodeRegistryIndex(decoded).pipe(
267 Effect.mapError(
268 (cause) =>
269 new AcpRegistryError({
270 reason: "registry_unavailable",
271 detail: "ACP Registry returned an invalid index.",
272 cause,
273 }),
274 ),
275 );
276 });
277​
278 const readCachedRegistry = fileSystem
279 .readFileString(registryCachePath)
280 .pipe(Effect.flatMap(decodeRegistryText), Effect.option);
281​
282 const writeRegistryCache = (text: string) =>
283 fileSystem
284 .makeDirectory(registryDirectory, { recursive: true })
285 .pipe(
286 Effect.andThen(fileSystem.writeFileString(`${registryCachePath}.${process.pid}.tmp`, text)),
287 Effect.andThen(
288 fileSystem.rename(`${registryCachePath}.${process.pid}.tmp`, registryCachePath),
289 ),
290 Effect.ignore,
291 );
292​
293 const fetchRegistry = Effect.gen(function* () {
294 const response = yield* httpClient.execute(HttpClientRequest.get(registryUrl)).pipe(
295 Effect.flatMap(HttpClientResponse.filterStatusOk),
296 Effect.mapError(
297 (cause) =>
298 new AcpRegistryError({
299 reason: "registry_unavailable",
300 detail: `Could not fetch ACP Registry index from ${registryUrl}.`,
301 cause,
302 }),
303 ),
304 );
305 const text = yield* response.text.pipe(
306 Effect.mapError(
307 (cause) =>
308 new AcpRegistryError({
309 reason: "registry_unavailable",
310 detail: "Could not read ACP Registry response body.",
311 cause,
312 }),
313 ),
314 );
315 const registry = yield* decodeRegistryText(text);
316 yield* writeRegistryCache(text);
317 return registry;
318 });
319​
320 const loadRegistry = registrySemaphore.withPermits(1)(
321 Effect.gen(function* () {
322 const memoized = yield* Ref.get(registryRef);
323 if (memoized !== undefined) return memoized;
324 const registry = yield* fetchRegistry.pipe(
325 Effect.catch((networkError) =>
326 readCachedRegistry.pipe(
327 Effect.flatMap(
328 Option.match({
329 onNone: () => Effect.fail(networkError),
330 onSome: Effect.succeed,
331 }),
332 ),
333 ),
334 ),
335 );
336 yield* Ref.set(registryRef, registry);
337 return registry;
338 }),
339 );
340​
341 const runCommand = Effect.fn("AcpRegistryResolver.runCommand")(function* (
342 command: string,
343 args: ReadonlyArray<string>,
344 cwd?: string,
345 ) {
346 const child = yield* spawner.spawn(
347 ChildProcess.make(command, args, {
348 ...(cwd ? { cwd } : {}),
349 shell: false,
350 }),
351 );
352 const [stdout, stderr, exitCode] = yield* Effect.all(
353 [
354 collectUint8StreamText({ stream: child.stdout }),
355 collectUint8StreamText({ stream: child.stderr }),
356 child.exitCode,
357 ],
358 { concurrency: "unbounded" },
359 );
360 if (Number(exitCode) !== 0) {
361 return yield* new AcpRegistryError({
362 reason: "install_failed",
363 detail: `ACP Registry install command '${command}' exited with code ${Number(exitCode)}: ${stderr.text.trim()}`,
364 });
365 }
366 return stdout.text;
367 });
368​
369 const acquireInstallLock = Effect.fn("AcpRegistryResolver.acquireInstallLock")(function* (
370 lockPath: string,
371 ) {
372 for (let attempt = 0; attempt < INSTALL_LOCK_RETRY_COUNT; attempt += 1) {
373 const acquired = yield* fileSystem.writeFileString(lockPath, "", { flag: "wx" }).pipe(
374 Effect.as(true),
375 Effect.catch((error) =>
376 isAlreadyExists(error) ? Effect.succeed(false) : Effect.fail(error),
377 ),
378 );
379 if (acquired) return;
380 const now = yield* Clock.currentTimeMillis;
381 const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option);
382 const mtime = Option.flatMap(lockInfo, (info) => info.mtime);
383 if (Option.isSome(mtime) && now - mtime.value.getTime() > INSTALL_LOCK_STALE_MS) {
384 yield* fileSystem.remove(lockPath, { force: true });
385 continue;
386 }
387 yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY);
388 }
389 return yield* new AcpRegistryError({
390 reason: "install_failed",
391 detail: `Timed out waiting for ACP Registry install lock ${lockPath}.`,
392 });
393 });
394​
395 const assertExecutableInRoot = Effect.fn("AcpRegistryResolver.assertExecutableInRoot")(function* (
396 root: string,
397 executablePath: string,
398 ) {
399 const rootRealPath = yield* fileSystem.realPath(root);
400 const executableRealPath = yield* fileSystem.realPath(executablePath);
401 const relative = path.relative(rootRealPath, executableRealPath);
402 if (relative.startsWith("..") || path.isAbsolute(relative)) {
403 return yield* new AcpRegistryError({
404 reason: "archive_invalid",
405 detail: "ACP Registry archive command resolves outside its installation directory.",
406 });
407 }
408 return executableRealPath;
409 });
410​
411 const installBinary = Effect.fn("AcpRegistryResolver.installBinary")(function* (
412 agent: AcpRegistryAgent,
413 target: typeof AcpRegistryBinaryTarget.Type,
414 ) {
415 if (platformTarget === undefined) {
416 return yield* new AcpRegistryError({
417 reason: "unsupported_platform",
418 detail: `ACP Registry does not support platform ${platform}-${architecture}.`,
419 });
420 }
421 const commandSegments = normalizeRegistryCommandPath(target.cmd);
422 if (commandSegments === undefined) {
423 return yield* new AcpRegistryError({
424 reason: "archive_invalid",
425 detail: `ACP Registry agent ${agent.id} declares an unsafe command path '${target.cmd}'.`,
426 });
427 }
428 const installRoot = path.join(installsDirectory, agent.id, agent.version, platformTarget);
429 const executablePath = path.join(installRoot, ...commandSegments);
430 if (yield* fileSystem.exists(executablePath).pipe(Effect.orElseSucceed(() => false))) {
431 return yield* assertExecutableInRoot(installRoot, executablePath).pipe(
432 Effect.mapError((cause) =>
433 isAcpRegistryError(cause)
434 ? cause
435 : new AcpRegistryError({
436 reason: "install_failed",
437 detail: `Could not validate cached ACP Registry agent ${agent.id}.`,
438 cause,
439 }),
440 ),
441 );
442 }
443​
444 yield* fileSystem.makeDirectory(path.dirname(installRoot), { recursive: true }).pipe(
445 Effect.mapError(
446 (cause) =>
447 new AcpRegistryError({
448 reason: "install_failed",
449 detail: `Could not create ACP Registry cache for ${agent.id}.`,
450 cause,
451 }),
452 ),
453 );
454 const lockPath = `${installRoot}.lock`;
455 yield* acquireInstallLock(lockPath).pipe(
456 Effect.mapError((cause) =>
457 isAcpRegistryError(cause)
458 ? cause
459 : new AcpRegistryError({
460 reason: "install_failed",
461 detail: `Could not acquire install lock for ACP Registry agent ${agent.id}.`,
462 cause,
463 }),
464 ),
465 );
466​
467 return yield* Effect.gen(function* () {
468 if (yield* fileSystem.exists(executablePath).pipe(Effect.orElseSucceed(() => false))) {
469 return yield* assertExecutableInRoot(installRoot, executablePath);
470 }
471 const temporaryRoot = yield* fileSystem.makeTempDirectoryScoped({
472 directory: path.dirname(installRoot),
473 prefix: `.${agent.id}-install-`,
474 });
475 const extractionRoot = path.join(temporaryRoot, "extracted");
476 yield* fileSystem.makeDirectory(extractionRoot, { recursive: true });
477 const kind = archiveKind(target.archive);
478 const archivePath = path.join(temporaryRoot, archiveFileName(kind));
479 const response = yield* httpClient.execute(HttpClientRequest.get(target.archive)).pipe(
480 Effect.flatMap(HttpClientResponse.filterStatusOk),
481 Effect.mapError(
482 (cause) =>
483 new AcpRegistryError({
484 reason: "download_failed",
485 detail: `Could not download ACP Registry agent ${agent.id} ${agent.version}.`,
486 cause,
487 }),
488 ),
489 );
490 const bytes = new Uint8Array(
491 yield* response.arrayBuffer.pipe(
492 Effect.mapError(
493 (cause) =>
494 new AcpRegistryError({
495 reason: "download_failed",
496 detail: `Could not read ACP Registry agent ${agent.id} download.`,
497 cause,
498 }),
499 ),
500 ),
501 );
502 if (bytes.byteLength > MAX_ARCHIVE_BYTES) {
503 return yield* new AcpRegistryError({
504 reason: "archive_invalid",
505 detail: `ACP Registry agent ${agent.id} archive exceeds ${MAX_ARCHIVE_BYTES} bytes.`,
506 });
507 }
508 yield* fileSystem.writeFile(archivePath, bytes);
509​
510 if (kind === "raw") {
511 const targetPath = path.join(extractionRoot, ...commandSegments);
512 yield* fileSystem.makeDirectory(path.dirname(targetPath), { recursive: true });
513 yield* fileSystem.rename(archivePath, targetPath);
514 } else {
515 const listArgs =
516 kind === "tar_gz"
517 ? ["-tzf", archivePath]
518 : kind === "tar_bz2"
519 ? ["-tjf", archivePath]
520 : platform === "win32"
521 ? ["-tf", archivePath]
522 : undefined;
523 const entries =
524 listArgs === undefined
525 ? yield* runCommand("unzip", ["-Z1", archivePath])
526 : yield* runCommand("tar", listArgs);
527 if (!validateArchiveEntries(entries)) {
528 return yield* new AcpRegistryError({
529 reason: "archive_invalid",
530 detail: `ACP Registry agent ${agent.id} archive contains an unsafe path.`,
531 });
532 }
533 if (kind === "zip" && platform !== "win32") {
534 yield* runCommand("unzip", ["-q", archivePath, "-d", extractionRoot]);
535 } else {
536 const extractFlag = kind === "tar_gz" ? "-xzf" : kind === "tar_bz2" ? "-xjf" : "-xf";
537 yield* runCommand("tar", [extractFlag, archivePath, "-C", extractionRoot]);
538 }
539 }
540​
541 const stagedExecutable = path.join(extractionRoot, ...commandSegments);
542 if (!(yield* fileSystem.exists(stagedExecutable).pipe(Effect.orElseSucceed(() => false)))) {
543 return yield* new AcpRegistryError({
544 reason: "archive_invalid",
545 detail: `ACP Registry archive for ${agent.id} did not contain '${target.cmd}'.`,
546 });
547 }
548 if (platform !== "win32") yield* fileSystem.chmod(stagedExecutable, 0o755);
549 yield* assertExecutableInRoot(extractionRoot, stagedExecutable);
550 yield* fileSystem.remove(installRoot, { recursive: true, force: true });
551 yield* fileSystem.rename(extractionRoot, installRoot);
552 return yield* assertExecutableInRoot(installRoot, executablePath);
553 }).pipe(
554 Effect.scoped,
555 Effect.ensuring(fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore)),
556 Effect.mapError((cause) =>
557 isAcpRegistryError(cause)
558 ? cause
559 : new AcpRegistryError({
560 reason: "install_failed",
561 detail: `Could not install ACP Registry agent ${agent.id}.`,
562 cause,
563 }),
564 ),
565 );
566 });
567​
568 const resolve: AcpRegistryResolverShape["resolve"] = (settings, cwd, environment) =>
569 Effect.gen(function* () {
570 const agentId = settings.agentId.trim();
571 if (agentId.length === 0) {
572 return yield* new AcpRegistryError({
573 reason: "agent_not_configured",
574 detail: "ACP Registry provider requires a registry agent ID.",
575 });
576 }
577 const registry = yield* loadRegistry;
578 const agent = registry.agents.find((candidate) => candidate.id === agentId);
579 if (agent === undefined) {
580 return yield* new AcpRegistryError({
581 reason: "agent_not_found",
582 detail: `ACP Registry does not contain agent '${agentId}'.`,
583 });
584 }
585 const distribution = resolveAcpRegistryDistribution({
586 agent,
587 preference: settings.distribution,
588 platformTarget,
589 });
590 if (distribution === undefined) {
591 return yield* new AcpRegistryError({
592 reason:
593 platformTarget === undefined ? "unsupported_platform" : "unsupported_distribution",
594 detail: `ACP Registry agent ${agent.id} has no ${settings.distribution === "auto" ? "compatible" : settings.distribution} distribution for ${platform}-${architecture}.`,
595 });
596 }
597​
598 let command: string;
599 let args: ReadonlyArray<string>;
600 const commandOverride = settings.commandPath.trim();
601 if (commandOverride.length > 0) {
602 command = commandOverride;
603 args = distribution.args;
604 } else if (distribution.kind === "npx") {
605 command = "npx";
606 args = ["--yes", distribution.packageName!, ...distribution.args];
607 } else if (distribution.kind === "uvx") {
608 command = "uvx";
609 args = [distribution.packageName!, ...distribution.args];
610 } else {
611 command = yield* installSemaphore.withPermits(1)(
612 installBinary(agent, distribution.binaryTarget!),
613 );
614 args = distribution.args;
615 }
616​
617 return {
618 agent,
619 distribution: distribution.kind,
620 spawn: {
621 command,
622 args,
623 cwd,
624 env: {
625 ...environment,
626 ...distribution.env,
627 },
628 },
629 } satisfies ResolvedAcpRegistryAgent;
630 });
631​
632 return { resolve };
633});