@wrongstack/tools 0.5.6 → 0.5.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bash.d.ts +2 -1
- package/dist/bash.js +361 -3
- package/dist/bash.js.map +1 -1
- package/dist/builtin.js +389 -5
- package/dist/builtin.js.map +1 -1
- package/dist/circuit-breaker.d.ts +111 -0
- package/dist/circuit-breaker.js +150 -0
- package/dist/circuit-breaker.js.map +1 -0
- package/dist/exec.js +346 -2
- package/dist/exec.js.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.js +393 -6
- package/dist/index.js.map +1 -1
- package/dist/pack.js +389 -5
- package/dist/pack.js.map +1 -1
- package/dist/process-registry.d.ts +112 -0
- package/dist/process-registry.js +327 -0
- package/dist/process-registry.js.map +1 -0
- package/package.json +10 -2
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { ChildProcess } from 'node:child_process';
|
|
2
|
+
import { CircuitBreakerSnapshot, CircuitBreakerConfig } from './circuit-breaker.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* ProcessRegistry — global singleton that tracks all spawned child processes
|
|
6
|
+
* from `bash` and `exec` tools. Enables:
|
|
7
|
+
*
|
|
8
|
+
* - Listing active processes (for TUI status bar)
|
|
9
|
+
* - Killing individual processes or all processes (for Ctrl+C and /kill)
|
|
10
|
+
* - Detecting runaway processes (hung, looping)
|
|
11
|
+
* - Circuit breaker integration to prevent recursive/repeated failures
|
|
12
|
+
*
|
|
13
|
+
* Thread-safety: Node.js is single-threaded, but async callbacks can fire
|
|
14
|
+
* in any order. All mutations go through synchronized Map methods.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
interface TrackedProcess {
|
|
18
|
+
pid: number;
|
|
19
|
+
name: string;
|
|
20
|
+
command: string;
|
|
21
|
+
startedAt: number;
|
|
22
|
+
sessionId?: string;
|
|
23
|
+
/** The raw ChildProcess handle. Never call .kill() directly on this —
|
|
24
|
+
* use `kill()` below which handles process groups correctly on POSIX
|
|
25
|
+
* and degrades gracefully on Windows. */
|
|
26
|
+
child: ChildProcess;
|
|
27
|
+
/** True once the process has been kill()ed but not yet exited.
|
|
28
|
+
* We keep it in the registry until 'close' fires so callers can
|
|
29
|
+
* distinguish "still running" from "just exited". */
|
|
30
|
+
killed: boolean;
|
|
31
|
+
}
|
|
32
|
+
interface KillOpts {
|
|
33
|
+
/** SIGKILL instead of SIGTERM. Default: false (SIGTERM first). */
|
|
34
|
+
force?: boolean;
|
|
35
|
+
/** MS to wait between SIGTERM and SIGKILL on POSIX. Default: 2000. */
|
|
36
|
+
graceMs?: number;
|
|
37
|
+
}
|
|
38
|
+
interface RegistryStats {
|
|
39
|
+
activeCount: number;
|
|
40
|
+
totalCount: number;
|
|
41
|
+
breaker: CircuitBreakerSnapshot;
|
|
42
|
+
}
|
|
43
|
+
declare class ProcessRegistryImpl {
|
|
44
|
+
private readonly processes;
|
|
45
|
+
private readonly breaker;
|
|
46
|
+
constructor(breakerConfig?: CircuitBreakerConfig);
|
|
47
|
+
register(info: Omit<TrackedProcess, 'killed'>): void;
|
|
48
|
+
/** Unregister a process by PID. Called on 'close' / 'exit' events. */
|
|
49
|
+
unregister(pid: number): void;
|
|
50
|
+
/** Get a single process by PID. */
|
|
51
|
+
get(pid: number): TrackedProcess | undefined;
|
|
52
|
+
/** Get all tracked processes. */
|
|
53
|
+
list(): TrackedProcess[];
|
|
54
|
+
/** Get processes filtered by name (e.g. 'bash', 'exec'). */
|
|
55
|
+
byName(name: string): TrackedProcess[];
|
|
56
|
+
/** Get processes filtered by session. */
|
|
57
|
+
bySession(sessionId: string): TrackedProcess[];
|
|
58
|
+
/** Count of active (non-killed) processes. */
|
|
59
|
+
get activeCount(): number;
|
|
60
|
+
/**
|
|
61
|
+
* Combined stats for observability — used by /ps and the TUI status bar.
|
|
62
|
+
*/
|
|
63
|
+
stats(): RegistryStats;
|
|
64
|
+
/**
|
|
65
|
+
* Returns true if the circuit allows a new bash/exec call to proceed.
|
|
66
|
+
* When false, callers MUST NOT spawn a process.
|
|
67
|
+
*/
|
|
68
|
+
get canProceed(): boolean;
|
|
69
|
+
/**
|
|
70
|
+
* Called before spawning a process. Returns true if allowed; false if
|
|
71
|
+
* the circuit breaker is open.
|
|
72
|
+
*/
|
|
73
|
+
beforeCall(): boolean;
|
|
74
|
+
/**
|
|
75
|
+
* Called after a process finishes. `durationMs` is wall-clock time;
|
|
76
|
+
* `failed` is true for non-zero exit codes.
|
|
77
|
+
*/
|
|
78
|
+
afterCall(durationMs: number, failed: boolean): void;
|
|
79
|
+
/** Force-open the circuit breaker (Ctrl+C, /kill force). */
|
|
80
|
+
forceBreakerOpen(): void;
|
|
81
|
+
/** Force-reset the circuit breaker to closed (/kill reset). */
|
|
82
|
+
forceBreakerReset(): void;
|
|
83
|
+
/** Kill a single process by PID.
|
|
84
|
+
*
|
|
85
|
+
* On POSIX: sends SIGTERM to the *process group* (-pid) so that
|
|
86
|
+
* runaway grandchild processes (`sleep 9999 & disown`) are also killed.
|
|
87
|
+
* After `graceMs` a SIGKILL is sent if the process hasn't exited.
|
|
88
|
+
*
|
|
89
|
+
* On Windows: `child.kill()` maps to TerminateProcess — process groups
|
|
90
|
+
* are not meaningfully supported. A second `force=true` call sends
|
|
91
|
+
* SIGKILL (which maps to TerminateProcess again — the distinction is
|
|
92
|
+
* in the exit code, not the signal).
|
|
93
|
+
*
|
|
94
|
+
* Returns true if the process was found and kill was attempted.
|
|
95
|
+
*/
|
|
96
|
+
kill(pid: number, opts?: KillOpts): boolean;
|
|
97
|
+
/**
|
|
98
|
+
* Kill all tracked processes.
|
|
99
|
+
* Returns the PIDs that were kill()ed.
|
|
100
|
+
*/
|
|
101
|
+
killAll(opts?: KillOpts): number[];
|
|
102
|
+
/**
|
|
103
|
+
* Kill all processes for a specific session.
|
|
104
|
+
* Returns the PIDs that were kill()ed.
|
|
105
|
+
*/
|
|
106
|
+
killSession(sessionId: string, opts?: KillOpts): number[];
|
|
107
|
+
}
|
|
108
|
+
declare function getProcessRegistry(): ProcessRegistryImpl;
|
|
109
|
+
/** Reset for tests. */
|
|
110
|
+
declare function _resetProcessRegistry(): void;
|
|
111
|
+
|
|
112
|
+
export { CircuitBreakerConfig, CircuitBreakerSnapshot, type KillOpts, type RegistryStats, type TrackedProcess, _resetProcessRegistry, getProcessRegistry };
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
import * as os from 'os';
|
|
2
|
+
|
|
3
|
+
// src/process-registry.ts
|
|
4
|
+
|
|
5
|
+
// src/circuit-breaker.ts
|
|
6
|
+
var DEFAULT_MAX_CONSECUTIVE_FAILURES = 5;
|
|
7
|
+
var DEFAULT_SLOW_CALL_THRESHOLD_MS = 6e4;
|
|
8
|
+
var DEFAULT_MAX_SLOW_CALLS = 3;
|
|
9
|
+
var DEFAULT_WINDOW_MS = 6e4;
|
|
10
|
+
var DEFAULT_MAX_CALLS_PER_WINDOW = 30;
|
|
11
|
+
var DEFAULT_COOLDOWN_MS = 3e4;
|
|
12
|
+
var CircuitBreaker = class {
|
|
13
|
+
maxConsecutiveFailures;
|
|
14
|
+
slowCallThresholdMs;
|
|
15
|
+
maxSlowCalls;
|
|
16
|
+
windowMs;
|
|
17
|
+
maxCallsPerWindow;
|
|
18
|
+
cooldownMs;
|
|
19
|
+
state = "closed";
|
|
20
|
+
consecutiveFailures = 0;
|
|
21
|
+
window = [];
|
|
22
|
+
lastFailureAt = null;
|
|
23
|
+
lastSlowAt = null;
|
|
24
|
+
/** Timestamp when the breaker was opened (for cooldown calculation). */
|
|
25
|
+
openedAt = null;
|
|
26
|
+
/** Timestamp when the last call ran (for half-open gate). */
|
|
27
|
+
lastCallAt = null;
|
|
28
|
+
constructor(config = {}) {
|
|
29
|
+
this.maxConsecutiveFailures = config.maxConsecutiveFailures ?? DEFAULT_MAX_CONSECUTIVE_FAILURES;
|
|
30
|
+
this.slowCallThresholdMs = config.slowCallThresholdMs ?? DEFAULT_SLOW_CALL_THRESHOLD_MS;
|
|
31
|
+
this.maxSlowCalls = config.maxSlowCalls ?? DEFAULT_MAX_SLOW_CALLS;
|
|
32
|
+
this.windowMs = config.windowMs ?? DEFAULT_WINDOW_MS;
|
|
33
|
+
this.maxCallsPerWindow = config.maxCallsPerWindow ?? DEFAULT_MAX_CALLS_PER_WINDOW;
|
|
34
|
+
this.cooldownMs = config.cooldownMs ?? DEFAULT_COOLDOWN_MS;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Returns true if the circuit allows a new call to proceed.
|
|
38
|
+
* When false, callers should abort the tool call and return a
|
|
39
|
+
* circuit-breaker error instead of spawning a process.
|
|
40
|
+
*/
|
|
41
|
+
get canProceed() {
|
|
42
|
+
this._checkStateTransition();
|
|
43
|
+
return this.state !== "open";
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Snapshot of the current breaker state for observability (`/kill`).
|
|
47
|
+
*/
|
|
48
|
+
snapshot() {
|
|
49
|
+
this._checkStateTransition();
|
|
50
|
+
const now = Date.now();
|
|
51
|
+
let cooldownRemaining = null;
|
|
52
|
+
if (this.openedAt !== null && this.state === "open") {
|
|
53
|
+
const elapsed = now - this.openedAt;
|
|
54
|
+
cooldownRemaining = Math.max(0, this.cooldownMs - elapsed);
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
state: this.state,
|
|
58
|
+
consecutiveFailures: this.consecutiveFailures,
|
|
59
|
+
slowCallsInWindow: this.window.filter((c) => c.slow).length,
|
|
60
|
+
callsInWindow: this.window.length,
|
|
61
|
+
windowMs: this.windowMs,
|
|
62
|
+
cooldownRemainingMs: cooldownRemaining,
|
|
63
|
+
lastFailureAt: this.lastFailureAt,
|
|
64
|
+
lastSlowAt: this.lastSlowAt
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Call this BEFORE spawning a bash/exec process.
|
|
69
|
+
* Returns true if the call is allowed; false if the breaker is open.
|
|
70
|
+
* When false, callers MUST NOT spawn a process.
|
|
71
|
+
*/
|
|
72
|
+
beforeCall() {
|
|
73
|
+
this._checkStateTransition();
|
|
74
|
+
if (this.state === "open") return false;
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Call this AFTER a bash/exec process finishes (success or failure).
|
|
79
|
+
* `durationMs` is the wall-clock time the process ran.
|
|
80
|
+
* `failed` is true when the process returned a non-zero exit code or
|
|
81
|
+
* threw an exception before spawning.
|
|
82
|
+
*/
|
|
83
|
+
afterCall(durationMs, failed) {
|
|
84
|
+
const now = Date.now();
|
|
85
|
+
this.lastCallAt = now;
|
|
86
|
+
if (this.state === "half-open") {
|
|
87
|
+
if (failed) {
|
|
88
|
+
this._trip();
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
this._reset();
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
this._pruneWindow(now);
|
|
95
|
+
const slow = durationMs >= this.slowCallThresholdMs;
|
|
96
|
+
this.window.push({ at: now, failed, slow });
|
|
97
|
+
if (failed) {
|
|
98
|
+
this.consecutiveFailures++;
|
|
99
|
+
this.lastFailureAt = now;
|
|
100
|
+
if (this.consecutiveFailures >= this.maxConsecutiveFailures) {
|
|
101
|
+
this._trip();
|
|
102
|
+
}
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
this.consecutiveFailures = 0;
|
|
106
|
+
if (slow) {
|
|
107
|
+
this.lastSlowAt = now;
|
|
108
|
+
const slowCount = this.window.filter((c) => c.slow).length;
|
|
109
|
+
if (slowCount >= this.maxSlowCalls) {
|
|
110
|
+
this._trip();
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
const callCount = this.window.length;
|
|
114
|
+
if (callCount >= this.maxCallsPerWindow) {
|
|
115
|
+
this._trip();
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/** Force the breaker open. Used by /kill force and Ctrl+C. */
|
|
119
|
+
forceOpen() {
|
|
120
|
+
this._trip();
|
|
121
|
+
}
|
|
122
|
+
/** Force a reset to closed. Used by tests and /kill reset. */
|
|
123
|
+
forceReset() {
|
|
124
|
+
this._reset();
|
|
125
|
+
}
|
|
126
|
+
_trip() {
|
|
127
|
+
if (this.state === "open") return;
|
|
128
|
+
this.state = "open";
|
|
129
|
+
this.openedAt = Date.now();
|
|
130
|
+
}
|
|
131
|
+
_reset() {
|
|
132
|
+
this.state = "closed";
|
|
133
|
+
this.consecutiveFailures = 0;
|
|
134
|
+
this.window = [];
|
|
135
|
+
this.openedAt = null;
|
|
136
|
+
}
|
|
137
|
+
/** Transition from open → half-open when cooldown elapses. */
|
|
138
|
+
_checkStateTransition() {
|
|
139
|
+
if (this.state !== "open" || this.openedAt === null) return;
|
|
140
|
+
const elapsed = Date.now() - this.openedAt;
|
|
141
|
+
if (elapsed >= this.cooldownMs) {
|
|
142
|
+
this.state = "half-open";
|
|
143
|
+
this.openedAt = null;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
_pruneWindow(now) {
|
|
147
|
+
const cutoff = now - this.windowMs;
|
|
148
|
+
this.window = this.window.filter((c) => c.at >= cutoff);
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
// src/process-registry.ts
|
|
153
|
+
var DEFAULT_GRACE_MS = 2e3;
|
|
154
|
+
var ProcessRegistryImpl = class {
|
|
155
|
+
processes = /* @__PURE__ */ new Map();
|
|
156
|
+
breaker;
|
|
157
|
+
constructor(breakerConfig) {
|
|
158
|
+
this.breaker = new CircuitBreaker(breakerConfig);
|
|
159
|
+
}
|
|
160
|
+
register(info) {
|
|
161
|
+
this.processes.set(info.pid, { ...info, killed: false });
|
|
162
|
+
}
|
|
163
|
+
/** Unregister a process by PID. Called on 'close' / 'exit' events. */
|
|
164
|
+
unregister(pid) {
|
|
165
|
+
this.processes.delete(pid);
|
|
166
|
+
}
|
|
167
|
+
/** Get a single process by PID. */
|
|
168
|
+
get(pid) {
|
|
169
|
+
return this.processes.get(pid);
|
|
170
|
+
}
|
|
171
|
+
/** Get all tracked processes. */
|
|
172
|
+
list() {
|
|
173
|
+
return Array.from(this.processes.values());
|
|
174
|
+
}
|
|
175
|
+
/** Get processes filtered by name (e.g. 'bash', 'exec'). */
|
|
176
|
+
byName(name) {
|
|
177
|
+
return this.list().filter((p) => p.name === name);
|
|
178
|
+
}
|
|
179
|
+
/** Get processes filtered by session. */
|
|
180
|
+
bySession(sessionId) {
|
|
181
|
+
return this.list().filter((p) => p.sessionId === sessionId);
|
|
182
|
+
}
|
|
183
|
+
/** Count of active (non-killed) processes. */
|
|
184
|
+
get activeCount() {
|
|
185
|
+
let n = 0;
|
|
186
|
+
for (const p of this.processes.values()) {
|
|
187
|
+
if (!p.killed) n++;
|
|
188
|
+
}
|
|
189
|
+
return n;
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Combined stats for observability — used by /ps and the TUI status bar.
|
|
193
|
+
*/
|
|
194
|
+
stats() {
|
|
195
|
+
return {
|
|
196
|
+
activeCount: this.activeCount,
|
|
197
|
+
totalCount: this.processes.size,
|
|
198
|
+
breaker: this.breaker.snapshot()
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Returns true if the circuit allows a new bash/exec call to proceed.
|
|
203
|
+
* When false, callers MUST NOT spawn a process.
|
|
204
|
+
*/
|
|
205
|
+
get canProceed() {
|
|
206
|
+
return this.breaker.canProceed;
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Called before spawning a process. Returns true if allowed; false if
|
|
210
|
+
* the circuit breaker is open.
|
|
211
|
+
*/
|
|
212
|
+
beforeCall() {
|
|
213
|
+
return this.breaker.beforeCall();
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Called after a process finishes. `durationMs` is wall-clock time;
|
|
217
|
+
* `failed` is true for non-zero exit codes.
|
|
218
|
+
*/
|
|
219
|
+
afterCall(durationMs, failed) {
|
|
220
|
+
this.breaker.afterCall(durationMs, failed);
|
|
221
|
+
}
|
|
222
|
+
/** Force-open the circuit breaker (Ctrl+C, /kill force). */
|
|
223
|
+
forceBreakerOpen() {
|
|
224
|
+
this.breaker.forceOpen();
|
|
225
|
+
}
|
|
226
|
+
/** Force-reset the circuit breaker to closed (/kill reset). */
|
|
227
|
+
forceBreakerReset() {
|
|
228
|
+
this.breaker.forceReset();
|
|
229
|
+
}
|
|
230
|
+
/** Kill a single process by PID.
|
|
231
|
+
*
|
|
232
|
+
* On POSIX: sends SIGTERM to the *process group* (-pid) so that
|
|
233
|
+
* runaway grandchild processes (`sleep 9999 & disown`) are also killed.
|
|
234
|
+
* After `graceMs` a SIGKILL is sent if the process hasn't exited.
|
|
235
|
+
*
|
|
236
|
+
* On Windows: `child.kill()` maps to TerminateProcess — process groups
|
|
237
|
+
* are not meaningfully supported. A second `force=true` call sends
|
|
238
|
+
* SIGKILL (which maps to TerminateProcess again — the distinction is
|
|
239
|
+
* in the exit code, not the signal).
|
|
240
|
+
*
|
|
241
|
+
* Returns true if the process was found and kill was attempted.
|
|
242
|
+
*/
|
|
243
|
+
kill(pid, opts = {}) {
|
|
244
|
+
const p = this.processes.get(pid);
|
|
245
|
+
if (!p) return false;
|
|
246
|
+
if (p.killed) return true;
|
|
247
|
+
const { force = false, graceMs = DEFAULT_GRACE_MS } = opts;
|
|
248
|
+
const isWin = os.platform() === "win32";
|
|
249
|
+
if (isWin) {
|
|
250
|
+
try {
|
|
251
|
+
p.child.kill(force ? "SIGKILL" : "SIGTERM");
|
|
252
|
+
} catch {
|
|
253
|
+
}
|
|
254
|
+
p.killed = true;
|
|
255
|
+
return true;
|
|
256
|
+
}
|
|
257
|
+
try {
|
|
258
|
+
if (force) {
|
|
259
|
+
try {
|
|
260
|
+
process.kill(-pid, "SIGKILL");
|
|
261
|
+
} catch {
|
|
262
|
+
p.child.kill("SIGKILL");
|
|
263
|
+
}
|
|
264
|
+
} else {
|
|
265
|
+
try {
|
|
266
|
+
process.kill(-pid, "SIGTERM");
|
|
267
|
+
} catch {
|
|
268
|
+
p.child.kill("SIGTERM");
|
|
269
|
+
}
|
|
270
|
+
const timer = setTimeout(() => {
|
|
271
|
+
if (this.processes.has(pid) && !p.child.killed) {
|
|
272
|
+
try {
|
|
273
|
+
process.kill(-pid, "SIGKILL");
|
|
274
|
+
} catch {
|
|
275
|
+
try {
|
|
276
|
+
p.child.kill("SIGKILL");
|
|
277
|
+
} catch {
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
}, graceMs);
|
|
282
|
+
timer.unref?.();
|
|
283
|
+
}
|
|
284
|
+
} catch {
|
|
285
|
+
}
|
|
286
|
+
p.killed = true;
|
|
287
|
+
return true;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Kill all tracked processes.
|
|
291
|
+
* Returns the PIDs that were kill()ed.
|
|
292
|
+
*/
|
|
293
|
+
killAll(opts = {}) {
|
|
294
|
+
const pids = Array.from(this.processes.keys());
|
|
295
|
+
const killed = [];
|
|
296
|
+
for (const pid of pids) {
|
|
297
|
+
if (this.kill(pid, opts)) killed.push(pid);
|
|
298
|
+
}
|
|
299
|
+
return killed;
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Kill all processes for a specific session.
|
|
303
|
+
* Returns the PIDs that were kill()ed.
|
|
304
|
+
*/
|
|
305
|
+
killSession(sessionId, opts = {}) {
|
|
306
|
+
const pids = this.bySession(sessionId).map((p) => p.pid);
|
|
307
|
+
const killed = [];
|
|
308
|
+
for (const pid of pids) {
|
|
309
|
+
if (this.kill(pid, opts)) killed.push(pid);
|
|
310
|
+
}
|
|
311
|
+
return killed;
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
var _registry;
|
|
315
|
+
function getProcessRegistry() {
|
|
316
|
+
if (!_registry) {
|
|
317
|
+
_registry = new ProcessRegistryImpl();
|
|
318
|
+
}
|
|
319
|
+
return _registry;
|
|
320
|
+
}
|
|
321
|
+
function _resetProcessRegistry() {
|
|
322
|
+
_registry = void 0;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
export { _resetProcessRegistry, getProcessRegistry };
|
|
326
|
+
//# sourceMappingURL=process-registry.js.map
|
|
327
|
+
//# sourceMappingURL=process-registry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/circuit-breaker.ts","../src/process-registry.ts"],"names":[],"mappings":";;;;;AA6DA,IAAM,gCAAA,GAAmC,CAAA;AACzC,IAAM,8BAAA,GAAiC,GAAA;AACvC,IAAM,sBAAA,GAAyB,CAAA;AAC/B,IAAM,iBAAA,GAAoB,GAAA;AAC1B,IAAM,4BAAA,GAA+B,EAAA;AACrC,IAAM,mBAAA,GAAsB,GAAA;AAarB,IAAM,iBAAN,MAAqB;AAAA,EACT,sBAAA;AAAA,EACA,mBAAA;AAAA,EACA,YAAA;AAAA,EACA,QAAA;AAAA,EACA,iBAAA;AAAA,EACA,UAAA;AAAA,EAET,KAAA,GAAsB,QAAA;AAAA,EACtB,mBAAA,GAAsB,CAAA;AAAA,EACtB,SAAuB,EAAC;AAAA,EACxB,aAAA,GAA+B,IAAA;AAAA,EAC/B,UAAA,GAA4B,IAAA;AAAA;AAAA,EAE5B,QAAA,GAA0B,IAAA;AAAA;AAAA,EAE1B,UAAA,GAA4B,IAAA;AAAA,EAEpC,WAAA,CAAY,MAAA,GAA+B,EAAC,EAAG;AAC7C,IAAA,IAAA,CAAK,sBAAA,GAAyB,OAAO,sBAAA,IAA0B,gCAAA;AAC/D,IAAA,IAAA,CAAK,mBAAA,GAAsB,OAAO,mBAAA,IAAuB,8BAAA;AACzD,IAAA,IAAA,CAAK,YAAA,GAAe,OAAO,YAAA,IAAgB,sBAAA;AAC3C,IAAA,IAAA,CAAK,QAAA,GAAW,OAAO,QAAA,IAAY,iBAAA;AACnC,IAAA,IAAA,CAAK,iBAAA,GAAoB,OAAO,iBAAA,IAAqB,4BAAA;AACrD,IAAA,IAAA,CAAK,UAAA,GAAa,OAAO,UAAA,IAAc,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,OAAO,IAAA;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,OAAA,CAAQ,IAAA,GAAiB,EAAC,EAAa;AACrC,IAAA,MAAM,OAAO,KAAA,CAAM,IAAA,CAAK,IAAA,CAAK,SAAA,CAAU,MAAM,CAAA;AAC7C,IAAA,MAAM,SAAmB,EAAC;AAC1B,IAAA,KAAA,MAAW,OAAO,IAAA,EAAM;AACtB,MAAA,IAAI,KAAK,IAAA,CAAK,GAAA,EAAK,IAAI,CAAA,EAAG,MAAA,CAAO,KAAK,GAAG,CAAA;AAAA,IAC3C;AACA,IAAA,OAAO,MAAA;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,WAAA,CAAY,SAAA,EAAmB,IAAA,GAAiB,EAAC,EAAa;AAC5D,IAAA,MAAM,IAAA,GAAO,KAAK,SAAA,CAAU,SAAS,EAAE,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,GAAG,CAAA;AACvD,IAAA,MAAM,SAAmB,EAAC;AAC1B,IAAA,KAAA,MAAW,OAAO,IAAA,EAAM;AACtB,MAAA,IAAI,KAAK,IAAA,CAAK,GAAA,EAAK,IAAI,CAAA,EAAG,MAAA,CAAO,KAAK,GAAG,CAAA;AAAA,IAC3C;AACA,IAAA,OAAO,MAAA;AAAA,EACT;AACF,CAAA;AAGA,IAAI,SAAA;AAEG,SAAS,kBAAA,GAA0C;AACxD,EAAA,IAAI,CAAC,SAAA,EAAW;AACd,IAAA,SAAA,GAAY,IAAI,mBAAA,EAAoB;AAAA,EACtC;AACA,EAAA,OAAO,SAAA;AACT;AAGO,SAAS,qBAAA,GAA8B;AAC5C,EAAA,SAAA,GAAY,MAAA;AACd","file":"process-registry.js","sourcesContent":["/**\n * CircuitBreaker — prevents runaway bash/exec tool chains by:\n *\n * - Tripping on consecutive failures (models that keep repeating the\n * same failing command, e.g. `npm install` with wrong args in a loop)\n * - Tripping on slow call ratio (too many long-running commands suggest\n * a hung subprocess that the model doesn't know how to kill)\n * - Rate-limiting bursts (rapid succession of commands without reading\n * output suggests the model isn't processing results)\n * - Auto-recovering after a cooldown period so a fixed model can resume\n *\n * The breaker is owned by the ProcessRegistry so any tool that registers\n * a process participates in the same circuit. \"Per-tool\" isolation is\n * intentionally NOT implemented — the model treats bash/exec as one\n * resource pool; isolating them would let the model route around the\n * breaker by alternating which tool it uses.\n */\n\nexport interface CircuitBreakerConfig {\n /**\n * Consecutive failures before trip. Default: 5.\n * A single success resets this counter to 0.\n */\n maxConsecutiveFailures?: number;\n /**\n * Slow-call threshold in ms. A call that runs longer than this is\n * counted as \"slow\". Default: 60_000 (1 minute).\n */\n slowCallThresholdMs?: number;\n /**\n * Max slow calls before trip (within the sliding window). Default: 3.\n */\n maxSlowCalls?: number;\n /**\n * Sliding window for rate-limit and slow-call counting, in ms.\n * Default: 60_000 (1 minute).\n */\n windowMs?: number;\n /**\n * Max calls within the sliding window. Default: 30.\n * Burst exceeding this trips the breaker immediately.\n */\n maxCallsPerWindow?: number;\n /**\n * Cooldown before auto-recovery attempt, in ms. Default: 30_000 (30s).\n * After this the breaker enters \"half-open\" state and allows one call\n * through to test whether the problem is resolved.\n */\n cooldownMs?: number;\n}\n\ninterface CallRecord {\n at: number;\n /** True if the call threw or returned an is_error result. */\n failed: boolean;\n /** True if elapsed time exceeded slowCallThresholdMs. */\n slow: boolean;\n}\n\ntype BreakerState = 'closed' | 'open' | 'half-open';\n\nconst DEFAULT_MAX_CONSECUTIVE_FAILURES = 5;\nconst DEFAULT_SLOW_CALL_THRESHOLD_MS = 60_000;\nconst DEFAULT_MAX_SLOW_CALLS = 3;\nconst DEFAULT_WINDOW_MS = 60_000;\nconst DEFAULT_MAX_CALLS_PER_WINDOW = 30;\nconst DEFAULT_COOLDOWN_MS = 30_000;\n\nexport interface CircuitBreakerSnapshot {\n state: 'closed' | 'open' | 'half-open';\n consecutiveFailures: number;\n slowCallsInWindow: number;\n callsInWindow: number;\n windowMs: number;\n cooldownRemainingMs: number | null;\n lastFailureAt: number | null;\n lastSlowAt: number | null;\n}\n\nexport class CircuitBreaker {\n private readonly maxConsecutiveFailures: number;\n private readonly slowCallThresholdMs: number;\n private readonly maxSlowCalls: number;\n private readonly windowMs: number;\n private readonly maxCallsPerWindow: number;\n private readonly cooldownMs: number;\n\n private state: BreakerState = 'closed';\n private consecutiveFailures = 0;\n private window: CallRecord[] = [];\n private lastFailureAt: number | null = null;\n private lastSlowAt: number | null = null;\n /** Timestamp when the breaker was opened (for cooldown calculation). */\n private openedAt: number | null = null;\n /** Timestamp when the last call ran (for half-open gate). */\n private lastCallAt: number | null = null;\n\n constructor(config: CircuitBreakerConfig = {}) {\n this.maxConsecutiveFailures = config.maxConsecutiveFailures ?? DEFAULT_MAX_CONSECUTIVE_FAILURES;\n this.slowCallThresholdMs = config.slowCallThresholdMs ?? DEFAULT_SLOW_CALL_THRESHOLD_MS;\n this.maxSlowCalls = config.maxSlowCalls ?? DEFAULT_MAX_SLOW_CALLS;\n this.windowMs = config.windowMs ?? DEFAULT_WINDOW_MS;\n this.maxCallsPerWindow = config.maxCallsPerWindow ?? DEFAULT_MAX_CALLS_PER_WINDOW;\n this.cooldownMs = config.cooldownMs ?? DEFAULT_COOLDOWN_MS;\n }\n\n /**\n * Returns true if the circuit allows a new call to proceed.\n * When false, callers should abort the tool call and return a\n * circuit-breaker error instead of spawning a process.\n */\n get canProceed(): boolean {\n this._checkStateTransition();\n return this.state !== 'open';\n }\n\n /**\n * Snapshot of the current breaker state for observability (`/kill`).\n */\n snapshot(): CircuitBreakerSnapshot {\n this._checkStateTransition();\n const now = Date.now();\n let cooldownRemaining: number | null = null;\n if (this.openedAt !== null && this.state === 'open') {\n const elapsed = now - this.openedAt;\n cooldownRemaining = Math.max(0, this.cooldownMs - elapsed);\n }\n return {\n state: this.state,\n consecutiveFailures: this.consecutiveFailures,\n slowCallsInWindow: this.window.filter((c) => c.slow).length,\n callsInWindow: this.window.length,\n windowMs: this.windowMs,\n cooldownRemainingMs: cooldownRemaining,\n lastFailureAt: this.lastFailureAt,\n lastSlowAt: this.lastSlowAt,\n };\n }\n\n /**\n * Call this BEFORE spawning a bash/exec process.\n * Returns true if the call is allowed; false if the breaker is open.\n * When false, callers MUST NOT spawn a process.\n */\n beforeCall(): boolean {\n this._checkStateTransition();\n if (this.state === 'open') return false;\n return true;\n }\n\n /**\n * Call this AFTER a bash/exec process finishes (success or failure).\n * `durationMs` is the wall-clock time the process ran.\n * `failed` is true when the process returned a non-zero exit code or\n * threw an exception before spawning.\n */\n afterCall(durationMs: number, failed: boolean): void {\n const now = Date.now();\n this.lastCallAt = now;\n\n if (this.state === 'half-open') {\n // First call through after cooldown — if it failed, go back to open.\n if (failed) {\n this._trip();\n return;\n }\n // Success in half-open → reset to closed.\n this._reset();\n return;\n }\n\n // Prune old records outside the sliding window.\n this._pruneWindow(now);\n\n const slow = durationMs >= this.slowCallThresholdMs;\n this.window.push({ at: now, failed, slow });\n\n if (failed) {\n this.consecutiveFailures++;\n this.lastFailureAt = now;\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n this._trip();\n }\n return;\n }\n\n // Success: reset consecutive failure counter.\n this.consecutiveFailures = 0;\n\n if (slow) {\n this.lastSlowAt = now;\n const slowCount = this.window.filter((c) => c.slow).length;\n if (slowCount >= this.maxSlowCalls) {\n this._trip();\n }\n }\n\n const callCount = this.window.length;\n if (callCount >= this.maxCallsPerWindow) {\n // Rate limit exceeded. This is a soft trip — we reset the window\n // and let the next call try immediately (the caller will still see\n // canProceed=false until the window drains naturally).\n this._trip();\n }\n }\n\n /** Force the breaker open. Used by /kill force and Ctrl+C. */\n forceOpen(): void {\n this._trip();\n }\n\n /** Force a reset to closed. Used by tests and /kill reset. */\n forceReset(): void {\n this._reset();\n }\n\n private _trip(): void {\n if (this.state === 'open') return; // already open\n this.state = 'open';\n this.openedAt = Date.now();\n }\n\n private _reset(): void {\n this.state = 'closed';\n this.consecutiveFailures = 0;\n this.window = [];\n this.openedAt = null;\n }\n\n /** Transition from open → half-open when cooldown elapses. */\n private _checkStateTransition(): void {\n if (this.state !== 'open' || this.openedAt === null) return;\n const elapsed = Date.now() - this.openedAt;\n if (elapsed >= this.cooldownMs) {\n this.state = 'half-open';\n this.openedAt = null;\n }\n }\n\n private _pruneWindow(now: number): void {\n const cutoff = now - this.windowMs;\n this.window = this.window.filter((c) => c.at >= cutoff);\n }\n}","/**\n * ProcessRegistry — global singleton that tracks all spawned child processes\n * from `bash` and `exec` tools. Enables:\n *\n * - Listing active processes (for TUI status bar)\n * - Killing individual processes or all processes (for Ctrl+C and /kill)\n * - Detecting runaway processes (hung, looping)\n * - Circuit breaker integration to prevent recursive/repeated failures\n *\n * Thread-safety: Node.js is single-threaded, but async callbacks can fire\n * in any order. All mutations go through synchronized Map methods.\n */\nimport type { ChildProcess } from 'node:child_process';\nimport * as os from 'node:os';\nimport { CircuitBreaker, type CircuitBreakerSnapshot, type CircuitBreakerConfig } from './circuit-breaker.js';\n\nexport { type CircuitBreakerSnapshot, type CircuitBreakerConfig } from './circuit-breaker.js';\n\nexport interface TrackedProcess {\n pid: number;\n name: string;\n command: string;\n startedAt: number;\n sessionId?: string;\n /** The raw ChildProcess handle. Never call .kill() directly on this —\n * use `kill()` below which handles process groups correctly on POSIX\n * and degrades gracefully on Windows. */\n child: ChildProcess;\n /** True once the process has been kill()ed but not yet exited.\n * We keep it in the registry until 'close' fires so callers can\n * distinguish \"still running\" from \"just exited\". */\n killed: boolean;\n}\n\ninterface KillOpts {\n /** SIGKILL instead of SIGTERM. Default: false (SIGTERM first). */\n force?: boolean;\n /** MS to wait between SIGTERM and SIGKILL on POSIX. Default: 2000. */\n graceMs?: number;\n}\n\nexport interface RegistryStats {\n activeCount: number;\n totalCount: number;\n breaker: CircuitBreakerSnapshot;\n}\n\nconst DEFAULT_GRACE_MS = 2000;\n\nclass ProcessRegistryImpl {\n private readonly processes = new Map<number, TrackedProcess>();\n private readonly breaker: CircuitBreaker;\n\n constructor(breakerConfig?: CircuitBreakerConfig) {\n this.breaker = new CircuitBreaker(breakerConfig);\n }\n\n register(info: Omit<TrackedProcess, 'killed'>): void {\n this.processes.set(info.pid, { ...info, killed: false });\n }\n\n /** Unregister a process by PID. Called on 'close' / 'exit' events. */\n unregister(pid: number): void {\n this.processes.delete(pid);\n }\n\n /** Get a single process by PID. */\n get(pid: number): TrackedProcess | undefined {\n return this.processes.get(pid);\n }\n\n /** Get all tracked processes. */\n list(): TrackedProcess[] {\n return Array.from(this.processes.values());\n }\n\n /** Get processes filtered by name (e.g. 'bash', 'exec'). */\n byName(name: string): TrackedProcess[] {\n return this.list().filter((p) => p.name === name);\n }\n\n /** Get processes filtered by session. */\n bySession(sessionId: string): TrackedProcess[] {\n return this.list().filter((p) => p.sessionId === sessionId);\n }\n\n /** Count of active (non-killed) processes. */\n get activeCount(): number {\n let n = 0;\n for (const p of this.processes.values()) {\n if (!p.killed) n++;\n }\n return n;\n }\n\n /**\n * Combined stats for observability — used by /ps and the TUI status bar.\n */\n stats(): RegistryStats {\n return {\n activeCount: this.activeCount,\n totalCount: this.processes.size,\n breaker: this.breaker.snapshot(),\n };\n }\n\n /**\n * Returns true if the circuit allows a new bash/exec call to proceed.\n * When false, callers MUST NOT spawn a process.\n */\n get canProceed(): boolean {\n return this.breaker.canProceed;\n }\n\n /**\n * Called before spawning a process. Returns true if allowed; false if\n * the circuit breaker is open.\n */\n beforeCall(): boolean {\n return this.breaker.beforeCall();\n }\n\n /**\n * Called after a process finishes. `durationMs` is wall-clock time;\n * `failed` is true for non-zero exit codes.\n */\n afterCall(durationMs: number, failed: boolean): void {\n this.breaker.afterCall(durationMs, failed);\n }\n\n /** Force-open the circuit breaker (Ctrl+C, /kill force). */\n forceBreakerOpen(): void {\n this.breaker.forceOpen();\n }\n\n /** Force-reset the circuit breaker to closed (/kill reset). */\n forceBreakerReset(): void {\n this.breaker.forceReset();\n }\n\n /** Kill a single process by PID.\n *\n * On POSIX: sends SIGTERM to the *process group* (-pid) so that\n * runaway grandchild processes (`sleep 9999 & disown`) are also killed.\n * After `graceMs` a SIGKILL is sent if the process hasn't exited.\n *\n * On Windows: `child.kill()` maps to TerminateProcess — process groups\n * are not meaningfully supported. A second `force=true` call sends\n * SIGKILL (which maps to TerminateProcess again — the distinction is\n * in the exit code, not the signal).\n *\n * Returns true if the process was found and kill was attempted.\n */\n kill(pid: number, opts: KillOpts = {}): boolean {\n const p = this.processes.get(pid);\n if (!p) return false;\n if (p.killed) return true; // already kill()ed, don't double-send\n\n const { force = false, graceMs = DEFAULT_GRACE_MS } = opts;\n const isWin = os.platform() === 'win32';\n\n if (isWin) {\n // Windows: no process group semantics; just kill the process.\n try {\n p.child.kill(force ? 'SIGKILL' : 'SIGTERM');\n } catch {\n // Process may have already exited.\n }\n p.killed = true;\n return true;\n }\n\n // POSIX: kill the process group so grandchildren are cleaned up too.\n try {\n if (force) {\n try {\n process.kill(-pid, 'SIGKILL');\n } catch {\n p.child.kill('SIGKILL');\n }\n } else {\n try {\n process.kill(-pid, 'SIGTERM');\n } catch {\n p.child.kill('SIGTERM');\n }\n // Schedule SIGKILL as backup.\n const timer = setTimeout(() => {\n // Re-check: process may have exited on its own.\n if (this.processes.has(pid) && !p.child.killed) {\n try {\n process.kill(-pid, 'SIGKILL');\n } catch {\n try {\n p.child.kill('SIGKILL');\n } catch {\n /* already gone */\n }\n }\n }\n }, graceMs);\n timer.unref?.(); // Don't keep event loop alive.\n }\n } catch {\n // Process may have already exited.\n }\n p.killed = true;\n return true;\n }\n\n /**\n * Kill all tracked processes.\n * Returns the PIDs that were kill()ed.\n */\n killAll(opts: KillOpts = {}): number[] {\n const pids = Array.from(this.processes.keys());\n const killed: number[] = [];\n for (const pid of pids) {\n if (this.kill(pid, opts)) killed.push(pid);\n }\n return killed;\n }\n\n /**\n * Kill all processes for a specific session.\n * Returns the PIDs that were kill()ed.\n */\n killSession(sessionId: string, opts: KillOpts = {}): number[] {\n const pids = this.bySession(sessionId).map((p) => p.pid);\n const killed: number[] = [];\n for (const pid of pids) {\n if (this.kill(pid, opts)) killed.push(pid);\n }\n return killed;\n }\n}\n\n/** Module-level singleton. Initialized on first access. */\nlet _registry: ProcessRegistryImpl | undefined;\n\nexport function getProcessRegistry(): ProcessRegistryImpl {\n if (!_registry) {\n _registry = new ProcessRegistryImpl();\n }\n return _registry;\n}\n\n/** Reset for tests. */\nexport function _resetProcessRegistry(): void {\n _registry = undefined;\n}\n\n// ── Convenience re-exports ────────────────────────────────────────────────────\n\nexport type { KillOpts };"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wrongstack/tools",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.7",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "WrongStack built-in tools: read/write/edit, bash/exec, grep/glob, git, fetch, test, lint, and more.",
|
|
6
6
|
"repository": {
|
|
@@ -155,13 +155,21 @@
|
|
|
155
155
|
"./mode": {
|
|
156
156
|
"types": "./dist/mode.d.ts",
|
|
157
157
|
"import": "./dist/mode.js"
|
|
158
|
+
},
|
|
159
|
+
"./process-registry": {
|
|
160
|
+
"types": "./dist/process-registry.d.ts",
|
|
161
|
+
"import": "./dist/process-registry.js"
|
|
162
|
+
},
|
|
163
|
+
"./circuit-breaker": {
|
|
164
|
+
"types": "./dist/circuit-breaker.d.ts",
|
|
165
|
+
"import": "./dist/circuit-breaker.js"
|
|
158
166
|
}
|
|
159
167
|
},
|
|
160
168
|
"files": [
|
|
161
169
|
"dist"
|
|
162
170
|
],
|
|
163
171
|
"dependencies": {
|
|
164
|
-
"@wrongstack/core": "0.5.
|
|
172
|
+
"@wrongstack/core": "0.5.7"
|
|
165
173
|
},
|
|
166
174
|
"devDependencies": {
|
|
167
175
|
"@types/node": "^22.19.19",
|