ssh.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. /**
  2. * SSH Remote Execution Example
  3. *
  4. * Demonstrates delegating tool operations to a remote machine via SSH.
  5. * When --ssh is provided, read/write/edit/bash run on the remote.
  6. *
  7. * Usage:
  8. * pi -e ./ssh.ts --ssh user@host
  9. * pi -e ./ssh.ts --ssh user@host:/remote/path
  10. *
  11. * Requirements:
  12. * - SSH key-based auth (no password prompts)
  13. * - bash on remote
  14. */
  15. import { spawn } from "node:child_process";
  16. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  17. import {
  18. type BashOperations,
  19. createBashTool,
  20. createEditTool,
  21. createReadTool,
  22. createWriteTool,
  23. type EditOperations,
  24. type ReadOperations,
  25. type WriteOperations,
  26. } from "@earendil-works/pi-coding-agent";
  27. function sshExec(remote: string, command: string): Promise<Buffer> {
  28. return new Promise((resolve, reject) => {
  29. const child = spawn("ssh", [remote, command], { stdio: ["ignore", "pipe", "pipe"] });
  30. const chunks: Buffer[] = [];
  31. const errChunks: Buffer[] = [];
  32. child.stdout.on("data", (data) => chunks.push(data));
  33. child.stderr.on("data", (data) => errChunks.push(data));
  34. child.on("error", reject);
  35. child.on("close", (code) => {
  36. if (code !== 0) {
  37. reject(new Error(`SSH failed (${code}): ${Buffer.concat(errChunks).toString()}`));
  38. } else {
  39. resolve(Buffer.concat(chunks));
  40. }
  41. });
  42. });
  43. }
  44. function createRemoteReadOps(remote: string, remoteCwd: string, localCwd: string): ReadOperations {
  45. const toRemote = (p: string) => p.replace(localCwd, remoteCwd);
  46. return {
  47. readFile: (p) => sshExec(remote, `cat ${JSON.stringify(toRemote(p))}`),
  48. access: (p) => sshExec(remote, `test -r ${JSON.stringify(toRemote(p))}`).then(() => {}),
  49. detectImageMimeType: async (p) => {
  50. try {
  51. const r = await sshExec(remote, `file --mime-type -b ${JSON.stringify(toRemote(p))}`);
  52. const m = r.toString().trim();
  53. return ["image/jpeg", "image/png", "image/gif", "image/webp"].includes(m) ? m : null;
  54. } catch {
  55. return null;
  56. }
  57. },
  58. };
  59. }
  60. function createRemoteWriteOps(remote: string, remoteCwd: string, localCwd: string): WriteOperations {
  61. const toRemote = (p: string) => p.replace(localCwd, remoteCwd);
  62. return {
  63. writeFile: async (p, content) => {
  64. const b64 = Buffer.from(content).toString("base64");
  65. await sshExec(remote, `echo ${JSON.stringify(b64)} | base64 -d > ${JSON.stringify(toRemote(p))}`);
  66. },
  67. mkdir: (dir) => sshExec(remote, `mkdir -p ${JSON.stringify(toRemote(dir))}`).then(() => {}),
  68. };
  69. }
  70. function createRemoteEditOps(remote: string, remoteCwd: string, localCwd: string): EditOperations {
  71. const r = createRemoteReadOps(remote, remoteCwd, localCwd);
  72. const w = createRemoteWriteOps(remote, remoteCwd, localCwd);
  73. return { readFile: r.readFile, access: r.access, writeFile: w.writeFile };
  74. }
  75. function createRemoteBashOps(remote: string, remoteCwd: string, localCwd: string): BashOperations {
  76. const toRemote = (p: string) => p.replace(localCwd, remoteCwd);
  77. return {
  78. exec: (command, cwd, { onData, signal, timeout }) =>
  79. new Promise((resolve, reject) => {
  80. const cmd = `cd ${JSON.stringify(toRemote(cwd))} && ${command}`;
  81. const child = spawn("ssh", [remote, cmd], { stdio: ["ignore", "pipe", "pipe"] });
  82. let timedOut = false;
  83. const timer = timeout
  84. ? setTimeout(() => {
  85. timedOut = true;
  86. child.kill();
  87. }, timeout * 1000)
  88. : undefined;
  89. child.stdout.on("data", onData);
  90. child.stderr.on("data", onData);
  91. child.on("error", (e) => {
  92. if (timer) clearTimeout(timer);
  93. reject(e);
  94. });
  95. const onAbort = () => child.kill();
  96. signal?.addEventListener("abort", onAbort, { once: true });
  97. child.on("close", (code) => {
  98. if (timer) clearTimeout(timer);
  99. signal?.removeEventListener("abort", onAbort);
  100. if (signal?.aborted) reject(new Error("aborted"));
  101. else if (timedOut) reject(new Error(`timeout:${timeout}`));
  102. else resolve({ exitCode: code });
  103. });
  104. }),
  105. };
  106. }
  107. export default function (pi: ExtensionAPI) {
  108. pi.registerFlag("ssh", { description: "SSH remote: user@host or user@host:/path", type: "string" });
  109. const localCwd = process.cwd();
  110. const localRead = createReadTool(localCwd);
  111. const localWrite = createWriteTool(localCwd);
  112. const localEdit = createEditTool(localCwd);
  113. const localBash = createBashTool(localCwd);
  114. // Resolved lazily on session_start (CLI flags not available during factory)
  115. let resolvedSsh: { remote: string; remoteCwd: string } | null = null;
  116. const getSsh = () => resolvedSsh;
  117. pi.registerTool({
  118. ...localRead,
  119. async execute(id, params, signal, onUpdate, _ctx) {
  120. const ssh = getSsh();
  121. if (ssh) {
  122. const tool = createReadTool(localCwd, {
  123. operations: createRemoteReadOps(ssh.remote, ssh.remoteCwd, localCwd),
  124. });
  125. return tool.execute(id, params, signal, onUpdate);
  126. }
  127. return localRead.execute(id, params, signal, onUpdate);
  128. },
  129. });
  130. pi.registerTool({
  131. ...localWrite,
  132. async execute(id, params, signal, onUpdate, _ctx) {
  133. const ssh = getSsh();
  134. if (ssh) {
  135. const tool = createWriteTool(localCwd, {
  136. operations: createRemoteWriteOps(ssh.remote, ssh.remoteCwd, localCwd),
  137. });
  138. return tool.execute(id, params, signal, onUpdate);
  139. }
  140. return localWrite.execute(id, params, signal, onUpdate);
  141. },
  142. });
  143. pi.registerTool({
  144. ...localEdit,
  145. async execute(id, params, signal, onUpdate, _ctx) {
  146. const ssh = getSsh();
  147. if (ssh) {
  148. const tool = createEditTool(localCwd, {
  149. operations: createRemoteEditOps(ssh.remote, ssh.remoteCwd, localCwd),
  150. });
  151. return tool.execute(id, params, signal, onUpdate);
  152. }
  153. return localEdit.execute(id, params, signal, onUpdate);
  154. },
  155. });
  156. pi.registerTool({
  157. ...localBash,
  158. async execute(id, params, signal, onUpdate, _ctx) {
  159. const ssh = getSsh();
  160. if (ssh) {
  161. const tool = createBashTool(localCwd, {
  162. operations: createRemoteBashOps(ssh.remote, ssh.remoteCwd, localCwd),
  163. });
  164. return tool.execute(id, params, signal, onUpdate);
  165. }
  166. return localBash.execute(id, params, signal, onUpdate);
  167. },
  168. });
  169. pi.on("session_start", async (_event, ctx) => {
  170. // Resolve SSH config now that CLI flags are available
  171. const arg = pi.getFlag("ssh") as string | undefined;
  172. if (arg) {
  173. if (arg.includes(":")) {
  174. const [remote, path] = arg.split(":");
  175. resolvedSsh = { remote, remoteCwd: path };
  176. } else {
  177. // No path given, evaluate pwd on remote
  178. const remote = arg;
  179. const pwd = (await sshExec(remote, "pwd")).toString().trim();
  180. resolvedSsh = { remote, remoteCwd: pwd };
  181. }
  182. ctx.ui.setStatus("ssh", ctx.ui.theme.fg("accent", `SSH: ${resolvedSsh.remote}:${resolvedSsh.remoteCwd}`));
  183. ctx.ui.notify(`SSH mode: ${resolvedSsh.remote}:${resolvedSsh.remoteCwd}`, "info");
  184. }
  185. });
  186. // Handle user ! commands via SSH
  187. pi.on("user_bash", (_event) => {
  188. const ssh = getSsh();
  189. if (!ssh) return; // No SSH, use local execution
  190. return { operations: createRemoteBashOps(ssh.remote, ssh.remoteCwd, localCwd) };
  191. });
  192. // Replace local cwd with remote cwd in system prompt
  193. pi.on("before_agent_start", async (event) => {
  194. const ssh = getSsh();
  195. if (ssh) {
  196. const modified = event.systemPrompt.replace(
  197. `Current working directory: ${localCwd}`,
  198. `Current working directory: ${ssh.remoteCwd} (via SSH: ${ssh.remote})`,
  199. );
  200. return { systemPrompt: modified };
  201. }
  202. });
  203. }