import {
getRegistryAgent,
isAgentAvailable,
installFromRegistry,
buildAgentCommand,
} from "@/core/acp";
import { spawn } from "child_process";
async function installAndRunAgent(agentId: string, message: string) {
// 1. Check if agent exists in registry
const agent = await getRegistryAgent(agentId);
if (!agent) {
throw new Error(`Agent ${agentId} not found in registry`);
}
console.log(`Found: ${agent.name} v${agent.version}`);
// 2. Check if already installed
if (!(await isAgentAvailable(agentId))) {
console.log("Installing agent...");
const result = await installFromRegistry(agentId);
if (!result.success) {
throw new Error(`Installation failed: ${result.error}`);
}
console.log(`Installed via ${result.distributionType}`);
}
// 3. Build command
const command = await buildAgentCommand(agentId);
if (!command) {
throw new Error("Failed to build agent command");
}
// 4. Spawn agent process
console.log(`Running: ${command.command} ${command.args.join(" ")}`);
const proc = spawn(command.command, command.args, {
env: { ...process.env, ...command.env },
stdio: "pipe",
});
// 5. Send message via stdin (JSON-RPC)
proc.stdin.write(JSON.stringify({
jsonrpc: "2.0",
method: "session/prompt",
params: { message },
id: 1,
}));
// 6. Handle responses
proc.stdout.on("data", (data) => {
console.log("Response:", data.toString());
});
return proc;
}
// Usage
installAndRunAgent("opencode", "Fix the login bug");