|
| 1 | +import { spawn, type ChildProcess } from "node:child_process"; |
| 2 | +import * as readline from "node:readline"; |
| 3 | +import { Readable, Writable } from "node:stream"; |
| 4 | + |
| 5 | +import { |
| 6 | + ClientSideConnection, |
| 7 | + PROTOCOL_VERSION, |
| 8 | + ndJsonStream, |
| 9 | + type SessionNotification, |
| 10 | +} from "@agentclientprotocol/sdk"; |
| 11 | + |
| 12 | +import { ensureClawdbotCliOnPath } from "../infra/path-env.js"; |
| 13 | + |
| 14 | +export type AcpClientOptions = { |
| 15 | + cwd?: string; |
| 16 | + serverCommand?: string; |
| 17 | + serverArgs?: string[]; |
| 18 | + serverVerbose?: boolean; |
| 19 | + verbose?: boolean; |
| 20 | +}; |
| 21 | + |
| 22 | +export type AcpClientHandle = { |
| 23 | + client: ClientSideConnection; |
| 24 | + agent: ChildProcess; |
| 25 | + sessionId: string; |
| 26 | +}; |
| 27 | + |
| 28 | +function toArgs(value: string[] | string | undefined): string[] { |
| 29 | + if (!value) return []; |
| 30 | + return Array.isArray(value) ? value : [value]; |
| 31 | +} |
| 32 | + |
| 33 | +function buildServerArgs(opts: AcpClientOptions): string[] { |
| 34 | + const args = ["acp", ...toArgs(opts.serverArgs)]; |
| 35 | + if (opts.serverVerbose && !args.includes("--verbose") && !args.includes("-v")) { |
| 36 | + args.push("--verbose"); |
| 37 | + } |
| 38 | + return args; |
| 39 | +} |
| 40 | + |
| 41 | +function printSessionUpdate(notification: SessionNotification): void { |
| 42 | + const update = notification.update; |
| 43 | + if (!("sessionUpdate" in update)) return; |
| 44 | + |
| 45 | + switch (update.sessionUpdate) { |
| 46 | + case "agent_message_chunk": { |
| 47 | + if (update.content?.type === "text") { |
| 48 | + process.stdout.write(update.content.text); |
| 49 | + } |
| 50 | + return; |
| 51 | + } |
| 52 | + case "tool_call": { |
| 53 | + console.log(`\n[tool] ${update.title} (${update.status})`); |
| 54 | + return; |
| 55 | + } |
| 56 | + case "tool_call_update": { |
| 57 | + if (update.status) { |
| 58 | + console.log(`[tool update] ${update.toolCallId}: ${update.status}`); |
| 59 | + } |
| 60 | + return; |
| 61 | + } |
| 62 | + case "available_commands_update": { |
| 63 | + const names = update.availableCommands?.map((cmd) => `/${cmd.name}`).join(" "); |
| 64 | + if (names) console.log(`\n[commands] ${names}`); |
| 65 | + return; |
| 66 | + } |
| 67 | + default: |
| 68 | + return; |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +export async function createAcpClient(opts: AcpClientOptions = {}): Promise<AcpClientHandle> { |
| 73 | + const cwd = opts.cwd ?? process.cwd(); |
| 74 | + const verbose = Boolean(opts.verbose); |
| 75 | + const log = verbose ? (msg: string) => console.error(`[acp-client] ${msg}`) : () => {}; |
| 76 | + |
| 77 | + ensureClawdbotCliOnPath({ cwd }); |
| 78 | + const serverCommand = opts.serverCommand ?? "clawdbot"; |
| 79 | + const serverArgs = buildServerArgs(opts); |
| 80 | + |
| 81 | + log(`spawning: ${serverCommand} ${serverArgs.join(" ")}`); |
| 82 | + |
| 83 | + const agent = spawn(serverCommand, serverArgs, { |
| 84 | + stdio: ["pipe", "pipe", "inherit"], |
| 85 | + cwd, |
| 86 | + }); |
| 87 | + |
| 88 | + if (!agent.stdin || !agent.stdout) { |
| 89 | + throw new Error("Failed to create ACP stdio pipes"); |
| 90 | + } |
| 91 | + |
| 92 | + const input = Writable.toWeb(agent.stdin); |
| 93 | + const output = Readable.toWeb(agent.stdout) as ReadableStream<Uint8Array>; |
| 94 | + const stream = ndJsonStream(input, output); |
| 95 | + |
| 96 | + const client = new ClientSideConnection( |
| 97 | + () => ({ |
| 98 | + sessionUpdate: async (params: SessionNotification) => { |
| 99 | + printSessionUpdate(params); |
| 100 | + }, |
| 101 | + requestPermission: async (params) => { |
| 102 | + console.log("\n[permission requested]", params.toolCall?.title ?? "tool"); |
| 103 | + const allowOnce = params.options.find((option) => option.kind === "allow_once"); |
| 104 | + const fallback = params.options[0]; |
| 105 | + return { |
| 106 | + outcome: { |
| 107 | + outcome: "selected", |
| 108 | + optionId: allowOnce?.optionId ?? fallback?.optionId ?? "allow", |
| 109 | + }, |
| 110 | + }; |
| 111 | + }, |
| 112 | + }), |
| 113 | + stream, |
| 114 | + ); |
| 115 | + |
| 116 | + log("initializing"); |
| 117 | + await client.initialize({ |
| 118 | + protocolVersion: PROTOCOL_VERSION, |
| 119 | + clientCapabilities: { |
| 120 | + fs: { readTextFile: true, writeTextFile: true }, |
| 121 | + terminal: true, |
| 122 | + }, |
| 123 | + clientInfo: { name: "clawdbot-acp-client", version: "1.0.0" }, |
| 124 | + }); |
| 125 | + |
| 126 | + log("creating session"); |
| 127 | + const session = await client.newSession({ |
| 128 | + cwd, |
| 129 | + mcpServers: [], |
| 130 | + }); |
| 131 | + |
| 132 | + return { |
| 133 | + client, |
| 134 | + agent, |
| 135 | + sessionId: session.sessionId, |
| 136 | + }; |
| 137 | +} |
| 138 | + |
| 139 | +export async function runAcpClientInteractive(opts: AcpClientOptions = {}): Promise<void> { |
| 140 | + const { client, agent, sessionId } = await createAcpClient(opts); |
| 141 | + |
| 142 | + const rl = readline.createInterface({ |
| 143 | + input: process.stdin, |
| 144 | + output: process.stdout, |
| 145 | + }); |
| 146 | + |
| 147 | + console.log("Clawdbot ACP client"); |
| 148 | + console.log(`Session: ${sessionId}`); |
| 149 | + console.log('Type a prompt, or "exit" to quit.\n'); |
| 150 | + |
| 151 | + const prompt = () => { |
| 152 | + rl.question("> ", async (input) => { |
| 153 | + const text = input.trim(); |
| 154 | + if (!text) { |
| 155 | + prompt(); |
| 156 | + return; |
| 157 | + } |
| 158 | + if (text === "exit" || text === "quit") { |
| 159 | + agent.kill(); |
| 160 | + rl.close(); |
| 161 | + process.exit(0); |
| 162 | + } |
| 163 | + |
| 164 | + try { |
| 165 | + const response = await client.prompt({ |
| 166 | + sessionId, |
| 167 | + prompt: [{ type: "text", text }], |
| 168 | + }); |
| 169 | + console.log(`\n[${response.stopReason}]\n`); |
| 170 | + } catch (err) { |
| 171 | + console.error(`\n[error] ${String(err)}\n`); |
| 172 | + } |
| 173 | + |
| 174 | + prompt(); |
| 175 | + }); |
| 176 | + }; |
| 177 | + |
| 178 | + prompt(); |
| 179 | + |
| 180 | + agent.on("exit", (code) => { |
| 181 | + console.log(`\nAgent exited with code ${code ?? 0}`); |
| 182 | + rl.close(); |
| 183 | + process.exit(code ?? 0); |
| 184 | + }); |
| 185 | +} |
0 commit comments