index.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. /**
  2. * Gondolin Tool Routing Example
  3. *
  4. * Runs pi's built-in tools inside a local Gondolin micro-VM. The host working
  5. * directory is mounted at /workspace in the guest. File changes under
  6. * /workspace write through to the host; other guest filesystem changes are
  7. * isolated to the VM.
  8. *
  9. * Setup:
  10. * cd packages/coding-agent/examples/extensions/gondolin
  11. * npm install --ignore-scripts
  12. *
  13. * Usage:
  14. * cd /path/to/project
  15. * pi -e /path/to/pi/packages/coding-agent/examples/extensions/gondolin
  16. *
  17. * Requirements:
  18. * - Node.js >= 23.6.0 for @earendil-works/gondolin
  19. * - QEMU installed (for example, `brew install qemu` on macOS)
  20. */
  21. import path from "node:path";
  22. import { RealFSProvider, VM } from "@earendil-works/gondolin";
  23. import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
  24. import {
  25. type BashOperations,
  26. createBashTool,
  27. createEditTool,
  28. createFindTool,
  29. createGrepTool,
  30. createLsTool,
  31. createReadTool,
  32. createWriteTool,
  33. DEFAULT_MAX_BYTES,
  34. type EditOperations,
  35. type FindOperations,
  36. formatSize,
  37. type GrepToolDetails,
  38. type GrepToolInput,
  39. type LsOperations,
  40. type ReadOperations,
  41. truncateHead,
  42. truncateLine,
  43. type WriteOperations,
  44. } from "@earendil-works/pi-coding-agent";
  45. const GUEST_WORKSPACE = "/workspace";
  46. const DEFAULT_GREP_LIMIT = 100;
  47. type TextToolResult<TDetails> = {
  48. content: Array<{ type: "text"; text: string }>;
  49. details: TDetails | undefined;
  50. };
  51. function stripAtPrefix(value: string): string {
  52. return value.startsWith("@") ? value.slice(1) : value;
  53. }
  54. function toPosix(value: string): string {
  55. return value.split(path.sep).join(path.posix.sep);
  56. }
  57. function isInsideHostPath(root: string, value: string): boolean {
  58. const relativePath = path.relative(root, value);
  59. return relativePath === "" || (!relativePath.startsWith("..") && !path.isAbsolute(relativePath));
  60. }
  61. function hostPathToGuest(localCwd: string, hostPath: string): string {
  62. const relativePath = path.relative(localCwd, hostPath);
  63. if (!isInsideHostPath(localCwd, hostPath)) return toPosix(hostPath);
  64. return relativePath ? path.posix.join(GUEST_WORKSPACE, toPosix(relativePath)) : GUEST_WORKSPACE;
  65. }
  66. function toGuestPath(localCwd: string, inputPath: string): string {
  67. const trimmed = stripAtPrefix(inputPath.trim());
  68. if (!trimmed) return GUEST_WORKSPACE;
  69. if (path.isAbsolute(trimmed)) {
  70. if (isInsideHostPath(localCwd, trimmed)) return hostPathToGuest(localCwd, trimmed);
  71. return path.posix.resolve("/", toPosix(trimmed));
  72. }
  73. return path.posix.resolve(GUEST_WORKSPACE, toPosix(trimmed));
  74. }
  75. function createGondolinReadOps(vm: VM, localCwd: string): ReadOperations {
  76. return {
  77. readFile: async (filePath) => vm.fs.readFile(toGuestPath(localCwd, filePath)),
  78. access: async (filePath) => {
  79. await vm.fs.access(toGuestPath(localCwd, filePath));
  80. },
  81. detectImageMimeType: async (filePath) => {
  82. const ext = path.posix.extname(toGuestPath(localCwd, filePath)).toLowerCase();
  83. if (ext === ".png") return "image/png";
  84. if (ext === ".jpg" || ext === ".jpeg") return "image/jpeg";
  85. if (ext === ".gif") return "image/gif";
  86. if (ext === ".webp") return "image/webp";
  87. return null;
  88. },
  89. };
  90. }
  91. function createGondolinWriteOps(vm: VM, localCwd: string): WriteOperations {
  92. return {
  93. writeFile: async (filePath, content) => {
  94. await vm.fs.writeFile(toGuestPath(localCwd, filePath), content, { encoding: "utf8" });
  95. },
  96. mkdir: async (dirPath) => {
  97. await vm.fs.mkdir(toGuestPath(localCwd, dirPath), { recursive: true });
  98. },
  99. };
  100. }
  101. function createGondolinEditOps(vm: VM, localCwd: string): EditOperations {
  102. const readOps = createGondolinReadOps(vm, localCwd);
  103. const writeOps = createGondolinWriteOps(vm, localCwd);
  104. return {
  105. readFile: readOps.readFile,
  106. writeFile: writeOps.writeFile,
  107. access: readOps.access,
  108. };
  109. }
  110. function createGondolinLsOps(vm: VM, localCwd: string): LsOperations {
  111. return {
  112. exists: async (filePath) => {
  113. try {
  114. await vm.fs.access(toGuestPath(localCwd, filePath));
  115. return true;
  116. } catch {
  117. return false;
  118. }
  119. },
  120. stat: async (filePath) => vm.fs.stat(toGuestPath(localCwd, filePath)),
  121. readdir: async (dirPath) => vm.fs.listDir(toGuestPath(localCwd, dirPath)),
  122. };
  123. }
  124. async function walkGuestFiles(
  125. vm: VM,
  126. root: string,
  127. visit: (guestPath: string, relativePath: string) => Promise<boolean>,
  128. signal?: AbortSignal,
  129. ): Promise<boolean> {
  130. if (signal?.aborted) throw new Error("Operation aborted");
  131. const stat = await vm.fs.stat(root, { signal });
  132. if (!stat.isDirectory()) return visit(root, path.posix.basename(root));
  133. const walkDirectory = async (dir: string, relativeDir: string): Promise<boolean> => {
  134. if (signal?.aborted) throw new Error("Operation aborted");
  135. const entries = await vm.fs.listDir(dir, { signal });
  136. for (const entry of entries) {
  137. if (entry === ".git" || entry === "node_modules") continue;
  138. const guestPath = path.posix.join(dir, entry);
  139. const relativePath = relativeDir ? path.posix.join(relativeDir, entry) : entry;
  140. let entryStat: Awaited<ReturnType<VM["fs"]["stat"]>>;
  141. try {
  142. entryStat = await vm.fs.stat(guestPath, { signal });
  143. } catch {
  144. continue;
  145. }
  146. if (entryStat.isDirectory()) {
  147. if (!(await walkDirectory(guestPath, relativePath))) return false;
  148. } else if (!(await visit(guestPath, relativePath))) {
  149. return false;
  150. }
  151. }
  152. return true;
  153. };
  154. return walkDirectory(root, "");
  155. }
  156. function matchesToolGlob(relativePath: string, pattern: string): boolean {
  157. const normalizedPattern = toPosix(pattern);
  158. if (normalizedPattern.includes("/")) {
  159. return (
  160. path.posix.matchesGlob(relativePath, normalizedPattern) ||
  161. path.posix.matchesGlob(relativePath, `**/${normalizedPattern}`)
  162. );
  163. }
  164. return path.posix.matchesGlob(path.posix.basename(relativePath), normalizedPattern);
  165. }
  166. function createGondolinFindOps(vm: VM, localCwd: string): FindOperations {
  167. return {
  168. exists: async (filePath) => {
  169. try {
  170. await vm.fs.access(toGuestPath(localCwd, filePath));
  171. return true;
  172. } catch {
  173. return false;
  174. }
  175. },
  176. glob: async (pattern, cwd, options) => {
  177. const root = toGuestPath(localCwd, cwd);
  178. const results: string[] = [];
  179. await walkGuestFiles(vm, root, async (guestPath, relativePath) => {
  180. if (results.length >= options.limit) return false;
  181. if (matchesToolGlob(relativePath, pattern)) results.push(guestPath);
  182. return results.length < options.limit;
  183. });
  184. return results;
  185. },
  186. };
  187. }
  188. function createLineMatcher(pattern: string, literal: boolean | undefined, ignoreCase: boolean | undefined) {
  189. if (literal) {
  190. const needle = ignoreCase ? pattern.toLowerCase() : pattern;
  191. return (line: string) => (ignoreCase ? line.toLowerCase() : line).includes(needle);
  192. }
  193. const regex = new RegExp(pattern, ignoreCase ? "i" : undefined);
  194. return (line: string) => regex.test(line);
  195. }
  196. function appendGrepBlock(params: {
  197. outputLines: string[];
  198. lines: string[];
  199. relativePath: string;
  200. lineIndex: number;
  201. contextLines: number;
  202. }): boolean {
  203. let linesTruncated = false;
  204. const start = params.contextLines > 0 ? Math.max(0, params.lineIndex - params.contextLines) : params.lineIndex;
  205. const end =
  206. params.contextLines > 0
  207. ? Math.min(params.lines.length - 1, params.lineIndex + params.contextLines)
  208. : params.lineIndex;
  209. for (let index = start; index <= end; index++) {
  210. const rawLine = params.lines[index] ?? "";
  211. const { text, wasTruncated } = truncateLine(rawLine.replace(/\r/g, ""));
  212. if (wasTruncated) linesTruncated = true;
  213. const separator = index === params.lineIndex ? ":" : "-";
  214. params.outputLines.push(`${params.relativePath}${separator}${index + 1}${separator} ${text}`);
  215. }
  216. return linesTruncated;
  217. }
  218. async function executeGondolinGrep(
  219. vm: VM,
  220. localCwd: string,
  221. params: GrepToolInput,
  222. signal?: AbortSignal,
  223. ): Promise<TextToolResult<GrepToolDetails>> {
  224. const root = toGuestPath(localCwd, params.path ?? ".");
  225. const rootStat = await vm.fs.stat(root, { signal });
  226. const rootIsDirectory = rootStat.isDirectory();
  227. const matcher = createLineMatcher(params.pattern, params.literal, params.ignoreCase);
  228. const contextLines = params.context && params.context > 0 ? params.context : 0;
  229. const effectiveLimit = Math.max(1, params.limit ?? DEFAULT_GREP_LIMIT);
  230. const outputLines: string[] = [];
  231. const details: GrepToolDetails = {};
  232. let matchCount = 0;
  233. let matchLimitReached = false;
  234. let linesTruncated = false;
  235. await walkGuestFiles(
  236. vm,
  237. root,
  238. async (guestPath, relativePath) => {
  239. if (matchCount >= effectiveLimit) return false;
  240. if (params.glob && !matchesToolGlob(relativePath, params.glob)) return true;
  241. let content: string;
  242. try {
  243. content = await vm.fs.readFile(guestPath, { encoding: "utf8", signal });
  244. } catch {
  245. return true;
  246. }
  247. const lines = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
  248. const displayPath = rootIsDirectory ? relativePath : path.posix.basename(guestPath);
  249. for (let index = 0; index < lines.length; index++) {
  250. if (signal?.aborted) throw new Error("Operation aborted");
  251. if (!matcher(lines[index] ?? "")) continue;
  252. matchCount++;
  253. if (appendGrepBlock({ outputLines, lines, relativePath: displayPath, lineIndex: index, contextLines })) {
  254. linesTruncated = true;
  255. }
  256. if (matchCount >= effectiveLimit) {
  257. matchLimitReached = true;
  258. return false;
  259. }
  260. }
  261. return true;
  262. },
  263. signal,
  264. );
  265. if (matchCount === 0) return { content: [{ type: "text", text: "No matches found" }], details: undefined };
  266. const rawOutput = outputLines.join("\n");
  267. const truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER });
  268. const notices: string[] = [];
  269. let output = truncation.content;
  270. if (matchLimitReached) {
  271. details.matchLimitReached = effectiveLimit;
  272. notices.push(`${effectiveLimit} matches limit reached`);
  273. }
  274. if (linesTruncated) {
  275. details.linesTruncated = true;
  276. notices.push("long lines truncated");
  277. }
  278. if (truncation.truncated) {
  279. details.truncation = truncation;
  280. notices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);
  281. }
  282. if (notices.length > 0) output += `\n\n[${notices.join(". ")}]`;
  283. return {
  284. content: [{ type: "text", text: output }],
  285. details: Object.keys(details).length > 0 ? details : undefined,
  286. };
  287. }
  288. function sanitizeEnv(env: NodeJS.ProcessEnv | undefined): Record<string, string> | undefined {
  289. if (!env) return undefined;
  290. const result: Record<string, string> = {};
  291. for (const [key, value] of Object.entries(env)) {
  292. if (typeof value === "string") result[key] = value;
  293. }
  294. return result;
  295. }
  296. function createGondolinBashOps(vm: VM, localCwd: string, shellPath: string): BashOperations {
  297. return {
  298. exec: async (command, cwd, { onData, signal, timeout, env }) => {
  299. if (signal?.aborted) throw new Error("aborted");
  300. const guestCwd = toGuestPath(localCwd, cwd);
  301. const controller = new AbortController();
  302. const onAbort = () => controller.abort();
  303. signal?.addEventListener("abort", onAbort, { once: true });
  304. let timedOut = false;
  305. const timer =
  306. timeout && timeout > 0
  307. ? setTimeout(() => {
  308. timedOut = true;
  309. controller.abort();
  310. }, timeout * 1000)
  311. : undefined;
  312. try {
  313. const proc = vm.exec([shellPath, "-lc", command], {
  314. cwd: guestCwd,
  315. env: sanitizeEnv(env),
  316. signal: controller.signal,
  317. stdout: "pipe",
  318. stderr: "pipe",
  319. });
  320. for await (const chunk of proc.output()) onData(chunk.data);
  321. const result = await proc;
  322. return { exitCode: result.exitCode };
  323. } catch (error) {
  324. if (signal?.aborted) throw new Error("aborted");
  325. if (timedOut) throw new Error(`timeout:${timeout}`);
  326. throw error;
  327. } finally {
  328. if (timer) clearTimeout(timer);
  329. signal?.removeEventListener("abort", onAbort);
  330. }
  331. },
  332. };
  333. }
  334. export default function (pi: ExtensionAPI) {
  335. const localCwd = process.cwd();
  336. const localRead = createReadTool(localCwd);
  337. const localWrite = createWriteTool(localCwd);
  338. const localEdit = createEditTool(localCwd);
  339. const localBash = createBashTool(localCwd);
  340. const localGrep = createGrepTool(localCwd);
  341. const localFind = createFindTool(localCwd);
  342. const localLs = createLsTool(localCwd);
  343. let vm: VM | undefined;
  344. let vmStarting: Promise<VM> | undefined;
  345. let shellPath = "/bin/sh";
  346. async function startVm(ctx?: ExtensionContext): Promise<VM> {
  347. ctx?.ui.setStatus("gondolin", ctx.ui.theme.fg("accent", `Gondolin: starting ${GUEST_WORKSPACE}`));
  348. const created = await VM.create({
  349. sessionLabel: `pi ${path.basename(localCwd)}`,
  350. vfs: {
  351. mounts: {
  352. [GUEST_WORKSPACE]: new RealFSProvider(localCwd),
  353. },
  354. },
  355. });
  356. const bashProbe = await created.exec(["/bin/sh", "-lc", "command -v bash || true"]);
  357. shellPath = bashProbe.stdout.trim() || "/bin/sh";
  358. vm = created;
  359. ctx?.ui.setStatus(
  360. "gondolin",
  361. ctx.ui.theme.fg("accent", `Gondolin: ${created.id.slice(0, 8)} (${GUEST_WORKSPACE})`),
  362. );
  363. ctx?.ui.notify(`Gondolin VM ready. ${localCwd} is mounted at ${GUEST_WORKSPACE}.`, "info");
  364. return created;
  365. }
  366. async function ensureVm(ctx?: ExtensionContext): Promise<VM> {
  367. if (vm) return vm;
  368. if (!vmStarting) {
  369. vmStarting = startVm(ctx).finally(() => {
  370. vmStarting = undefined;
  371. });
  372. }
  373. return vmStarting;
  374. }
  375. pi.on("session_start", async (_event, ctx) => {
  376. await ensureVm(ctx);
  377. });
  378. pi.on("session_shutdown", async (_event, ctx) => {
  379. const activeVm = vm;
  380. vm = undefined;
  381. vmStarting = undefined;
  382. if (!activeVm) return;
  383. ctx.ui.setStatus("gondolin", ctx.ui.theme.fg("muted", "Gondolin: stopping"));
  384. try {
  385. await activeVm.close();
  386. } finally {
  387. ctx.ui.setStatus("gondolin", undefined);
  388. }
  389. });
  390. pi.registerCommand("gondolin", {
  391. description: "Show Gondolin VM status",
  392. handler: async (_args, ctx) => {
  393. const activeVm = await ensureVm(ctx);
  394. ctx.ui.notify(
  395. [
  396. `Gondolin VM: ${activeVm.id}`,
  397. `Host workspace: ${localCwd}`,
  398. `Guest workspace: ${GUEST_WORKSPACE}`,
  399. `Shell: ${shellPath}`,
  400. ].join("\n"),
  401. "info",
  402. );
  403. },
  404. });
  405. pi.registerTool({
  406. ...localRead,
  407. async execute(id, params, signal, onUpdate, ctx) {
  408. const activeVm = await ensureVm(ctx);
  409. const tool = createReadTool(GUEST_WORKSPACE, {
  410. operations: createGondolinReadOps(activeVm, localCwd),
  411. });
  412. return tool.execute(id, params, signal, onUpdate);
  413. },
  414. });
  415. pi.registerTool({
  416. ...localWrite,
  417. async execute(id, params, signal, onUpdate, ctx) {
  418. const activeVm = await ensureVm(ctx);
  419. const tool = createWriteTool(GUEST_WORKSPACE, {
  420. operations: createGondolinWriteOps(activeVm, localCwd),
  421. });
  422. return tool.execute(id, params, signal, onUpdate);
  423. },
  424. });
  425. pi.registerTool({
  426. ...localEdit,
  427. async execute(id, params, signal, onUpdate, ctx) {
  428. const activeVm = await ensureVm(ctx);
  429. const tool = createEditTool(GUEST_WORKSPACE, {
  430. operations: createGondolinEditOps(activeVm, localCwd),
  431. });
  432. return tool.execute(id, params, signal, onUpdate);
  433. },
  434. });
  435. pi.registerTool({
  436. ...localBash,
  437. async execute(id, params, signal, onUpdate, ctx) {
  438. const activeVm = await ensureVm(ctx);
  439. const tool = createBashTool(GUEST_WORKSPACE, {
  440. operations: createGondolinBashOps(activeVm, localCwd, shellPath),
  441. });
  442. return tool.execute(id, params, signal, onUpdate);
  443. },
  444. });
  445. pi.registerTool({
  446. ...localLs,
  447. async execute(id, params, signal, onUpdate, ctx) {
  448. const activeVm = await ensureVm(ctx);
  449. const tool = createLsTool(GUEST_WORKSPACE, {
  450. operations: createGondolinLsOps(activeVm, localCwd),
  451. });
  452. return tool.execute(id, params, signal, onUpdate);
  453. },
  454. });
  455. pi.registerTool({
  456. ...localFind,
  457. async execute(id, params, signal, onUpdate, ctx) {
  458. const activeVm = await ensureVm(ctx);
  459. const tool = createFindTool(GUEST_WORKSPACE, {
  460. operations: createGondolinFindOps(activeVm, localCwd),
  461. });
  462. return tool.execute(id, params, signal, onUpdate);
  463. },
  464. });
  465. pi.registerTool({
  466. ...localGrep,
  467. async execute(_id, params, signal, _onUpdate, ctx) {
  468. const activeVm = await ensureVm(ctx);
  469. return executeGondolinGrep(activeVm, localCwd, params, signal);
  470. },
  471. });
  472. pi.on("user_bash", async (_event, ctx) => {
  473. const activeVm = await ensureVm(ctx);
  474. return { operations: createGondolinBashOps(activeVm, localCwd, shellPath) };
  475. });
  476. pi.on("before_agent_start", async (event, ctx) => {
  477. await ensureVm(ctx);
  478. const localLine = `Current working directory: ${localCwd}`;
  479. const guestLine = `Current working directory: ${GUEST_WORKSPACE} (Gondolin VM; host workspace mounted from ${localCwd})`;
  480. const systemPrompt = event.systemPrompt.includes(localLine)
  481. ? event.systemPrompt.replace(localLine, guestLine)
  482. : `${event.systemPrompt}\n\n${guestLine}`;
  483. return { systemPrompt };
  484. });
  485. }