rpc-client.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. /**
  2. * RPC Client for programmatic access to the coding agent.
  3. *
  4. * Spawns the agent in RPC mode and provides a typed API for all operations.
  5. */
  6. import { type ChildProcess, spawn } from "node:child_process";
  7. import type { AgentEvent, AgentMessage, ThinkingLevel } from "@earendil-works/pi-agent-core";
  8. import type { ImageContent } from "@earendil-works/pi-ai";
  9. import type { SessionStats } from "../../core/agent-session.ts";
  10. import type { BashResult } from "../../core/bash-executor.ts";
  11. import type { CompactionResult } from "../../core/compaction/index.ts";
  12. import { attachJsonlLineReader, serializeJsonLine } from "./jsonl.ts";
  13. import type { RpcCommand, RpcResponse, RpcSessionState, RpcSlashCommand } from "./rpc-types.ts";
  14. // ============================================================================
  15. // Types
  16. // ============================================================================
  17. /** Distributive Omit that works with union types */
  18. type DistributiveOmit<T, K extends keyof T> = T extends unknown ? Omit<T, K> : never;
  19. /** RpcCommand without the id field (for internal send) */
  20. type RpcCommandBody = DistributiveOmit<RpcCommand, "id">;
  21. export interface RpcClientOptions {
  22. /** Path to the CLI entry point (default: searches for dist/cli.js) */
  23. cliPath?: string;
  24. /** Working directory for the agent */
  25. cwd?: string;
  26. /** Environment variables */
  27. env?: Record<string, string>;
  28. /** Provider to use */
  29. provider?: string;
  30. /** Model ID to use */
  31. model?: string;
  32. /** Additional CLI arguments */
  33. args?: string[];
  34. }
  35. export interface ModelInfo {
  36. provider: string;
  37. id: string;
  38. contextWindow: number;
  39. reasoning: boolean;
  40. }
  41. export type RpcEventListener = (event: AgentEvent) => void;
  42. // ============================================================================
  43. // RPC Client
  44. // ============================================================================
  45. export class RpcClient {
  46. private process: ChildProcess | null = null;
  47. private stopReadingStdout: (() => void) | null = null;
  48. private eventListeners: RpcEventListener[] = [];
  49. private pendingRequests: Map<string, { resolve: (response: RpcResponse) => void; reject: (error: Error) => void }> =
  50. new Map();
  51. private requestId = 0;
  52. private stderr = "";
  53. private exitError: Error | null = null;
  54. private options: RpcClientOptions;
  55. constructor(options: RpcClientOptions = {}) {
  56. this.options = options;
  57. }
  58. /**
  59. * Start the RPC agent process.
  60. */
  61. async start(): Promise<void> {
  62. if (this.process) {
  63. throw new Error("Client already started");
  64. }
  65. this.exitError = null;
  66. const cliPath = this.options.cliPath ?? "dist/cli.js";
  67. const args = ["--mode", "rpc"];
  68. if (this.options.provider) {
  69. args.push("--provider", this.options.provider);
  70. }
  71. if (this.options.model) {
  72. args.push("--model", this.options.model);
  73. }
  74. if (this.options.args) {
  75. args.push(...this.options.args);
  76. }
  77. const childProcess = spawn("node", [cliPath, ...args], {
  78. cwd: this.options.cwd,
  79. env: { ...process.env, ...this.options.env },
  80. stdio: ["pipe", "pipe", "pipe"],
  81. });
  82. this.process = childProcess;
  83. // Collect stderr for debugging
  84. childProcess.stderr?.on("data", (data) => {
  85. this.stderr += data.toString();
  86. process.stderr.write(data);
  87. });
  88. childProcess.once("exit", (code, signal) => {
  89. if (this.process !== childProcess) return;
  90. const error = this.createProcessExitError(code, signal);
  91. this.exitError = error;
  92. this.rejectPendingRequests(error);
  93. });
  94. childProcess.once("error", (error) => {
  95. if (this.process !== childProcess) return;
  96. const processError = new Error(`Agent process error: ${error.message}. Stderr: ${this.stderr}`);
  97. this.exitError = processError;
  98. this.rejectPendingRequests(processError);
  99. });
  100. childProcess.stdin?.on("error", (error) => {
  101. if (this.process !== childProcess) return;
  102. const stdinError =
  103. this.exitError ?? new Error(`Agent process stdin error: ${error.message}. Stderr: ${this.stderr}`);
  104. this.exitError = stdinError;
  105. this.rejectPendingRequests(stdinError);
  106. });
  107. // Set up strict JSONL reader for stdout.
  108. this.stopReadingStdout = attachJsonlLineReader(childProcess.stdout!, (line) => {
  109. this.handleLine(line);
  110. });
  111. // Wait a moment for process to initialize
  112. await new Promise((resolve) => setTimeout(resolve, 100));
  113. if (this.process.exitCode !== null) {
  114. const error = this.exitError ?? this.createProcessExitError(this.process.exitCode, this.process.signalCode);
  115. this.exitError = error;
  116. throw error;
  117. }
  118. }
  119. /**
  120. * Stop the RPC agent process.
  121. */
  122. async stop(): Promise<void> {
  123. if (!this.process) return;
  124. this.stopReadingStdout?.();
  125. this.stopReadingStdout = null;
  126. this.process.kill("SIGTERM");
  127. // Wait for process to exit
  128. await new Promise<void>((resolve) => {
  129. const timeout = setTimeout(() => {
  130. this.process?.kill("SIGKILL");
  131. resolve();
  132. }, 1000);
  133. this.process?.on("exit", () => {
  134. clearTimeout(timeout);
  135. resolve();
  136. });
  137. });
  138. this.process = null;
  139. this.pendingRequests.clear();
  140. }
  141. /**
  142. * Subscribe to agent events.
  143. */
  144. onEvent(listener: RpcEventListener): () => void {
  145. this.eventListeners.push(listener);
  146. return () => {
  147. const index = this.eventListeners.indexOf(listener);
  148. if (index !== -1) {
  149. this.eventListeners.splice(index, 1);
  150. }
  151. };
  152. }
  153. /**
  154. * Get collected stderr output (useful for debugging).
  155. */
  156. getStderr(): string {
  157. return this.stderr;
  158. }
  159. // =========================================================================
  160. // Command Methods
  161. // =========================================================================
  162. /**
  163. * Send a prompt to the agent.
  164. * Returns immediately after sending; use onEvent() to receive streaming events.
  165. * Use waitForIdle() to wait for completion.
  166. */
  167. async prompt(message: string, images?: ImageContent[]): Promise<void> {
  168. await this.send({ type: "prompt", message, images });
  169. }
  170. /**
  171. * Queue a steering message to interrupt the agent mid-run.
  172. */
  173. async steer(message: string, images?: ImageContent[]): Promise<void> {
  174. await this.send({ type: "steer", message, images });
  175. }
  176. /**
  177. * Queue a follow-up message to be processed after the agent finishes.
  178. */
  179. async followUp(message: string, images?: ImageContent[]): Promise<void> {
  180. await this.send({ type: "follow_up", message, images });
  181. }
  182. /**
  183. * Abort current operation.
  184. */
  185. async abort(): Promise<void> {
  186. await this.send({ type: "abort" });
  187. }
  188. /**
  189. * Start a new session, optionally with parent tracking.
  190. * @param parentSession - Optional parent session path for lineage tracking
  191. * @returns Object with `cancelled: true` if an extension cancelled the new session
  192. */
  193. async newSession(parentSession?: string): Promise<{ cancelled: boolean }> {
  194. const response = await this.send({ type: "new_session", parentSession });
  195. return this.getData(response);
  196. }
  197. /**
  198. * Get current session state.
  199. */
  200. async getState(): Promise<RpcSessionState> {
  201. const response = await this.send({ type: "get_state" });
  202. return this.getData(response);
  203. }
  204. /**
  205. * Set model by provider and ID.
  206. */
  207. async setModel(provider: string, modelId: string): Promise<{ provider: string; id: string }> {
  208. const response = await this.send({ type: "set_model", provider, modelId });
  209. return this.getData(response);
  210. }
  211. /**
  212. * Cycle to next model.
  213. */
  214. async cycleModel(): Promise<{
  215. model: { provider: string; id: string };
  216. thinkingLevel: ThinkingLevel;
  217. isScoped: boolean;
  218. } | null> {
  219. const response = await this.send({ type: "cycle_model" });
  220. return this.getData(response);
  221. }
  222. /**
  223. * Get list of available models.
  224. */
  225. async getAvailableModels(): Promise<ModelInfo[]> {
  226. const response = await this.send({ type: "get_available_models" });
  227. return this.getData<{ models: ModelInfo[] }>(response).models;
  228. }
  229. /**
  230. * Set thinking level.
  231. */
  232. async setThinkingLevel(level: ThinkingLevel): Promise<void> {
  233. await this.send({ type: "set_thinking_level", level });
  234. }
  235. /**
  236. * Cycle thinking level.
  237. */
  238. async cycleThinkingLevel(): Promise<{ level: ThinkingLevel } | null> {
  239. const response = await this.send({ type: "cycle_thinking_level" });
  240. return this.getData(response);
  241. }
  242. /**
  243. * Set steering mode.
  244. */
  245. async setSteeringMode(mode: "all" | "one-at-a-time"): Promise<void> {
  246. await this.send({ type: "set_steering_mode", mode });
  247. }
  248. /**
  249. * Set follow-up mode.
  250. */
  251. async setFollowUpMode(mode: "all" | "one-at-a-time"): Promise<void> {
  252. await this.send({ type: "set_follow_up_mode", mode });
  253. }
  254. /**
  255. * Compact session context.
  256. */
  257. async compact(customInstructions?: string): Promise<CompactionResult> {
  258. const response = await this.send({ type: "compact", customInstructions });
  259. return this.getData(response);
  260. }
  261. /**
  262. * Set auto-compaction enabled/disabled.
  263. */
  264. async setAutoCompaction(enabled: boolean): Promise<void> {
  265. await this.send({ type: "set_auto_compaction", enabled });
  266. }
  267. /**
  268. * Set auto-retry enabled/disabled.
  269. */
  270. async setAutoRetry(enabled: boolean): Promise<void> {
  271. await this.send({ type: "set_auto_retry", enabled });
  272. }
  273. /**
  274. * Abort in-progress retry.
  275. */
  276. async abortRetry(): Promise<void> {
  277. await this.send({ type: "abort_retry" });
  278. }
  279. /**
  280. * Execute a bash command.
  281. */
  282. async bash(command: string): Promise<BashResult> {
  283. const response = await this.send({ type: "bash", command });
  284. return this.getData(response);
  285. }
  286. /**
  287. * Abort running bash command.
  288. */
  289. async abortBash(): Promise<void> {
  290. await this.send({ type: "abort_bash" });
  291. }
  292. /**
  293. * Get session statistics.
  294. */
  295. async getSessionStats(): Promise<SessionStats> {
  296. const response = await this.send({ type: "get_session_stats" });
  297. return this.getData(response);
  298. }
  299. /**
  300. * Export session to HTML.
  301. */
  302. async exportHtml(outputPath?: string): Promise<{ path: string }> {
  303. const response = await this.send({ type: "export_html", outputPath });
  304. return this.getData(response);
  305. }
  306. /**
  307. * Switch to a different session file.
  308. * @returns Object with `cancelled: true` if an extension cancelled the switch
  309. */
  310. async switchSession(sessionPath: string): Promise<{ cancelled: boolean }> {
  311. const response = await this.send({ type: "switch_session", sessionPath });
  312. return this.getData(response);
  313. }
  314. /**
  315. * Fork from a specific message.
  316. * @returns Object with `text` (the message text) and `cancelled` (if extension cancelled)
  317. */
  318. async fork(entryId: string): Promise<{ text: string; cancelled: boolean }> {
  319. const response = await this.send({ type: "fork", entryId });
  320. return this.getData(response);
  321. }
  322. /**
  323. * Clone the current active branch into a new session.
  324. * @returns Object with `cancelled: true` if an extension cancelled the clone
  325. */
  326. async clone(): Promise<{ cancelled: boolean }> {
  327. const response = await this.send({ type: "clone" });
  328. return this.getData(response);
  329. }
  330. /**
  331. * Get messages available for forking.
  332. */
  333. async getForkMessages(): Promise<Array<{ entryId: string; text: string }>> {
  334. const response = await this.send({ type: "get_fork_messages" });
  335. return this.getData<{ messages: Array<{ entryId: string; text: string }> }>(response).messages;
  336. }
  337. /**
  338. * Get text of last assistant message.
  339. */
  340. async getLastAssistantText(): Promise<string | null> {
  341. const response = await this.send({ type: "get_last_assistant_text" });
  342. return this.getData<{ text: string | null }>(response).text;
  343. }
  344. /**
  345. * Set the session display name.
  346. */
  347. async setSessionName(name: string): Promise<void> {
  348. await this.send({ type: "set_session_name", name });
  349. }
  350. /**
  351. * Get all messages in the session.
  352. */
  353. async getMessages(): Promise<AgentMessage[]> {
  354. const response = await this.send({ type: "get_messages" });
  355. return this.getData<{ messages: AgentMessage[] }>(response).messages;
  356. }
  357. /**
  358. * Get available commands (extension commands, prompt templates, skills).
  359. */
  360. async getCommands(): Promise<RpcSlashCommand[]> {
  361. const response = await this.send({ type: "get_commands" });
  362. return this.getData<{ commands: RpcSlashCommand[] }>(response).commands;
  363. }
  364. // =========================================================================
  365. // Helpers
  366. // =========================================================================
  367. /**
  368. * Wait for agent to become idle (no streaming).
  369. * Resolves when agent_end event is received.
  370. */
  371. waitForIdle(timeout = 60000): Promise<void> {
  372. return new Promise((resolve, reject) => {
  373. const timer = setTimeout(() => {
  374. unsubscribe();
  375. reject(new Error(`Timeout waiting for agent to become idle. Stderr: ${this.stderr}`));
  376. }, timeout);
  377. const unsubscribe = this.onEvent((event) => {
  378. if (event.type === "agent_end") {
  379. clearTimeout(timer);
  380. unsubscribe();
  381. resolve();
  382. }
  383. });
  384. });
  385. }
  386. /**
  387. * Collect events until agent becomes idle.
  388. */
  389. collectEvents(timeout = 60000): Promise<AgentEvent[]> {
  390. return new Promise((resolve, reject) => {
  391. const events: AgentEvent[] = [];
  392. const timer = setTimeout(() => {
  393. unsubscribe();
  394. reject(new Error(`Timeout collecting events. Stderr: ${this.stderr}`));
  395. }, timeout);
  396. const unsubscribe = this.onEvent((event) => {
  397. events.push(event);
  398. if (event.type === "agent_end") {
  399. clearTimeout(timer);
  400. unsubscribe();
  401. resolve(events);
  402. }
  403. });
  404. });
  405. }
  406. /**
  407. * Send prompt and wait for completion, returning all events.
  408. */
  409. async promptAndWait(message: string, images?: ImageContent[], timeout = 60000): Promise<AgentEvent[]> {
  410. const eventsPromise = this.collectEvents(timeout);
  411. await this.prompt(message, images);
  412. return eventsPromise;
  413. }
  414. // =========================================================================
  415. // Internal
  416. // =========================================================================
  417. private handleLine(line: string): void {
  418. try {
  419. const data = JSON.parse(line);
  420. // Check if it's a response to a pending request
  421. if (data.type === "response" && data.id && this.pendingRequests.has(data.id)) {
  422. const pending = this.pendingRequests.get(data.id)!;
  423. this.pendingRequests.delete(data.id);
  424. pending.resolve(data as RpcResponse);
  425. return;
  426. }
  427. // Otherwise it's an event
  428. for (const listener of this.eventListeners) {
  429. listener(data as AgentEvent);
  430. }
  431. } catch {
  432. // Ignore non-JSON lines
  433. }
  434. }
  435. private createProcessExitError(code: number | null, signal: NodeJS.Signals | null): Error {
  436. return new Error(`Agent process exited (code=${code} signal=${signal}). Stderr: ${this.stderr}`);
  437. }
  438. private rejectPendingRequests(error: Error): void {
  439. for (const pending of this.pendingRequests.values()) {
  440. pending.reject(error);
  441. }
  442. this.pendingRequests.clear();
  443. }
  444. private async send(command: RpcCommandBody): Promise<RpcResponse> {
  445. const childProcess = this.process;
  446. const stdin = childProcess?.stdin;
  447. if (!childProcess || !stdin) {
  448. throw new Error("Client not started");
  449. }
  450. if (this.exitError) {
  451. throw this.exitError;
  452. }
  453. if (childProcess.exitCode !== null) {
  454. const error = this.createProcessExitError(childProcess.exitCode, childProcess.signalCode);
  455. this.exitError = error;
  456. throw error;
  457. }
  458. if (stdin.destroyed || !stdin.writable) {
  459. const error = new Error(`Agent process stdin is not writable. Stderr: ${this.stderr}`);
  460. this.exitError = error;
  461. throw error;
  462. }
  463. const id = `req_${++this.requestId}`;
  464. const fullCommand = { ...command, id } as RpcCommand;
  465. return new Promise((resolve, reject) => {
  466. const timeout = setTimeout(() => {
  467. this.pendingRequests.delete(id);
  468. reject(new Error(`Timeout waiting for response to ${command.type}. Stderr: ${this.stderr}`));
  469. }, 30000);
  470. this.pendingRequests.set(id, {
  471. resolve: (response) => {
  472. clearTimeout(timeout);
  473. resolve(response);
  474. },
  475. reject: (error) => {
  476. clearTimeout(timeout);
  477. reject(error);
  478. },
  479. });
  480. try {
  481. stdin.write(serializeJsonLine(fullCommand));
  482. } catch (error: unknown) {
  483. const writeError = error instanceof Error ? error : new Error(String(error));
  484. const pending = this.pendingRequests.get(id);
  485. this.pendingRequests.delete(id);
  486. pending?.reject(writeError);
  487. }
  488. });
  489. }
  490. private getData<T>(response: RpcResponse): T {
  491. if (!response.success) {
  492. const errorResponse = response as Extract<RpcResponse, { success: false }>;
  493. throw new Error(errorResponse.error);
  494. }
  495. // Type assertion: we trust response.data matches T based on the command sent.
  496. // This is safe because each public method specifies the correct T for its command.
  497. const successResponse = response as Extract<RpcResponse, { success: true; data: unknown }>;
  498. return successResponse.data as T;
  499. }
  500. }