Use fs watch instead of polling

This commit is contained in:
andrepimenta
2025-07-09 01:36:24 +01:00
parent bad8c9a0a8
commit d9baf71e4a

View File

@@ -108,36 +108,53 @@ async function requestPermission(tool_name: string, input: any): Promise<{approv
try { try {
fs.writeFileSync(requestFile, JSON.stringify(request, null, 2)); fs.writeFileSync(requestFile, JSON.stringify(request, null, 2));
// Poll for response file // Use fs.watch to wait for response file
const maxWaitTime = 30000; // 30 seconds timeout return new Promise<{approved: boolean, reason?: string}>((resolve) => {
const pollInterval = 100; // Check every 100ms const timeout = setTimeout(() => {
let waitTime = 0; watcher.close();
// Clean up request file on timeout
if (fs.existsSync(requestFile)) {
fs.unlinkSync(requestFile);
}
console.error(`Permission request ${requestId} timed out`);
resolve({ approved: false, reason: "Permission request timed out" });
}, 3600000); // 1 hour timeout
while (waitTime < maxWaitTime) { const watcher = fs.watch(PERMISSIONS_PATH, (eventType, filename) => {
if (fs.existsSync(responseFile)) { if (eventType === 'rename' && filename === path.basename(responseFile)) {
const responseContent = fs.readFileSync(responseFile, 'utf8'); // Check if file exists (rename event can be for creation or deletion)
const response = JSON.parse(responseContent); if (fs.existsSync(responseFile)) {
try {
const responseContent = fs.readFileSync(responseFile, 'utf8');
const response = JSON.parse(responseContent);
// Clean up response file // Clean up response file
fs.unlinkSync(responseFile); fs.unlinkSync(responseFile);
return { // Clear timeout and close watcher
approved: response.approved, clearTimeout(timeout);
reason: response.approved ? undefined : "User rejected the request" watcher.close();
};
}
await new Promise(resolve => setTimeout(resolve, pollInterval)); resolve({
waitTime += pollInterval; approved: response.approved,
} reason: response.approved ? undefined : "User rejected the request"
});
} catch (error) {
console.error(`Error reading response file: ${error}`);
// Continue watching in case of read error
}
}
}
});
// Timeout - clean up request file and deny // Handle watcher errors
if (fs.existsSync(requestFile)) { watcher.on('error', (error) => {
fs.unlinkSync(requestFile); console.error(`File watcher error: ${error}`);
} clearTimeout(timeout);
watcher.close();
console.error(`Permission request ${requestId} timed out`); resolve({ approved: false, reason: "File watcher error" });
return { approved: false, reason: "Permission request timed out" }; });
});
} catch (error) { } catch (error) {
console.error(`Error requesting permission: ${error}`); console.error(`Error requesting permission: ${error}`);