rpc-extension-ui.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. /**
  2. * RPC Extension UI Example (TUI)
  3. *
  4. * A lightweight TUI chat client that spawns the agent in RPC mode.
  5. * Demonstrates how to build a custom UI on top of the RPC protocol,
  6. * including handling extension UI requests (select, confirm, input, editor).
  7. *
  8. * Usage: npx tsx examples/rpc-extension-ui.ts
  9. *
  10. * Slash commands:
  11. * /select - demo select dialog
  12. * /confirm - demo confirm dialog
  13. * /input - demo input dialog
  14. * /editor - demo editor dialog
  15. */
  16. import { spawn } from "node:child_process";
  17. import { dirname, join } from "node:path";
  18. import * as readline from "node:readline";
  19. import { fileURLToPath } from "node:url";
  20. import { type Component, Container, Input, matchesKey, ProcessTerminal, SelectList, TUI } from "@earendil-works/pi-tui";
  21. const __dirname = dirname(fileURLToPath(import.meta.url));
  22. // ============================================================================
  23. // ANSI helpers
  24. // ============================================================================
  25. const GREEN = "\x1b[32m";
  26. const YELLOW = "\x1b[33m";
  27. const BLUE = "\x1b[34m";
  28. const MAGENTA = "\x1b[35m";
  29. const RED = "\x1b[31m";
  30. const DIM = "\x1b[2m";
  31. const BOLD = "\x1b[1m";
  32. const RESET = "\x1b[0m";
  33. // ============================================================================
  34. // Extension UI request type (subset of rpc-types.ts)
  35. // ============================================================================
  36. interface ExtensionUIRequest {
  37. type: "extension_ui_request";
  38. id: string;
  39. method: string;
  40. title?: string;
  41. options?: string[];
  42. message?: string;
  43. placeholder?: string;
  44. prefill?: string;
  45. notifyType?: "info" | "warning" | "error";
  46. statusKey?: string;
  47. statusText?: string;
  48. widgetKey?: string;
  49. widgetLines?: string[];
  50. text?: string;
  51. }
  52. // ============================================================================
  53. // Output log: accumulates styled lines, renders the tail that fits
  54. // ============================================================================
  55. class OutputLog implements Component {
  56. private lines: string[] = [];
  57. private maxLines = 1000;
  58. private visibleLines = 0;
  59. setVisibleLines(n: number): void {
  60. this.visibleLines = n;
  61. }
  62. append(line: string): void {
  63. this.lines.push(line);
  64. if (this.lines.length > this.maxLines) {
  65. this.lines = this.lines.slice(-this.maxLines);
  66. }
  67. }
  68. appendRaw(text: string): void {
  69. if (this.lines.length === 0) {
  70. this.lines.push(text);
  71. } else {
  72. this.lines[this.lines.length - 1] += text;
  73. }
  74. }
  75. invalidate(): void {}
  76. render(width: number): string[] {
  77. if (this.lines.length === 0) return [""];
  78. const n = this.visibleLines > 0 ? this.visibleLines : this.lines.length;
  79. return this.lines.slice(-n).map((l) => l.slice(0, width));
  80. }
  81. }
  82. // ============================================================================
  83. // Loading indicator: "Agent: Working." -> ".." -> "..." -> "."
  84. // ============================================================================
  85. class LoadingIndicator implements Component {
  86. private dots = 1;
  87. private intervalId: NodeJS.Timeout | null = null;
  88. private tui: TUI | null = null;
  89. start(tui: TUI): void {
  90. this.tui = tui;
  91. this.dots = 1;
  92. this.intervalId = setInterval(() => {
  93. this.dots = (this.dots % 3) + 1;
  94. this.tui?.requestRender();
  95. }, 400);
  96. }
  97. stop(): void {
  98. if (this.intervalId) {
  99. clearInterval(this.intervalId);
  100. this.intervalId = null;
  101. }
  102. }
  103. invalidate(): void {}
  104. render(_width: number): string[] {
  105. return [`${BLUE}${BOLD}Agent:${RESET} ${DIM}Working${".".repeat(this.dots)}${RESET}`];
  106. }
  107. }
  108. // ============================================================================
  109. // Prompt input: label + single-line input
  110. // ============================================================================
  111. class PromptInput implements Component {
  112. readonly input: Input;
  113. onCtrlD?: () => void;
  114. constructor() {
  115. this.input = new Input();
  116. }
  117. handleInput(data: string): void {
  118. if (matchesKey(data, "ctrl+d")) {
  119. this.onCtrlD?.();
  120. return;
  121. }
  122. this.input.handleInput(data);
  123. }
  124. invalidate(): void {
  125. this.input.invalidate();
  126. }
  127. render(width: number): string[] {
  128. return [`${GREEN}${BOLD}You:${RESET}`, ...this.input.render(width)];
  129. }
  130. }
  131. // ============================================================================
  132. // Dialog components: replace the prompt input during interactive requests
  133. // ============================================================================
  134. class SelectDialog implements Component {
  135. private list: SelectList;
  136. private title: string;
  137. onSelect?: (value: string) => void;
  138. onCancel?: () => void;
  139. constructor(title: string, options: string[]) {
  140. this.title = title;
  141. const items = options.map((o) => ({ value: o, label: o }));
  142. this.list = new SelectList(items, Math.min(items.length, 8), {
  143. selectedPrefix: (t) => `${MAGENTA}${t}${RESET}`,
  144. selectedText: (t) => `${MAGENTA}${t}${RESET}`,
  145. description: (t) => `${DIM}${t}${RESET}`,
  146. scrollInfo: (t) => `${DIM}${t}${RESET}`,
  147. noMatch: (t) => `${YELLOW}${t}${RESET}`,
  148. });
  149. this.list.onSelect = (item) => this.onSelect?.(item.value);
  150. this.list.onCancel = () => this.onCancel?.();
  151. }
  152. handleInput(data: string): void {
  153. this.list.handleInput(data);
  154. }
  155. invalidate(): void {
  156. this.list.invalidate();
  157. }
  158. render(width: number): string[] {
  159. return [
  160. `${MAGENTA}${BOLD}${this.title}${RESET}`,
  161. ...this.list.render(width),
  162. `${DIM}Up/Down, Enter to select, Esc to cancel${RESET}`,
  163. ];
  164. }
  165. }
  166. class InputDialog implements Component {
  167. private dialogInput: Input;
  168. private title: string;
  169. onCtrlD?: () => void;
  170. constructor(title: string, prefill?: string) {
  171. this.title = title;
  172. this.dialogInput = new Input();
  173. if (prefill) this.dialogInput.setValue(prefill);
  174. }
  175. set onSubmit(fn: ((value: string) => void) | undefined) {
  176. this.dialogInput.onSubmit = fn;
  177. }
  178. set onEscape(fn: (() => void) | undefined) {
  179. this.dialogInput.onEscape = fn;
  180. }
  181. get inputComponent(): Input {
  182. return this.dialogInput;
  183. }
  184. handleInput(data: string): void {
  185. if (matchesKey(data, "ctrl+d")) {
  186. this.onCtrlD?.();
  187. return;
  188. }
  189. this.dialogInput.handleInput(data);
  190. }
  191. invalidate(): void {
  192. this.dialogInput.invalidate();
  193. }
  194. render(width: number): string[] {
  195. return [
  196. `${MAGENTA}${BOLD}${this.title}${RESET}`,
  197. ...this.dialogInput.render(width),
  198. `${DIM}Enter to submit, Esc to cancel${RESET}`,
  199. ];
  200. }
  201. }
  202. // ============================================================================
  203. // Main
  204. // ============================================================================
  205. async function main() {
  206. const extensionPath = join(__dirname, "extensions/rpc-demo.ts");
  207. const cliPath = join(__dirname, "../dist/cli.js");
  208. const agent = spawn(
  209. "node",
  210. [cliPath, "--mode", "rpc", "--no-session", "--no-extension", "--extension", extensionPath],
  211. { stdio: ["pipe", "pipe", "pipe"] },
  212. );
  213. let stderr = "";
  214. agent.stderr?.on("data", (data: Buffer) => {
  215. stderr += data.toString();
  216. });
  217. await new Promise((resolve) => setTimeout(resolve, 500));
  218. if (agent.exitCode !== null) {
  219. console.error(`Agent exited immediately. Stderr:\n${stderr}`);
  220. process.exit(1);
  221. }
  222. // -- TUI setup --
  223. const terminal = new ProcessTerminal();
  224. const tui = new TUI(terminal);
  225. const outputLog = new OutputLog();
  226. const loadingIndicator = new LoadingIndicator();
  227. const promptInput = new PromptInput();
  228. const root = new Container();
  229. root.addChild(outputLog);
  230. root.addChild(promptInput);
  231. tui.addChild(root);
  232. tui.setFocus(promptInput.input);
  233. // -- Agent communication --
  234. function send(obj: Record<string, unknown>): void {
  235. agent.stdin!.write(`${JSON.stringify(obj)}\n`);
  236. }
  237. let isStreaming = false;
  238. let hasTextOutput = false;
  239. function exit(): void {
  240. tui.stop();
  241. agent.kill("SIGTERM");
  242. process.exit(0);
  243. }
  244. // -- Bottom area management --
  245. // The bottom of the screen is either the prompt input or a dialog.
  246. // These helpers swap between them.
  247. let activeDialog: Component | null = null;
  248. function setBottomComponent(component: Component): void {
  249. root.clear();
  250. root.addChild(outputLog);
  251. if (isStreaming) root.addChild(loadingIndicator);
  252. root.addChild(component);
  253. tui.setFocus(component);
  254. tui.requestRender();
  255. }
  256. function showPrompt(): void {
  257. activeDialog = null;
  258. setBottomComponent(promptInput);
  259. tui.setFocus(promptInput.input);
  260. }
  261. function showDialog(dialog: Component): void {
  262. activeDialog = dialog;
  263. setBottomComponent(dialog);
  264. }
  265. function showLoading(): void {
  266. if (!isStreaming) {
  267. isStreaming = true;
  268. hasTextOutput = false;
  269. root.clear();
  270. root.addChild(outputLog);
  271. root.addChild(loadingIndicator);
  272. root.addChild(activeDialog ?? promptInput);
  273. if (!activeDialog) tui.setFocus(promptInput.input);
  274. loadingIndicator.start(tui);
  275. tui.requestRender();
  276. }
  277. }
  278. function hideLoading(): void {
  279. loadingIndicator.stop();
  280. root.clear();
  281. root.addChild(outputLog);
  282. root.addChild(activeDialog ?? promptInput);
  283. if (!activeDialog) tui.setFocus(promptInput.input);
  284. tui.requestRender();
  285. }
  286. // -- Extension UI dialog handling --
  287. function showSelectDialog(title: string, options: string[], onDone: (value: string | undefined) => void): void {
  288. const dialog = new SelectDialog(title, options);
  289. dialog.onSelect = (value) => {
  290. showPrompt();
  291. onDone(value);
  292. };
  293. dialog.onCancel = () => {
  294. showPrompt();
  295. onDone(undefined);
  296. };
  297. showDialog(dialog);
  298. }
  299. function showInputDialog(title: string, prefill?: string, onDone?: (value: string | undefined) => void): void {
  300. const dialog = new InputDialog(title, prefill);
  301. dialog.onSubmit = (value) => {
  302. showPrompt();
  303. onDone?.(value.trim() || undefined);
  304. };
  305. dialog.onEscape = () => {
  306. showPrompt();
  307. onDone?.(undefined);
  308. };
  309. dialog.onCtrlD = exit;
  310. showDialog(dialog);
  311. tui.setFocus(dialog.inputComponent);
  312. }
  313. function handleExtensionUI(req: ExtensionUIRequest): void {
  314. const { id, method } = req;
  315. switch (method) {
  316. // Dialog methods: replace prompt with interactive component
  317. case "select": {
  318. showSelectDialog(req.title ?? "Select", req.options ?? [], (value) => {
  319. if (value !== undefined) {
  320. send({ type: "extension_ui_response", id, value });
  321. } else {
  322. send({ type: "extension_ui_response", id, cancelled: true });
  323. }
  324. });
  325. break;
  326. }
  327. case "confirm": {
  328. const title = req.message ? `${req.title}: ${req.message}` : (req.title ?? "Confirm");
  329. showSelectDialog(title, ["Yes", "No"], (value) => {
  330. send({ type: "extension_ui_response", id, confirmed: value === "Yes" });
  331. });
  332. break;
  333. }
  334. case "input": {
  335. const title = req.placeholder ? `${req.title} (${req.placeholder})` : (req.title ?? "Input");
  336. showInputDialog(title, undefined, (value) => {
  337. if (value !== undefined) {
  338. send({ type: "extension_ui_response", id, value });
  339. } else {
  340. send({ type: "extension_ui_response", id, cancelled: true });
  341. }
  342. });
  343. break;
  344. }
  345. case "editor": {
  346. const prefill = req.prefill?.replace(/\n/g, " ");
  347. showInputDialog(req.title ?? "Editor", prefill, (value) => {
  348. if (value !== undefined) {
  349. send({ type: "extension_ui_response", id, value });
  350. } else {
  351. send({ type: "extension_ui_response", id, cancelled: true });
  352. }
  353. });
  354. break;
  355. }
  356. // Fire-and-forget methods: display as notification
  357. case "notify": {
  358. const notifyType = (req.notifyType as string) ?? "info";
  359. const color = notifyType === "error" ? RED : notifyType === "warning" ? YELLOW : MAGENTA;
  360. outputLog.append(`${color}${BOLD}Notification:${RESET} ${req.message}`);
  361. tui.requestRender();
  362. break;
  363. }
  364. case "setStatus":
  365. outputLog.append(
  366. `${MAGENTA}${BOLD}Notification:${RESET} ${DIM}[status: ${req.statusKey}]${RESET} ${req.statusText ?? "(cleared)"}`,
  367. );
  368. tui.requestRender();
  369. break;
  370. case "setWidget": {
  371. const lines = req.widgetLines;
  372. if (lines && lines.length > 0) {
  373. outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} ${DIM}[widget: ${req.widgetKey}]${RESET}`);
  374. for (const wl of lines) {
  375. outputLog.append(` ${DIM}${wl}${RESET}`);
  376. }
  377. tui.requestRender();
  378. }
  379. break;
  380. }
  381. case "set_editor_text":
  382. promptInput.input.setValue((req.text as string) ?? "");
  383. tui.requestRender();
  384. break;
  385. }
  386. }
  387. // -- Slash commands (local, not sent to agent) --
  388. function handleSlashCommand(cmd: string): boolean {
  389. switch (cmd) {
  390. case "/select":
  391. showSelectDialog("Pick a color", ["Red", "Green", "Blue", "Yellow"], (value) => {
  392. if (value) {
  393. outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} You picked: ${value}`);
  394. } else {
  395. outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} Selection cancelled`);
  396. }
  397. tui.requestRender();
  398. });
  399. return true;
  400. case "/confirm":
  401. showSelectDialog("Are you sure?", ["Yes", "No"], (value) => {
  402. const confirmed = value === "Yes";
  403. outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} Confirmed: ${confirmed}`);
  404. tui.requestRender();
  405. });
  406. return true;
  407. case "/input":
  408. showInputDialog("Enter your name", undefined, (value) => {
  409. if (value) {
  410. outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} You entered: ${value}`);
  411. } else {
  412. outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} Input cancelled`);
  413. }
  414. tui.requestRender();
  415. });
  416. return true;
  417. case "/editor":
  418. showInputDialog("Edit text", "Hello, world!", (value) => {
  419. if (value) {
  420. outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} Submitted: ${value}`);
  421. } else {
  422. outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} Editor cancelled`);
  423. }
  424. tui.requestRender();
  425. });
  426. return true;
  427. default:
  428. return false;
  429. }
  430. }
  431. // -- Process agent stdout --
  432. const stdoutRl = readline.createInterface({ input: agent.stdout!, terminal: false });
  433. stdoutRl.on("line", (line) => {
  434. let data: Record<string, unknown>;
  435. try {
  436. data = JSON.parse(line);
  437. } catch {
  438. return;
  439. }
  440. if (data.type === "response" && !data.success) {
  441. outputLog.append(`${RED}[error]${RESET} ${data.command}: ${data.error}`);
  442. tui.requestRender();
  443. return;
  444. }
  445. if (data.type === "agent_start") {
  446. showLoading();
  447. return;
  448. }
  449. if (data.type === "extension_ui_request") {
  450. handleExtensionUI(data as unknown as ExtensionUIRequest);
  451. return;
  452. }
  453. if (data.type === "message_update") {
  454. const evt = data.assistantMessageEvent as Record<string, unknown> | undefined;
  455. if (evt?.type === "text_delta") {
  456. if (!hasTextOutput) {
  457. hasTextOutput = true;
  458. outputLog.append("");
  459. outputLog.append(`${BLUE}${BOLD}Agent:${RESET}`);
  460. }
  461. const delta = evt.delta as string;
  462. const parts = delta.split("\n");
  463. for (let i = 0; i < parts.length; i++) {
  464. if (i > 0) outputLog.append("");
  465. if (parts[i]) outputLog.appendRaw(parts[i]);
  466. }
  467. tui.requestRender();
  468. }
  469. return;
  470. }
  471. if (data.type === "tool_execution_start") {
  472. outputLog.append(`${DIM}[tool: ${data.toolName}]${RESET}`);
  473. tui.requestRender();
  474. return;
  475. }
  476. if (data.type === "tool_execution_end") {
  477. const result = JSON.stringify(data.result).slice(0, 120);
  478. outputLog.append(`${DIM}[result: ${result}...]${RESET}`);
  479. tui.requestRender();
  480. return;
  481. }
  482. if (data.type === "agent_end") {
  483. isStreaming = false;
  484. hideLoading();
  485. outputLog.append("");
  486. tui.requestRender();
  487. return;
  488. }
  489. });
  490. // -- User input --
  491. promptInput.input.onSubmit = (value) => {
  492. const trimmed = value.trim();
  493. if (!trimmed) return;
  494. promptInput.input.setValue("");
  495. if (handleSlashCommand(trimmed)) {
  496. outputLog.append(`${GREEN}${BOLD}You:${RESET} ${trimmed}`);
  497. tui.requestRender();
  498. return;
  499. }
  500. outputLog.append(`${GREEN}${BOLD}You:${RESET} ${trimmed}`);
  501. send({ type: "prompt", message: trimmed });
  502. tui.requestRender();
  503. };
  504. promptInput.onCtrlD = exit;
  505. promptInput.input.onEscape = () => {
  506. if (isStreaming) {
  507. send({ type: "abort" });
  508. outputLog.append(`${YELLOW}[aborted]${RESET}`);
  509. tui.requestRender();
  510. } else {
  511. exit();
  512. }
  513. };
  514. // -- Agent exit --
  515. agent.on("exit", (code) => {
  516. tui.stop();
  517. if (stderr) console.error(stderr);
  518. console.log(`Agent exited with code ${code}`);
  519. process.exit(code ?? 0);
  520. });
  521. // -- Start --
  522. outputLog.append(`${BOLD}RPC Chat${RESET}`);
  523. outputLog.append(`${DIM}Type a message and press Enter. Esc to abort or exit. Ctrl+D to quit.${RESET}`);
  524. outputLog.append(`${DIM}Slash commands: /select /confirm /input /editor${RESET}`);
  525. outputLog.append("");
  526. tui.start();
  527. }
  528. main().catch((err) => {
  529. console.error(err);
  530. process.exit(1);
  531. });