-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathkill-bash.ts
More file actions
105 lines (91 loc) · 2.77 KB
/
kill-bash.ts
File metadata and controls
105 lines (91 loc) · 2.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/**
* KillBash tool - Kill a background bash process
*/
import type { Tool, ToolContext, JSONSchema } from '../types/tools';
import { backgroundProcesses } from './bash';
export interface KillBashInput {
shellId: string;
}
export interface KillBashOutput {
success: boolean;
message: string;
}
const parameters: JSONSchema = {
type: 'object',
properties: {
shellId: {
type: 'string',
description: 'The shell ID returned by Bash tool when run_in_background is true',
},
},
required: ['shellId'],
};
export class KillBashTool implements Tool<KillBashInput, KillBashOutput> {
name = 'KillBash';
description =
'Kill a background bash process started with run_in_background. Sends SIGTERM first, then SIGKILL after 5 seconds if still running.';
parameters = parameters;
handler = async (
input: KillBashInput,
_context: ToolContext
): Promise<KillBashOutput> => {
const { shellId } = input;
const bgProcess = backgroundProcesses.get(shellId);
if (!bgProcess) {
return {
success: false,
message: `No background process found with ID: ${shellId}`,
};
}
// Check if process has already exited
if (bgProcess.exitCode !== null) {
return {
success: true,
message: `Process ${shellId} already exited with code ${bgProcess.exitCode}`,
};
}
// Send SIGTERM (target process group for detached background jobs)
try {
if (bgProcess.detached && process.platform !== 'win32') {
process.kill(-bgProcess.pid, 'SIGTERM');
} else {
bgProcess.process.kill('SIGTERM');
}
} catch {
// Ignore if already exited between checks.
}
// Wait up to 5 seconds for graceful exit, then SIGKILL
return new Promise((resolve) => {
const checkInterval = setInterval(() => {
if (bgProcess.exitCode !== null) {
clearInterval(checkInterval);
clearTimeout(forceKillTimeout);
resolve({
success: true,
message: `Process ${shellId} terminated with exit code ${bgProcess.exitCode}`,
});
}
}, 100);
const forceKillTimeout = setTimeout(() => {
clearInterval(checkInterval);
if (bgProcess.exitCode === null) {
try {
if (bgProcess.detached && process.platform !== 'win32') {
process.kill(-bgProcess.pid, 'SIGKILL');
} else {
bgProcess.process.kill('SIGKILL');
}
} catch {
// Ignore if already exited.
}
resolve({
success: true,
message: `Process ${shellId} force-killed with SIGKILL`,
});
}
}, 5000);
});
};
}
// Export singleton instance
export const killBashTool = new KillBashTool();