Make file operations properly abortable with async operations

Replace synchronous file operations with async Promise-based operations
that listen to abort signals during execution:
- read, write, edit now use fs/promises async APIs
- Add abort event listeners that reject immediately on abort
- Check abort status before and after each async operation
- Clean up event listeners properly

This ensures pressing Esc during file operations shows red error state.
This commit is contained in:
Mario Zechner 2025-11-11 23:33:16 +01:00
parent e6b47799a4
commit 594edec31b
3 changed files with 230 additions and 55 deletions

View file

@ -1,8 +1,8 @@
import * as os from "node:os";
import type { AgentTool } from "@mariozechner/pi-ai";
import { Type } from "@sinclair/typebox";
import { mkdirSync, writeFileSync } from "fs";
import { dirname, resolve } from "path";
import { mkdir, writeFile } from "fs/promises";
import { dirname, resolve as resolvePath } from "path";
/**
* Expand ~ to home directory
@ -29,18 +29,64 @@ export const writeTool: AgentTool<typeof writeSchema> = {
"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.",
parameters: writeSchema,
execute: async (_toolCallId: string, { path, content }: { path: string; content: string }, signal?: AbortSignal) => {
// Check if already aborted
if (signal?.aborted) {
throw new Error("Operation aborted");
}
const absolutePath = resolve(expandPath(path));
const absolutePath = resolvePath(expandPath(path));
const dir = dirname(absolutePath);
// Create parent directories if needed
mkdirSync(dir, { recursive: true });
return new Promise<{ output: string; details: undefined }>((resolve, reject) => {
// Check if already aborted
if (signal?.aborted) {
reject(new Error("Operation aborted"));
return;
}
writeFileSync(absolutePath, content, "utf-8");
return { output: `Successfully wrote ${content.length} bytes to ${path}`, details: undefined };
let aborted = false;
// Set up abort handler
const onAbort = () => {
aborted = true;
reject(new Error("Operation aborted"));
};
if (signal) {
signal.addEventListener("abort", onAbort, { once: true });
}
// Perform the write operation
(async () => {
try {
// Create parent directories if needed
await mkdir(dir, { recursive: true });
// Check if aborted before writing
if (aborted) {
return;
}
// Write the file
await writeFile(absolutePath, content, "utf-8");
// Check if aborted after writing
if (aborted) {
return;
}
// Clean up abort handler
if (signal) {
signal.removeEventListener("abort", onAbort);
}
resolve({ output: `Successfully wrote ${content.length} bytes to ${path}`, details: undefined });
} catch (error: any) {
// Clean up abort handler
if (signal) {
signal.removeEventListener("abort", onAbort);
}
if (!aborted) {
reject(error);
}
}
})();
});
},
};