@@ -1,183 +0,0 @@
1-import { spawn } from "node:child_process";
2-import { existsSync, readFileSync, writeFileSync } from "node:fs";
3-import { Type, type Static, type TSchema, type Tool, type ToolCall } from "@earendil-works/pi-ai";
4-import { Value } from "typebox/value";
5-import { createTwoFilesPatch } from "diff";
6-import type { ToolName } from "./config.ts";
7-
8-export interface ToolContext {
9- signal: AbortSignal;
10- onOutput?: (chunk: string) => void;
11-}
12-
13-export interface ToolDetails {
14- truncated: boolean;
15- omittedChars: number;
16- totalChars: number;
17-}
18-
19-export interface ToolResult {
20- text: string;
21- isError: boolean;
22- details?: ToolDetails;
23-}
24-
25-const EDIT_PARAMS = Type.Object(
26- {
27- path: Type.String({ description: "File path" }),
28- oldText: Type.String({ description: "Exact text to replace; empty to create a file" }),
29- newText: Type.String({ description: "Replacement text" }),
30- },
31- { additionalProperties: false },
32-);
33-type EditArgs = Static<typeof EDIT_PARAMS>;
34-
35-const BASH_PARAMS = Type.Object(
36- { command: Type.String({ description: "Command to run" }) },
37- { additionalProperties: false },
38-);
39-type BashArgs = Static<typeof BASH_PARAMS>;
40-
41-const TOOL_SCHEMAS: Record<ToolName, Tool> = {
42- edit: {
43- name: "edit",
44- description:
45- "Edit a file by exact text replacement. oldText must occur exactly once. " +
46- "With empty oldText, create a new file (fails if it exists).",
47- parameters: EDIT_PARAMS,
48- },
49- bash: {
50- name: "bash",
51- description: "Run a bash command in the current working directory.",
52- parameters: BASH_PARAMS,
53- },
54-};
55-
56-export function toolSchemas(names: ToolName[]): Tool[] {
57- return names.map((name) => TOOL_SCHEMAS[name]);
58-}
59-
60-export function executeTool(name: ToolName, call: ToolCall, ctx: ToolContext): Promise<ToolResult> {
61- try {
62- if (name === "edit") return Promise.resolve(edit(parseArgs(EDIT_PARAMS, call.arguments), ctx.signal));
63- return bash(parseArgs(BASH_PARAMS, call.arguments), ctx);
64- } catch (error) {
65- return Promise.resolve({ text: (error as Error).message, isError: true });
66- }
67-}
68-
69-function parseArgs<T extends TSchema>(schema: T, value: unknown): Static<T> {
70- try {
71- return Value.Parse(schema, value);
72- } catch {
73- const first = [...Value.Errors(schema, value)][0];
74- throw new Error(first ? `${first.instancePath || "/"} ${first.message}` : "invalid arguments");
75- }
76-}
77-
78-function edit(args: EditArgs, signal: AbortSignal): ToolResult {
79- const { path, oldText, newText } = args;
80- const exists = existsSync(path);
81-
82- if (oldText === "") {
83- if (exists) return { text: `edit failed: ${path} already exists`, isError: true };
84- if (signal.aborted) return { text: "edit cancelled", isError: true };
85- writeFileSync(path, newText);
86- return { text: `created ${path}\n${unified(path, "", newText)}`, isError: false };
87- }
88-
89- if (!exists) return { text: `edit failed: ${path} does not exist`, isError: true };
90- const before = readFileSync(path, "utf8");
91- const count = before.split(oldText).length - 1;
92- if (count === 0) return { text: `edit failed: oldText not found in ${path}`, isError: true };
93- if (count > 1) return { text: `edit failed: oldText matches ${count} times in ${path}`, isError: true };
94-
95- const after = before.replace(oldText, newText);
96- if (signal.aborted) return { text: "edit cancelled", isError: true };
97- writeFileSync(path, after);
98- return { text: `edited ${path}\n${unified(path, before, after)}`, isError: false };
99-}
100-
101-function unified(path: string, before: string, after: string): string {
102- return createTwoFilesPatch(path, path, before, after, "", "", { context: 3 });
103-}
104-
105-const MAX_HEAD = 10_000;
106-const MAX_TAIL = 6_000;
107-const TRUNCATED = "\n\n... output truncated ...\n\n";
108-
109-function bash(args: BashArgs, ctx: ToolContext): Promise<ToolResult> {
110- return new Promise((resolve) => {
111- const child = spawn("bash", ["-c", args.command], {
112- cwd: process.cwd(),
113- detached: true,
114- stdio: ["ignore", "pipe", "pipe"],
115- });
116-
117- let head = "";
118- let tail = "";
119- let omitted = 0;
120- const append = (chunk: Buffer) => {
121- let text = chunk.toString();
122- ctx.onOutput?.(text);
123- if (head.length < MAX_HEAD) {
124- const take = Math.min(MAX_HEAD - head.length, text.length);
125- head += text.slice(0, take);
126- text = text.slice(take);
127- }
128- if (text === "") return;
129- tail += text;
130- if (tail.length > MAX_TAIL) {
131- omitted += tail.length - MAX_TAIL;
132- tail = tail.slice(tail.length - MAX_TAIL);
133- }
134- };
135- child.stdout?.on("data", append);
136- child.stderr?.on("data", append);
137-
138- let settled = false;
139- const finish = (code: number | null) => {
140- if (settled) return;
141- settled = true;
142- ctx.signal.removeEventListener("abort", onAbort);
143- clearTimeout(killTimer);
144- const exit = code ?? (ctx.signal.aborted ? "aborted" : "unknown");
145- const truncated = omitted > 0;
146- const body = truncated ? head + TRUNCATED + tail : head + tail;
147- const text = body + (body.endsWith("\n") || body === "" ? "" : "\n") + `exit code: ${exit}`;
148- resolve({
149- text,
150- isError: code !== 0,
151- details: truncated
152- ? { truncated: true, omittedChars: omitted, totalChars: head.length + tail.length + omitted }
153- : undefined,
154- });
155- };
156-
157- let killTimer: NodeJS.Timeout | undefined;
158- const onAbort = () => {
159- if (!child.pid) return;
160- try {
161- process.kill(-child.pid, "SIGTERM");
162- } catch {
163- /* already gone */
164- }
165- killTimer = setTimeout(() => {
166- try {
167- process.kill(-child.pid!, "SIGKILL");
168- } catch {
169- /* already gone */
170- }
171- }, 300);
172- };
173-
174- if (ctx.signal.aborted) onAbort();
175- else ctx.signal.addEventListener("abort", onAbort, { once: true });
176-
177- child.on("error", (error) => {
178- append(Buffer.from(`${head || tail ? "\n" : ""}bash failed: ${error.message}\n`));
179- finish(null);
180- });
181- child.on("close", (code) => finish(code));
182- });
183-}