rpc-example.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import { dirname, join } from "node:path";
  2. import * as readline from "node:readline";
  3. import { fileURLToPath } from "node:url";
  4. import { RpcClient } from "../src/modes/rpc/rpc-client.ts";
  5. const __dirname = dirname(fileURLToPath(import.meta.url));
  6. /**
  7. * Interactive example of using coding-agent via RpcClient.
  8. * Usage: npx tsx test/rpc-example.ts
  9. */
  10. async function main() {
  11. const client = new RpcClient({
  12. cliPath: join(__dirname, "../dist/cli.js"),
  13. provider: "anthropic",
  14. model: "claude-sonnet-4-20250514",
  15. args: ["--no-session"],
  16. });
  17. // Stream events to console
  18. client.onEvent((event) => {
  19. if (event.type === "message_update") {
  20. const { assistantMessageEvent } = event;
  21. if (assistantMessageEvent.type === "text_delta" || assistantMessageEvent.type === "thinking_delta") {
  22. process.stdout.write(assistantMessageEvent.delta);
  23. }
  24. }
  25. if (event.type === "tool_execution_start") {
  26. console.log(`\n[Tool: ${event.toolName}]`);
  27. }
  28. if (event.type === "tool_execution_end") {
  29. console.log(`[Result: ${JSON.stringify(event.result).slice(0, 200)}...]\n`);
  30. }
  31. });
  32. await client.start();
  33. const state = await client.getState();
  34. console.log(`Model: ${state.model?.provider}/${state.model?.id}`);
  35. console.log(`Thinking: ${state.thinkingLevel ?? "off"}\n`);
  36. // Handle user input
  37. const rl = readline.createInterface({
  38. input: process.stdin,
  39. output: process.stdout,
  40. terminal: true,
  41. });
  42. let isWaiting = false;
  43. const prompt = () => {
  44. if (!isWaiting) process.stdout.write("You: ");
  45. };
  46. rl.on("line", async (line) => {
  47. if (isWaiting) return;
  48. if (line.trim() === "exit") {
  49. await client.stop();
  50. process.exit(0);
  51. }
  52. isWaiting = true;
  53. await client.promptAndWait(line);
  54. console.log("\n");
  55. isWaiting = false;
  56. prompt();
  57. });
  58. rl.on("SIGINT", () => {
  59. if (isWaiting) {
  60. console.log("\n[Aborting...]");
  61. client.abort();
  62. } else {
  63. client.stop();
  64. process.exit(0);
  65. }
  66. });
  67. console.log("Interactive RPC example. Type 'exit' to quit.\n");
  68. prompt();
  69. }
  70. main().catch(console.error);