xonecas.io
64875
Mc

mini-coder / files

mini-coder / src / tools / bash.ts

2.6 KB
1import { spawn } from "node:child_process";
2import { Type, type Static } from "@earendil-works/pi-ai";
3import type { ToolContext, ToolResult } from "./common.ts";
4import { diffTrees, snapshot } from "./snapshot.ts";
5
6export const BASH_PARAMS = Type.Object(
7  { command: Type.String({ description: "Command to run" }) },
8  { additionalProperties: false },
9);
10export type BashArgs = Static<typeof BASH_PARAMS>;
11
12const MAX_HEAD = 10_000;
13const MAX_TAIL = 6_000;
14const TRUNCATED = "\n\n... output truncated ...\n\n";
15
16export function bash(args: BashArgs, ctx: ToolContext): Promise<ToolResult> {
17  return new Promise((resolve) => {
18    const startMs = Date.now();
19    const before = snapshot();
20    const child = spawn("bash", ["-c", args.command], {
21      cwd: process.cwd(),
22      detached: true,
23      stdio: ["ignore", "pipe", "pipe"],
24    });
25
26    let head = "";
27    let tail = "";
28    let truncated = false;
29    const append = (chunk: Buffer) => {
30      let text = chunk.toString();
31      ctx.onOutput?.(text);
32      if (head.length < MAX_HEAD) {
33        const take = Math.min(MAX_HEAD - head.length, text.length);
34        head += text.slice(0, take);
35        text = text.slice(take);
36      }
37      if (text === "") return;
38      tail += text;
39      if (tail.length > MAX_TAIL) {
40        truncated = true;
41        tail = tail.slice(tail.length - MAX_TAIL);
42      }
43    };
44    child.stdout?.on("data", append);
45    child.stderr?.on("data", append);
46
47    let settled = false;
48    const finish = (code: number | null) => {
49      if (settled) return;
50      settled = true;
51      ctx.signal.removeEventListener("abort", onAbort);
52      clearTimeout(killTimer);
53      const exit = code ?? (ctx.signal.aborted ? "aborted" : "unknown");
54      const body = truncated ? head + TRUNCATED + tail : head + tail;
55      const text = body + (body.endsWith("\n") || body === "" ? "" : "\n") + `exit code: ${exit}`;
56      const diffs = diffTrees(before, snapshot(startMs));
57      resolve({ text, isError: code !== 0, diffs });
58    };
59
60    let killTimer: NodeJS.Timeout | undefined;
61    const kill = (signal: NodeJS.Signals): void => {
62      try {
63        process.kill(-child.pid!, signal);
64      } catch {
65        /* already gone */
66      }
67    };
68    const onAbort = () => {
69      if (!child.pid) return;
70      kill("SIGTERM");
71      killTimer = setTimeout(() => kill("SIGKILL"), 300);
72    };
73
74    if (ctx.signal.aborted) onAbort();
75    else ctx.signal.addEventListener("abort", onAbort, { once: true });
76
77    child.on("error", (error) => {
78      append(Buffer.from(`${head || tail ? "\n" : ""}bash failed: ${error.message}\n`));
79      finish(null);
80    });
81    child.on("close", (code) => finish(code));
82  });
83}