From 792e19fc268aa17e0aa760c27b9a371d6b76c2d5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 1 May 2026 16:44:29 -0700 Subject: [PATCH] Refactor ACP binary registry installation - Move ACP binary install and launch resolution into a shared module - Switch stream exposure to a getter so runtime events stay fresh - Keep WebSocket RPC handlers thin and reuse registry install helpers --- .../src/provider/Layers/GenericAcpAdapter.ts | 4 +- .../acp/AcpRegistryBinaryInstaller.ts | 432 ++++++++++++++++++ apps/server/src/ws.ts | 415 +---------------- 3 files changed, 453 insertions(+), 398 deletions(-) create mode 100644 apps/server/src/provider/acp/AcpRegistryBinaryInstaller.ts diff --git a/apps/server/src/provider/Layers/GenericAcpAdapter.ts b/apps/server/src/provider/Layers/GenericAcpAdapter.ts index a151653fd1..cc9a7c0edb 100644 --- a/apps/server/src/provider/Layers/GenericAcpAdapter.ts +++ b/apps/server/src/provider/Layers/GenericAcpAdapter.ts @@ -737,7 +737,9 @@ export function makeGenericAcpAdapter( listSessions, hasSession, stopAll, - streamEvents: Stream.fromPubSub(runtimeEventPubSub), + get streamEvents() { + return Stream.fromPubSub(runtimeEventPubSub); + }, } satisfies ProviderAdapterShape; }); } diff --git a/apps/server/src/provider/acp/AcpRegistryBinaryInstaller.ts b/apps/server/src/provider/acp/AcpRegistryBinaryInstaller.ts new file mode 100644 index 0000000000..9d9e2e28f0 --- /dev/null +++ b/apps/server/src/provider/acp/AcpRegistryBinaryInstaller.ts @@ -0,0 +1,432 @@ +import { Data, Effect, FileSystem, Path, Schema } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; + +import { + type AcpRegistryAgent, + type AcpRegistryInstallBinaryResult, + type AcpRegistryListResult, +} from "@t3tools/contracts"; + +import { ServerConfig } from "../../config.ts"; +import { collectStreamAsString } from "../providerSnapshot.ts"; + +const ACP_BINARY_INSTALLS_DIR = "acp_agents"; +const ACP_BINARY_MANIFEST_FILE = "install.json"; + +type BinaryDistributionTarget = { + readonly archive: string; + readonly cmd: string; +}; + +class AcpRegistryBinaryInstallError extends Data.TaggedError("AcpRegistryBinaryInstallError")<{ + readonly detail: string; + readonly cause?: unknown; +}> {} + +const AcpBinaryInstallManifest = Schema.Struct({ + layoutVersion: Schema.Literal(2), + agentId: Schema.String, + version: Schema.String, + platformKey: Schema.String, + command: Schema.String, + archiveUrl: Schema.String, +}); + +type AcpBinaryInstallManifest = typeof AcpBinaryInstallManifest.Type; + +function getAcpBinaryPlatformKey(): string { + const os = process.platform; + const cpu = process.arch; + const osKey = + os === "darwin" ? "darwin" : os === "win32" ? "windows" : os === "linux" ? "linux" : os; + const archKey = cpu === "arm64" ? "aarch64" : cpu === "x64" ? "x86_64" : cpu; + return `${osKey}-${archKey}`; +} + +function getBinaryTarget(agent: AcpRegistryAgent): BinaryDistributionTarget | null { + const binary = agent.distribution.binary; + if (!binary || typeof binary !== "object" || globalThis.Array.isArray(binary)) return null; + const target = (binary as Record)[getAcpBinaryPlatformKey()]; + if (!target || typeof target !== "object" || globalThis.Array.isArray(target)) return null; + const record = target as Record; + if (typeof record.archive !== "string" || typeof record.cmd !== "string") return null; + return { archive: record.archive, cmd: record.cmd }; +} + +function resolveHomeDirectory(): string { + return process.env.HOME ?? process.env.USERPROFILE ?? ""; +} + +function normalizeArchiveCommandPath(path: Path.Path, command: string): string { + const trimmed = command.trim(); + if (!trimmed) { + throw new Error("Registry binary command must not be empty."); + } + if (path.isAbsolute(trimmed)) { + throw new Error("Registry binary command must be a relative archive path."); + } + const withoutLeadingDot = trimmed.replace(/^(?:\.[/\\])+/u, ""); + const parts = withoutLeadingDot + .split(/[/\\]+/u) + .filter((part) => part.length > 0 && part !== "."); + if (parts.length === 0 || parts.some((part) => part === "..")) { + throw new Error("Registry binary command resolves outside the archive."); + } + return path.join(...parts); +} + +function resolveInstallRootFromBinaryPath( + path: Path.Path, + binaryPath: string, + commandRelativePath: string, +): string { + const depth = commandRelativePath.split(/[/\\]+/u).filter((part) => part.length > 0).length; + let installRoot = binaryPath; + for (let index = 0; index < depth; index += 1) { + installRoot = path.dirname(installRoot); + } + return installRoot; +} + +function resolveAcpBinaryInstallPath( + path: Path.Path, + config: { readonly stateDir: string }, + agent: AcpRegistryAgent, +) { + const commandPath = normalizeArchiveCommandPath(path, getBinaryTarget(agent)?.cmd ?? agent.id); + return path.join(config.stateDir, ACP_BINARY_INSTALLS_DIR, agent.id, agent.version, commandPath); +} + +function expandUserPath(path: Path.Path, inputPath: string): string { + const home = resolveHomeDirectory(); + if (!home) return inputPath; + if (inputPath === "~") return home; + if (inputPath.startsWith("~/") || inputPath.startsWith("~\\")) { + return path.join(home, inputPath.slice(2)); + } + return inputPath; +} + +function normalizeAcpBinaryInstallPath(path: Path.Path, inputPath: string): string { + const expanded = expandUserPath(path, inputPath.trim()); + return path.isAbsolute(expanded) ? expanded : path.resolve(expanded); +} + +function displayPath(path: Path.Path, inputPath: string): string { + const home = resolveHomeDirectory(); + return home && (inputPath === home || inputPath.startsWith(`${home}${path.sep}`)) + ? `~${inputPath.slice(home.length)}` + : inputPath; +} + +function isPathInside(path: Path.Path, parent: string, child: string): boolean { + const relativePath = path.relative(parent, child); + return relativePath === "" || (!relativePath.startsWith("..") && !path.isAbsolute(relativePath)); +} + +function toBinaryInstallPreview( + path: Path.Path, + config: { readonly stateDir: string }, + agent: AcpRegistryAgent, + target: BinaryDistributionTarget, +) { + const defaultInstallPath = resolveAcpBinaryInstallPath(path, config, agent); + return { + archiveUrl: target.archive, + defaultInstallPath: displayPath(path, defaultInstallPath), + platformKey: getAcpBinaryPlatformKey(), + command: target.cmd, + }; +} + +function resolveAcpBinaryManifestPath( + path: Path.Path, + config: { readonly stateDir: string }, + agent: AcpRegistryAgent, +) { + return path.join( + path.dirname(resolveAcpBinaryInstallPath(path, config, agent)), + ACP_BINARY_MANIFEST_FILE, + ); +} + +const readAcpBinaryManifest = (config: { readonly stateDir: string }, agent: AcpRegistryAgent) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const manifestPath = resolveAcpBinaryManifestPath(path, config, agent); + const raw = yield* fs.readFileString(manifestPath).pipe(Effect.option); + if (raw._tag === "None") return null; + const json = yield* Effect.try({ + try: () => JSON.parse(raw.value) as unknown, + catch: () => null, + }); + if (json === null) return null; + const parsed = yield* Schema.decodeUnknownEffect(AcpBinaryInstallManifest)(json).pipe( + Effect.option, + ); + if (parsed._tag === "None") return null; + const manifest = parsed.value; + if ( + manifest.agentId === agent.id && + manifest.version === agent.version && + manifest.platformKey === getAcpBinaryPlatformKey() && + (yield* fs.exists(manifest.command)) + ) { + return manifest; + } + return null; + }); + +const downloadFile = (url: string, destination: string) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const bytes = yield* Effect.tryPromise({ + try: async () => { + const response = await fetch(url); + if (!response.ok) { + throw new Error(`Download failed with status ${response.status}`); + } + return new Uint8Array(await response.arrayBuffer()); + }, + catch: (cause) => + new AcpRegistryBinaryInstallError({ + detail: cause instanceof Error ? cause.message : String(cause), + cause, + }), + }); + yield* fs.writeFile(destination, bytes); + }); + +const runArchiveCommand = (command: string, args: ReadonlyArray) => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const child = yield* spawner.spawn(ChildProcess.make(command, [...args])); + const [stdout, stderr, exitCode] = yield* Effect.all( + [collectStreamAsString(child.stdout), collectStreamAsString(child.stderr), child.exitCode], + { concurrency: "unbounded" }, + ); + if (Number(exitCode) !== 0) { + return yield* Effect.fail( + new Error( + `Archive command '${command}' failed with exit code ${String(exitCode)}: ${ + stderr || stdout + }`, + ), + ); + } + }).pipe(Effect.scoped); + +const extractArchive = (archivePath: string, destinationDir: string) => { + if (archivePath.endsWith(".tar.gz") || archivePath.endsWith(".tgz")) { + return runArchiveCommand("tar", ["-xzf", archivePath, "-C", destinationDir]); + } + if (archivePath.endsWith(".zip")) { + if (process.platform === "win32") { + return runArchiveCommand("powershell.exe", [ + "-NoProfile", + "-Command", + "Expand-Archive", + "-LiteralPath", + archivePath, + "-DestinationPath", + destinationDir, + "-Force", + ]); + } + return runArchiveCommand("unzip", ["-q", archivePath, "-d", destinationDir]); + } + return Effect.fail(new Error("Unsupported binary archive format.")); +}; + +function toInstallError(cause: unknown): string { + return cause instanceof Error ? cause.message : String(cause); +} + +const installAcpBinaryAgent = (input: { + readonly config: { readonly stateDir: string }; + readonly agent: AcpRegistryAgent; + readonly installPath?: string | undefined; +}) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const target = getBinaryTarget(input.agent); + if (!target) { + return yield* Effect.fail( + new Error(`No binary is available for ${getAcpBinaryPlatformKey()}.`), + ); + } + const installPath = normalizeAcpBinaryInstallPath( + path, + input.installPath?.trim() || resolveAcpBinaryInstallPath(path, input.config, input.agent), + ); + const commandPath = normalizeArchiveCommandPath(path, target.cmd); + const installRoot = resolveInstallRootFromBinaryPath(path, installPath, commandPath); + if (installRoot === path.dirname(installRoot)) { + return yield* Effect.fail( + new Error(`Binary path is too shallow for registry command '${target.cmd}'.`), + ); + } + const manifestPath = resolveAcpBinaryManifestPath(path, input.config, input.agent); + const tempDir = yield* fs.makeTempDirectory({ prefix: "t3-acp-agent-" }); + yield* Effect.addFinalizer(() => + fs.remove(tempDir, { recursive: true, force: true }).pipe(Effect.ignore), + ); + + const archivePath = path.join( + tempDir, + path.basename(new URL(target.archive).pathname) || "agent.archive", + ); + const extractDir = path.join(tempDir, "extract"); + yield* fs.makeDirectory(extractDir, { recursive: true }); + yield* downloadFile(target.archive, archivePath); + yield* extractArchive(archivePath, extractDir); + + const extractedCommand = path.resolve(extractDir, commandPath); + if (!isPathInside(path, extractDir, extractedCommand)) { + return yield* Effect.fail(new Error("Registry binary command resolves outside the archive.")); + } + if (!(yield* fs.exists(extractedCommand))) { + return yield* Effect.fail( + new Error(`Installed archive did not contain expected command '${target.cmd}'.`), + ); + } + yield* fs.makeDirectory(installRoot, { recursive: true }); + yield* fs.copy(extractDir, installRoot, { overwrite: true }); + if (!(yield* fs.exists(installPath))) { + yield* fs.makeDirectory(path.dirname(installPath), { recursive: true }); + yield* fs.copyFile(extractedCommand, installPath); + } + if (process.platform !== "win32") { + yield* fs.chmod(installPath, 0o755); + } + const manifest: AcpBinaryInstallManifest = { + layoutVersion: 2, + agentId: input.agent.id, + version: input.agent.version, + platformKey: getAcpBinaryPlatformKey(), + command: installPath, + archiveUrl: target.archive, + }; + yield* fs.makeDirectory(path.dirname(manifestPath), { recursive: true }); + yield* fs.writeFileString(manifestPath, JSON.stringify(manifest, null, 2)); + return { ...target, command: installPath }; + }).pipe(Effect.scoped); + +export const toAcpLaunchSpec = (agent: AcpRegistryAgent) => + Effect.gen(function* () { + const config = yield* ServerConfig; + const path = yield* Path.Path; + if (agent.distribution.npx) { + return { + supported: true as const, + distributionType: "npx" as const, + launch: { + command: "npx", + args: ["-y", agent.distribution.npx.package, ...(agent.distribution.npx.args ?? [])], + env: agent.distribution.npx.env ?? {}, + }, + }; + } + if (agent.distribution.uvx) { + return { + supported: true as const, + distributionType: "uvx" as const, + launch: { + command: "uvx", + args: [agent.distribution.uvx.package, ...(agent.distribution.uvx.args ?? [])], + env: agent.distribution.uvx.env ?? {}, + }, + }; + } + const manifest = yield* readAcpBinaryManifest(config, agent); + const target = getBinaryTarget(agent); + if (manifest) { + return { + supported: true as const, + distributionType: "binary" as const, + launch: { + command: manifest.command, + args: [], + env: {}, + }, + ...(target ? { binaryInstall: toBinaryInstallPreview(path, config, agent, target) } : {}), + }; + } + return { + supported: false as const, + distributionType: "binaryUnsupported" as const, + launch: null, + ...(target ? { binaryInstall: toBinaryInstallPreview(path, config, agent, target) } : {}), + }; + }); + +export const listAcpRegistryAgents = (registry: { + readonly version: string; + readonly agents: ReadonlyArray; +}) => + Effect.gen(function* () { + const agents = yield* Effect.forEach(registry.agents, (agent) => + toAcpLaunchSpec(agent).pipe( + Effect.map((resolved) => ({ + agent, + supported: resolved.supported, + distributionType: resolved.distributionType, + launch: resolved.launch, + ...("binaryInstall" in resolved && resolved.binaryInstall + ? { binaryInstall: resolved.binaryInstall } + : {}), + })), + ), + ); + return { + registryVersion: registry.version, + agents: agents.toSorted((left, right) => left.agent.name.localeCompare(right.agent.name)), + } satisfies AcpRegistryListResult; + }); + +export const installAcpRegistryBinaryAgent = (input: { + readonly registry: { + readonly agents: ReadonlyArray; + }; + readonly agentId: string; + readonly installPath?: string | undefined; +}) => + Effect.gen(function* () { + const config = yield* ServerConfig; + const path = yield* Path.Path; + const agent = input.registry.agents.find((entry) => entry.id === input.agentId); + if (!agent) { + return { + ok: false, + error: `No ACP registry agent found for '${input.agentId}'.`, + } satisfies AcpRegistryInstallBinaryResult; + } + const installed = yield* installAcpBinaryAgent({ + config, + agent, + installPath: input.installPath, + }); + return { + ok: true, + agent: { + agent, + supported: true, + distributionType: "binary", + binaryInstall: toBinaryInstallPreview(path, config, agent, installed), + launch: { + command: installed.command, + args: [], + env: {}, + }, + }, + } satisfies AcpRegistryInstallBinaryResult; + }).pipe( + Effect.catch((cause: unknown) => + Effect.succeed({ + ok: false, + error: toInstallError(cause), + } satisfies AcpRegistryInstallBinaryResult), + ), + ); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 9669c40edd..a69665418e 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1,28 +1,7 @@ -import { execFile } from "node:child_process"; -import { createWriteStream } from "node:fs"; -import { - access, - chmod, - copyFile, - cp, - mkdir, - mkdtemp, - readFile, - rm, - writeFile, -} from "node:fs/promises"; -import { arch, homedir, platform, tmpdir } from "node:os"; -import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path"; -import { pipeline } from "node:stream/promises"; -import { promisify } from "node:util"; - import { Cause, Duration, Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect"; import { type AuthAccessStreamEvent, AcpRegistryIndex, - type AcpRegistryAgent, - type AcpRegistryInstallBinaryResult, - type AcpRegistryListResult, AuthSessionId, CommandId, EventId, @@ -97,8 +76,10 @@ import { type SessionCredentialChange, } from "./auth/Services/SessionCredentialService.ts"; import { respondToAuthError } from "./auth/http.ts"; - -const execFileAsync = promisify(execFile); +import { + installAcpRegistryBinaryAgent, + listAcpRegistryAgents, +} from "./provider/acp/AcpRegistryBinaryInstaller.ts"; function isThreadDetailEvent(event: OrchestrationEvent): event is Extract< OrchestrationEvent, @@ -123,313 +104,6 @@ function isThreadDetailEvent(event: OrchestrationEvent): event is Extract< } const PROVIDER_STATUS_DEBOUNCE_MS = 200; -const ACP_BINARY_INSTALLS_DIR = "acp_agents"; -const ACP_BINARY_MANIFEST_FILE = "install.json"; - -type BinaryDistributionTarget = { - readonly archive: string; - readonly cmd: string; -}; - -type AcpBinaryInstallManifest = { - readonly layoutVersion: 2; - readonly agentId: string; - readonly version: string; - readonly platformKey: string; - readonly command: string; - readonly archiveUrl: string; -}; - -function getAcpBinaryPlatformKey(): string { - const os = platform(); - const cpu = arch(); - const osKey = - os === "darwin" ? "darwin" : os === "win32" ? "windows" : os === "linux" ? "linux" : os; - const archKey = cpu === "arm64" ? "aarch64" : cpu === "x64" ? "x86_64" : cpu; - return `${osKey}-${archKey}`; -} - -function getBinaryTarget(agent: AcpRegistryAgent): BinaryDistributionTarget | null { - const binary = agent.distribution.binary; - if (!binary || typeof binary !== "object" || globalThis.Array.isArray(binary)) return null; - const target = (binary as Record)[getAcpBinaryPlatformKey()]; - if (!target || typeof target !== "object" || globalThis.Array.isArray(target)) return null; - const record = target as Record; - if (typeof record.archive !== "string" || typeof record.cmd !== "string") return null; - return { archive: record.archive, cmd: record.cmd }; -} - -async function fileExists(path: string): Promise { - try { - await access(path); - return true; - } catch { - return false; - } -} - -function normalizeArchiveCommandPath(command: string): string { - const trimmed = command.trim(); - if (!trimmed) { - throw new Error("Registry binary command must not be empty."); - } - if (isAbsolute(trimmed)) { - throw new Error("Registry binary command must be a relative archive path."); - } - const withoutLeadingDot = trimmed.replace(/^(?:\.[/\\])+/u, ""); - const parts = withoutLeadingDot - .split(/[/\\]+/u) - .filter((part) => part.length > 0 && part !== "."); - if (parts.length === 0 || parts.some((part) => part === "..")) { - throw new Error("Registry binary command resolves outside the archive."); - } - return join(...parts); -} - -function resolveInstallRootFromBinaryPath(binaryPath: string, commandRelativePath: string): string { - const depth = commandRelativePath.split(/[/\\]+/u).filter((part) => part.length > 0).length; - let installRoot = binaryPath; - for (let index = 0; index < depth; index += 1) { - installRoot = dirname(installRoot); - } - return installRoot; -} - -function resolveAcpBinaryInstallPath( - config: { readonly stateDir: string }, - agent: AcpRegistryAgent, -) { - const commandPath = normalizeArchiveCommandPath(getBinaryTarget(agent)?.cmd ?? agent.id); - return join(config.stateDir, ACP_BINARY_INSTALLS_DIR, agent.id, agent.version, commandPath); -} - -function expandUserPath(path: string): string { - if (path === "~") return homedir(); - if (path.startsWith("~/") || path.startsWith("~\\")) return join(homedir(), path.slice(2)); - return path; -} - -function normalizeAcpBinaryInstallPath(path: string): string { - const expanded = expandUserPath(path.trim()); - return isAbsolute(expanded) ? expanded : resolve(expanded); -} - -function displayPath(path: string): string { - const home = homedir(); - return path === home || path.startsWith(`${home}/`) || path.startsWith(`${home}\\`) - ? `~${path.slice(home.length)}` - : path; -} - -function isPathInside(parent: string, child: string): boolean { - const relativePath = relative(parent, child); - return relativePath === "" || (!relativePath.startsWith("..") && !isAbsolute(relativePath)); -} - -function toBinaryInstallPreview( - config: { readonly stateDir: string }, - agent: AcpRegistryAgent, - target: BinaryDistributionTarget, -) { - const defaultInstallPath = resolveAcpBinaryInstallPath(config, agent); - return { - archiveUrl: target.archive, - defaultInstallPath: displayPath(defaultInstallPath), - platformKey: getAcpBinaryPlatformKey(), - command: target.cmd, - }; -} - -function resolveAcpBinaryManifestPath( - config: { readonly stateDir: string }, - agent: AcpRegistryAgent, -) { - return join(dirname(resolveAcpBinaryInstallPath(config, agent)), ACP_BINARY_MANIFEST_FILE); -} - -async function readAcpBinaryManifest( - config: { readonly stateDir: string }, - agent: AcpRegistryAgent, -): Promise { - const manifestPath = resolveAcpBinaryManifestPath(config, agent); - try { - const raw = await readFile(manifestPath, "utf8"); - const parsed = JSON.parse(raw) as Partial; - if ( - parsed.layoutVersion === 2 && - parsed.agentId === agent.id && - parsed.version === agent.version && - parsed.platformKey === getAcpBinaryPlatformKey() && - typeof parsed.command === "string" && - (await fileExists(parsed.command)) - ) { - return parsed as AcpBinaryInstallManifest; - } - return null; - } catch { - return null; - } -} - -async function downloadFile(url: string, destination: string): Promise { - const response = await fetch(url); - if (!response.ok || !response.body) { - throw new Error(`Download failed with status ${response.status}`); - } - await pipeline(response.body, createWriteStream(destination)); -} - -async function extractArchive(archivePath: string, destinationDir: string): Promise { - if (archivePath.endsWith(".tar.gz") || archivePath.endsWith(".tgz")) { - await execFileAsync("tar", ["-xzf", archivePath, "-C", destinationDir]); - return; - } - if (archivePath.endsWith(".zip")) { - if (platform() === "win32") { - await execFileAsync("powershell.exe", [ - "-NoProfile", - "-Command", - "Expand-Archive", - "-LiteralPath", - archivePath, - "-DestinationPath", - destinationDir, - "-Force", - ]); - return; - } - await execFileAsync("unzip", ["-q", archivePath, "-d", destinationDir]); - return; - } - throw new Error("Unsupported binary archive format."); -} - -async function installAcpBinaryAgent(input: { - readonly config: { readonly stateDir: string }; - readonly agent: AcpRegistryAgent; - readonly installPath?: string | undefined; -}): Promise { - const target = getBinaryTarget(input.agent); - if (!target) { - throw new Error(`No binary is available for ${getAcpBinaryPlatformKey()}.`); - } - const installPath = normalizeAcpBinaryInstallPath( - input.installPath?.trim() || resolveAcpBinaryInstallPath(input.config, input.agent), - ); - const commandPath = normalizeArchiveCommandPath(target.cmd); - const installRoot = resolveInstallRootFromBinaryPath(installPath, commandPath); - if (installRoot === dirname(installRoot)) { - throw new Error(`Binary path is too shallow for registry command '${target.cmd}'.`); - } - const manifestPath = resolveAcpBinaryManifestPath(input.config, input.agent); - const tempDir = await mkdtemp(join(tmpdir(), "t3-acp-agent-")); - try { - const archivePath = join( - tempDir, - basename(new URL(target.archive).pathname) || "agent.archive", - ); - const extractDir = join(tempDir, "extract"); - await mkdir(extractDir, { recursive: true }); - await downloadFile(target.archive, archivePath); - await extractArchive(archivePath, extractDir); - - const extractedCommand = resolve(extractDir, commandPath); - if (!isPathInside(extractDir, extractedCommand)) { - throw new Error(`Registry binary command resolves outside the archive.`); - } - if (!(await fileExists(extractedCommand))) { - throw new Error(`Installed archive did not contain expected command '${target.cmd}'.`); - } - await mkdir(installRoot, { recursive: true }); - await cp(extractDir, installRoot, { - recursive: true, - force: true, - errorOnExist: false, - }); - if (!(await fileExists(installPath))) { - await mkdir(dirname(installPath), { recursive: true }); - await copyFile(extractedCommand, installPath); - } - if (platform() !== "win32") { - await chmod(installPath, 0o755); - } - } finally { - await rm(tempDir, { recursive: true, force: true }); - } - const manifest: AcpBinaryInstallManifest = { - layoutVersion: 2, - agentId: input.agent.id, - version: input.agent.version, - platformKey: getAcpBinaryPlatformKey(), - command: installPath, - archiveUrl: target.archive, - }; - await mkdir(dirname(manifestPath), { recursive: true }); - await writeFile(manifestPath, JSON.stringify(manifest, null, 2)); - return { ...target, command: installPath }; -} - -async function toAcpLaunchSpec( - agent: AcpRegistryAgent, - config: { readonly stateDir: string }, -): Promise<{ - readonly supported: boolean; - readonly distributionType: "npx" | "uvx" | "binary" | "binaryUnsupported"; - readonly launch: { - readonly command: string; - readonly args: readonly string[]; - readonly env: Record; - } | null; - readonly binaryInstall?: { - readonly archiveUrl: string; - readonly defaultInstallPath: string; - readonly platformKey: string; - readonly command: string; - }; -}> { - if (agent.distribution.npx) { - return { - supported: true as const, - distributionType: "npx" as const, - launch: { - command: "npx", - args: ["-y", agent.distribution.npx.package, ...(agent.distribution.npx.args ?? [])], - env: agent.distribution.npx.env ?? {}, - }, - }; - } - if (agent.distribution.uvx) { - return { - supported: true as const, - distributionType: "uvx" as const, - launch: { - command: "uvx", - args: [agent.distribution.uvx.package, ...(agent.distribution.uvx.args ?? [])], - env: agent.distribution.uvx.env ?? {}, - }, - }; - } - const manifest = await readAcpBinaryManifest(config, agent); - const target = getBinaryTarget(agent); - if (manifest) { - return { - supported: true as const, - distributionType: "binary" as const, - launch: { - command: manifest.command, - args: [], - env: {}, - }, - ...(target ? { binaryInstall: toBinaryInstallPreview(config, agent, target) } : {}), - }; - } - return { - supported: false as const, - distributionType: "binaryUnsupported" as const, - launch: null, - ...(target ? { binaryInstall: toBinaryInstallPreview(config, agent, target) } : {}), - }; -} function toAuthAccessStreamEvent( change: BootstrapCredentialChange | SessionCredentialChange, @@ -527,35 +201,14 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) => Effect.flatMap((raw) => Schema.decodeUnknownEffect(AcpRegistryIndex)(raw)), ); - const listAcpRegistry = Effect.all({ - registry: loadAcpRegistryIndex, - config: Effect.succeed(config), - }).pipe( - Effect.flatMap(({ registry, config }) => - Effect.tryPromise({ - try: async (): Promise => ({ - registryVersion: registry.version, - agents: ( - await Promise.all( - registry.agents.map(async (agent) => { - const resolved = await toAcpLaunchSpec(agent, config); - return { - agent, - supported: resolved.supported, - distributionType: resolved.distributionType, - launch: resolved.launch, - ...(resolved.binaryInstall ? { binaryInstall: resolved.binaryInstall } : {}), - }; - }), - ) - ).toSorted((left, right) => left.agent.name.localeCompare(right.agent.name)), + const listAcpRegistry = loadAcpRegistryIndex.pipe( + Effect.flatMap((registry) => listAcpRegistryAgents(registry)), + Effect.mapError( + (cause) => + new AcpRegistryClientError({ + detail: cause instanceof Error ? cause.message : String(cause), + cause, }), - catch: (cause) => - new AcpRegistryClientError({ - detail: cause instanceof Error ? cause.message : String(cause), - cause, - }), - }), ), ); @@ -563,51 +216,19 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) => readonly agentId: string; readonly installPath?: string | undefined; }) => - Effect.all({ - registry: loadAcpRegistryIndex, - config: Effect.succeed(config), - }).pipe( - Effect.flatMap(({ registry, config }) => - Effect.tryPromise({ - try: async (): Promise => { - const agent = registry.agents.find((entry) => entry.id === input.agentId); - if (!agent) { - return { - ok: false, - error: `No ACP registry agent found for '${input.agentId}'.`, - }; - } - const installed = await installAcpBinaryAgent({ - config, - agent, - installPath: input.installPath, - }); - return { - ok: true, - agent: { - agent, - supported: true, - distributionType: "binary", - binaryInstall: toBinaryInstallPreview(config, agent, installed), - launch: { - command: installed.command, - args: [], - env: {}, - }, - }, - }; - }, - catch: (cause): AcpRegistryInstallBinaryResult => ({ - ok: false, - error: cause instanceof Error ? cause.message : String(cause), - }), + loadAcpRegistryIndex.pipe( + Effect.flatMap((registry) => + installAcpRegistryBinaryAgent({ + registry, + agentId: input.agentId, + installPath: input.installPath, }), ), Effect.catch((cause: unknown) => Effect.succeed({ ok: false, error: cause instanceof Error ? cause.message : String(cause), - } satisfies AcpRegistryInstallBinaryResult), + }), ), );