@wrongstack/tools 0.310.1 → 0.313.1

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.
Files changed (135) hide show
  1. package/dist/_shell-pick.d.ts +5 -10
  2. package/dist/audit.js +10 -4055
  3. package/dist/bash.js +9 -2332
  4. package/dist/batch-tool-use.js +2 -187
  5. package/dist/browser/index.js +25 -1339
  6. package/dist/builtin.js +69 -33985
  7. package/dist/chunk-2CTB3UK5.js +197 -0
  8. package/dist/chunk-2ME7ZWDD.js +1272 -0
  9. package/dist/chunk-2TFQDEPU.js +113 -0
  10. package/dist/chunk-2ZCJNKFE.js +315 -0
  11. package/dist/chunk-3PVYQFRQ.js +472 -0
  12. package/dist/chunk-3QMQBO5Z.js +89 -0
  13. package/dist/chunk-42AKKX7O.js +385 -0
  14. package/dist/chunk-42SKEETB.js +113 -0
  15. package/dist/chunk-4BHUSMNL.js +104 -0
  16. package/dist/chunk-4I4LWFOO.js +431 -0
  17. package/dist/chunk-553IQUMO.js +478 -0
  18. package/dist/chunk-55KF77OK.js +1944 -0
  19. package/dist/chunk-6HLZK37X.js +359 -0
  20. package/dist/chunk-6RNIFLG4.js +305 -0
  21. package/dist/chunk-A6BRWIXN.js +317 -0
  22. package/dist/chunk-AHHDWNXC.js +200 -0
  23. package/dist/chunk-B2CIOKWP.js +899 -0
  24. package/dist/chunk-BTSFTGIL.js +7 -0
  25. package/dist/chunk-D33S4RQG.js +222 -0
  26. package/dist/chunk-DIJKHSUO.js +134 -0
  27. package/dist/chunk-DPL47QGS.js +3515 -0
  28. package/dist/chunk-EMRGN4KM.js +170 -0
  29. package/dist/chunk-FGOABE4Z.js +955 -0
  30. package/dist/chunk-FW65TP4G.js +520 -0
  31. package/dist/chunk-GOIZNNOA.js +221 -0
  32. package/dist/chunk-H5MJUAA6.js +295 -0
  33. package/dist/chunk-H5OHH6F4.js +223 -0
  34. package/dist/chunk-HC5RM4WY.js +199 -0
  35. package/dist/chunk-HEQFMLZ7.js +190 -0
  36. package/dist/chunk-HFXSNKCV.js +196 -0
  37. package/dist/chunk-HXSBQ2SE.js +1723 -0
  38. package/dist/chunk-ILESNGNM.js +163 -0
  39. package/dist/chunk-INF5CGAO.js +137 -0
  40. package/dist/chunk-IWDFZ6XR.js +337 -0
  41. package/dist/chunk-IXMNTNW5.js +238 -0
  42. package/dist/chunk-J4SRJKBW.js +428 -0
  43. package/dist/chunk-J5SKD6LN.js +235 -0
  44. package/dist/chunk-JRJJX3L5.js +424 -0
  45. package/dist/chunk-KXNDHMUB.js +366 -0
  46. package/dist/chunk-LIJQMYYX.js +59 -0
  47. package/dist/chunk-MAN26PZ5.js +260 -0
  48. package/dist/chunk-MKRQMLZA.js +474 -0
  49. package/dist/chunk-NBDZMMG2.js +169 -0
  50. package/dist/chunk-NHA6BEIH.js +101 -0
  51. package/dist/chunk-OA6YJIWL.js +4412 -0
  52. package/dist/chunk-OZC255IC.js +2830 -0
  53. package/dist/chunk-PUR6WU2B.js +154 -0
  54. package/dist/chunk-Q5JPPCZC.js +12 -0
  55. package/dist/chunk-QBV725YG.js +128 -0
  56. package/dist/chunk-QHVW4AAM.js +892 -0
  57. package/dist/chunk-QNJ7AQ4B.js +1000 -0
  58. package/dist/chunk-RGISBZBD.js +231 -0
  59. package/dist/chunk-RJZQWEMS.js +84 -0
  60. package/dist/chunk-RP2ZA47V.js +15 -0
  61. package/dist/chunk-RXISBFR5.js +315 -0
  62. package/dist/chunk-S5CCLZL3.js +99 -0
  63. package/dist/chunk-TVTCSBJF.js +122 -0
  64. package/dist/chunk-U4D5S3VQ.js +21 -0
  65. package/dist/chunk-U4VAATKP.js +193 -0
  66. package/dist/chunk-UKU2ZX4C.js +203 -0
  67. package/dist/chunk-UNSKG6DC.js +159 -0
  68. package/dist/chunk-URFKEIHM.js +1091 -0
  69. package/dist/chunk-UTV7YAW7.js +178 -0
  70. package/dist/chunk-V43EQ6VR.js +68 -0
  71. package/dist/chunk-VB3MJGCV.js +610 -0
  72. package/dist/chunk-WHIIIREL.js +223 -0
  73. package/dist/chunk-XMIFYKUT.js +1371 -0
  74. package/dist/chunk-YF2RSV34.js +54 -0
  75. package/dist/chunk-Z6DAKQ3U.js +1 -0
  76. package/dist/chunk-ZIGAZFWE.js +522 -0
  77. package/dist/circuit-breaker.js +3 -191
  78. package/dist/codebase-index/index.js +84 -13688
  79. package/dist/codebase-index/parser-worker-script.js +8 -3995
  80. package/dist/codebase-index/project-server.js +60 -8548
  81. package/dist/codebase-index/worker.js +20 -8416
  82. package/dist/design.js +2 -299
  83. package/dist/diff.js +4 -256
  84. package/dist/document.js +4 -222
  85. package/dist/e2e.js +5 -476
  86. package/dist/edit.js +14 -10200
  87. package/dist/exec.js +16 -3131
  88. package/dist/fetch.js +8 -398
  89. package/dist/format.js +10 -3750
  90. package/dist/generic-parser-VUXDIAOZ.js +13 -0
  91. package/dist/git.js +4 -380
  92. package/dist/glob.js +6 -280
  93. package/dist/go-parser-6CA77WZ4.js +469 -0
  94. package/dist/grep.js +7 -604
  95. package/dist/index.js +318 -35423
  96. package/dist/install.js +10 -4091
  97. package/dist/json-parser-7YMDJSBJ.js +213 -0
  98. package/dist/json.js +4 -665
  99. package/dist/kanban.js +3 -2096
  100. package/dist/languages/index.js +23 -4664
  101. package/dist/legacy-bridge-7UKZT46G.js +18 -0
  102. package/dist/lint.js +10 -3706
  103. package/dist/logs.js +4 -287
  104. package/dist/memory.js +6 -215
  105. package/dist/mode.js +3 -99
  106. package/dist/outdated.js +4 -5170
  107. package/dist/pack.js +65 -33933
  108. package/dist/parser-dispatch-VPOFDO2U.js +14 -0
  109. package/dist/patch.js +13 -9935
  110. package/dist/plan.js +5 -3286
  111. package/dist/process-registry.js +8 -651
  112. package/dist/ps-slash.js +12 -1439
  113. package/dist/py-parser-GPM5VYRG.js +16 -0
  114. package/dist/read.js +13 -9816
  115. package/dist/replace.js +15 -10014
  116. package/dist/rs-parser-WVQ4KYCX.js +81 -0
  117. package/dist/scaffold.js +4 -253
  118. package/dist/search.js +5 -585
  119. package/dist/session-kanban.js +30 -972
  120. package/dist/skill.js +2 -215
  121. package/dist/task.js +5 -3410
  122. package/dist/test.js +10 -3773
  123. package/dist/todo.js +4 -2891
  124. package/dist/tool-help.js +3 -123
  125. package/dist/tool-search.js +3 -79
  126. package/dist/tool-tier.js +68 -34020
  127. package/dist/tool-use.js +2 -93
  128. package/dist/tree-sitter-parser-YCILHGZD.js +17 -0
  129. package/dist/tree.js +4 -288
  130. package/dist/ts-parser-YH4ZMWMH.js +232 -0
  131. package/dist/typecheck.js +10 -3753
  132. package/dist/win32.js +6 -60
  133. package/dist/write.js +14 -9882
  134. package/dist/yaml-parser-GFAOKV53.js +157 -0
  135. package/package.json +5 -5
@@ -1,654 +1,11 @@
1
- // src/process-registry.ts
2
- import { spawn } from "node:child_process";
3
- import * as os from "node:os";
4
-
5
- // src/circuit-breaker.ts
6
- var DEFAULT_MAX_CONSECUTIVE_FAILURES = 5;
7
- var DEFAULT_SLOW_CALL_THRESHOLD_MS = 18e4;
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
- /**
27
- * Master enable flag. When false the breaker is bypassed: `beforeCall`
28
- * always returns true and `afterCall` records nothing. The class itself
29
- * defaults to enabled (so the standalone unit tests exercise tripping); the
30
- * ProcessRegistry flips this off until the user opts in via `/settings`.
31
- */
32
- enabled = true;
33
- /**
34
- * Fired (best-effort) when the breaker transitions into the `open` state.
35
- * The registry uses this to arm its auto kill/reset countdown.
36
- */
37
- onTrip;
38
- /**
39
- * Fired (best-effort) when the breaker returns to `closed` after having been
40
- * open/half-open. The registry uses this to cancel a pending kill/reset.
41
- */
42
- onReset;
43
- constructor(config = {}) {
44
- this.maxConsecutiveFailures = config.maxConsecutiveFailures ?? DEFAULT_MAX_CONSECUTIVE_FAILURES;
45
- this.slowCallThresholdMs = config.slowCallThresholdMs ?? DEFAULT_SLOW_CALL_THRESHOLD_MS;
46
- this.maxSlowCalls = config.maxSlowCalls ?? DEFAULT_MAX_SLOW_CALLS;
47
- this.windowMs = config.windowMs ?? DEFAULT_WINDOW_MS;
48
- this.maxCallsPerWindow = config.maxCallsPerWindow ?? DEFAULT_MAX_CALLS_PER_WINDOW;
49
- this.cooldownMs = config.cooldownMs ?? DEFAULT_COOLDOWN_MS;
50
- }
51
- /** Toggle the master enable. Disabling resets to a clean `closed` state. */
52
- setEnabled(enabled) {
53
- if (this.enabled === enabled) return;
54
- this.enabled = enabled;
55
- if (!enabled) this._reset();
56
- }
57
- get isEnabled() {
58
- return this.enabled;
59
- }
60
- /**
61
- * Returns true if the circuit allows a new call to proceed.
62
- * When false, callers should abort the tool call and return a
63
- * circuit-breaker error instead of spawning a process.
64
- */
65
- get canProceed() {
66
- if (!this.enabled) return true;
67
- this._checkStateTransition();
68
- return this.state !== "open";
69
- }
70
- /**
71
- * Snapshot of the current breaker state for observability (`/kill`).
72
- */
73
- snapshot() {
74
- this._checkStateTransition();
75
- const now = Date.now();
76
- let cooldownRemaining = null;
77
- if (this.openedAt !== null && this.state === "open") {
78
- const elapsed = now - this.openedAt;
79
- cooldownRemaining = Math.max(0, this.cooldownMs - elapsed);
80
- }
81
- return {
82
- state: this.state,
83
- consecutiveFailures: this.consecutiveFailures,
84
- slowCallsInWindow: this.window.filter((c) => c.slow).length,
85
- callsInWindow: this.window.length,
86
- windowMs: this.windowMs,
87
- cooldownRemainingMs: cooldownRemaining,
88
- lastFailureAt: this.lastFailureAt,
89
- lastSlowAt: this.lastSlowAt
90
- };
91
- }
92
- /**
93
- * Call this BEFORE spawning a bash/exec process.
94
- * Returns true if the call is allowed; false if the breaker is open.
95
- * When false, callers MUST NOT spawn a process.
96
- *
97
- * @param bypass - If true, skip the circuit breaker check entirely.
98
- * Use for background/fire-and-forget processes that should
99
- * not affect breaker state.
100
- */
101
- beforeCall(bypass = false) {
102
- if (bypass || !this.enabled) return true;
103
- this._checkStateTransition();
104
- if (this.state === "open") return false;
105
- return true;
106
- }
107
- /**
108
- * Call this AFTER a bash/exec process finishes (success or failure).
109
- * `durationMs` is the wall-clock time the process ran.
110
- * `failed` is true when the process returned a non-zero exit code or
111
- * threw an exception before spawning.
112
- *
113
- * @param bypass - If true, do not update breaker state.
114
- * Use for background/fire-and-forget processes.
115
- */
116
- afterCall(durationMs, failed, bypass = false) {
117
- if (bypass || !this.enabled) return;
118
- const now = Date.now();
119
- if (this.state === "half-open") {
120
- if (failed) {
121
- this._trip();
122
- return;
123
- }
124
- this._reset();
125
- return;
126
- }
127
- this._pruneWindow(now);
128
- const slow = durationMs >= this.slowCallThresholdMs;
129
- this.window.push({ at: now, failed, slow });
130
- if (failed) {
131
- this.consecutiveFailures++;
132
- this.lastFailureAt = now;
133
- if (this.consecutiveFailures >= this.maxConsecutiveFailures) {
134
- this._trip();
135
- }
136
- return;
137
- }
138
- this.consecutiveFailures = 0;
139
- if (slow) {
140
- this.lastSlowAt = now;
141
- const slowCount = this.window.filter((c) => c.slow).length;
142
- if (slowCount >= this.maxSlowCalls) {
143
- this._trip();
144
- }
145
- }
146
- const callCount = this.window.length;
147
- if (callCount >= this.maxCallsPerWindow) {
148
- this._trip();
149
- }
150
- }
151
- /** Force the breaker open. Used by /kill force and Ctrl+C. */
152
- forceOpen() {
153
- this._trip();
154
- }
155
- /** Force a reset to closed. Used by tests and /kill reset. */
156
- forceReset() {
157
- this._reset();
158
- }
159
- _trip() {
160
- if (this.state === "open") return;
161
- this.state = "open";
162
- this.openedAt = Date.now();
163
- this.window = [];
164
- try {
165
- this.onTrip?.();
166
- } catch {
167
- }
168
- }
169
- _reset() {
170
- const wasRecovering = this.state !== "closed";
171
- this.state = "closed";
172
- this.consecutiveFailures = 0;
173
- this.window = [];
174
- this.openedAt = null;
175
- if (wasRecovering) {
176
- try {
177
- this.onReset?.();
178
- } catch {
179
- }
180
- }
181
- }
182
- /** Transition from open → half-open when cooldown elapses. */
183
- _checkStateTransition() {
184
- if (this.state !== "open" || this.openedAt === null) return;
185
- const elapsed = Date.now() - this.openedAt;
186
- if (elapsed >= this.cooldownMs) {
187
- this.state = "half-open";
188
- this.openedAt = null;
189
- }
190
- }
191
- _pruneWindow(now) {
192
- const cutoff = now - this.windowMs;
193
- this.window = this.window.filter((c) => c.at >= cutoff);
194
- }
195
- };
196
-
197
- // src/_redact-command.ts
198
- import { expectDefined } from "@wrongstack/core/utils";
199
- var SENSITIVE_FLAG_PATTERNS = [
200
- // --flag=value or --flag "value" (value captured up to next space or comma)
201
- /--(?:token|password|passwd|pwd|secret|api[-_]?key|api[-_]?secret|auth|credential|private[-_]?key|access[-_]?key|github[-_]?token|gh[-_]?token|bearer|jwt|oauth|pin|pincode|passphrase|access[-_]?token)(?:[=\s,][^\s]*)?/gi,
202
- // -t short flag (token): attached (-tVALUE), separated (-t VALUE), or -t=VALUE.
203
- // (?<![-\w]) anchors to a token start so we don't match the `-t` inside `--token`.
204
- // The value must be token-like (>= 8 chars) so ordinary combined flags such
205
- // as `tar -tf` / `ssh -tt` are not eaten. Global flag: EVERY occurrence is
206
- // redacted, not just the first.
207
- // NOTE: synced with @wrongstack/core observability/redact-command.ts.
208
- /(?<![-\w])-t(?:[=\s]+)?[^\s,-]{8,}/g,
209
- // -p|-password|-a (redis auth) short flags: attached + separated + =value.
210
- // Same token-start anchor; over-redaction is an accepted tradeoff for a
211
- // redaction function. Synced with core copy.
212
- /(?<![-\w])-(?:password|p|a)(?:[=\s]+)?[^\s,-]+/gi,
213
- // env var–style secrets: TOKEN=x, API_KEY=y, etc.
214
- /(?:TOKEN|API_KEY|API_SECRET|AUTH_TOKEN|GITHUB_TOKEN|GH_TOKEN|BEARER|JWT|OAUTH|CREDENTIAL|SECRET|PRIVATE_KEY|PASSWORD|PASSWD|PASSPHRASE)\s*[=:]\s*[^\s,]+/gi,
215
- // Generic high-entropy look: base64 strings >32 chars or hex strings >32 digits — but only
216
- // when preceded by a flag name (e.g. --github-token=EyJ...). Global flag so
217
- // every such flag in the command line is redacted, not just the first.
218
- /--\w*(?:token|key|secret|password|passwd|auth|credential)\w*[=\s,][A-Za-z0-9+/=]{32,}/g
219
- ];
220
- function redactCommand(cmd) {
221
- let result = cmd;
222
- for (const pattern of SENSITIVE_FLAG_PATTERNS) {
223
- result = result.replace(pattern, (match) => {
224
- const eq = match.indexOf("=");
225
- const sp = match.search(/\s/);
226
- const delim = eq !== -1 ? "=" : sp !== -1 ? match[sp] : null;
227
- if (delim !== null) {
228
- const flag = match.slice(0, match.indexOf(expectDefined(delim)) + 1);
229
- return `${flag}[REDACTED]`;
230
- }
231
- if (match.startsWith("--")) {
232
- return match;
233
- }
234
- return `${match.slice(0, 2)}[REDACTED]`;
235
- });
236
- }
237
- return result;
238
- }
239
-
240
- // src/process-registry.ts
241
- var DEFAULT_GRACE_MS = 2e3;
242
- var WIN32_TASKKILL_TIMEOUT_MS = 5e3;
243
- function killWin32Tree(pid, opts = {}) {
244
- try {
245
- const child = spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
246
- stdio: "ignore",
247
- windowsHide: true
248
- });
249
- let settled = false;
250
- let timeout;
251
- const settle = () => {
252
- if (settled) return;
253
- settled = true;
254
- if (timeout) clearTimeout(timeout);
255
- try {
256
- opts.onSettled?.();
257
- } catch {
258
- }
259
- };
260
- child.on("error", settle);
261
- child.on("close", settle);
262
- timeout = setTimeout(
263
- () => {
264
- try {
265
- child.kill();
266
- } catch {
267
- }
268
- settle();
269
- },
270
- Math.max(1, opts.timeoutMs ?? WIN32_TASKKILL_TIMEOUT_MS)
271
- );
272
- timeout.unref?.();
273
- child.unref();
274
- return true;
275
- } catch {
276
- return false;
277
- }
278
- }
279
- var ProcessRegistryImpl = class {
280
- processes = /* @__PURE__ */ new Map();
281
- breaker;
282
- /**
283
- * Auto kill/reset config. When the breaker trips and `autoKillResetMs > 0`,
284
- * a countdown is armed; on expiry all tracked processes are killed and the
285
- * breaker is reset to closed (forced recovery). Zero means manual recovery
286
- * only (`/kill reset`).
287
- */
288
- autoKillResetMs = 0;
289
- autoKillTimer = null;
290
- autoKillArmedAt = null;
291
- breakerCountdownListeners = [];
292
- constructor(breakerConfig) {
293
- this.breaker = new CircuitBreaker(breakerConfig);
294
- this.breaker.onTrip = () => this._armAutoKillReset();
295
- this.breaker.onReset = () => this._cancelAutoKillReset();
296
- this.breaker.setEnabled(false);
297
- }
298
- register(info) {
299
- this.processes.set(info.pid, {
300
- ...info,
301
- killed: false,
302
- protected: info.protected ?? false,
303
- background: info.background ?? false
304
- });
305
- }
306
- _isSafeSignalPid(pid) {
307
- return Number.isInteger(pid) && pid > 1 && pid !== process.pid && pid !== process.ppid;
308
- }
309
- _canSignalProcessGroup(p) {
310
- return os.platform() !== "win32" && p.processGroupLeader === true && this._isSafeSignalPid(p.pid) && p.child !== null && typeof p.child.pid === "number" && p.child.pid === p.pid;
311
- }
312
- _killChildDirect(p, signal) {
313
- try {
314
- if (p.child) {
315
- p.child.kill(signal);
316
- return;
317
- }
318
- if (this._isSafeSignalPid(p.pid)) process.kill(p.pid, signal);
319
- } catch {
320
- }
321
- }
322
- _killPosix(p, signal) {
323
- if (this._canSignalProcessGroup(p)) {
324
- try {
325
- process.kill(-p.pid, signal);
326
- return;
327
- } catch {
328
- }
329
- }
330
- this._killChildDirect(p, signal);
331
- }
332
- /** Unregister a process by PID. Called on 'close' / 'exit' events. */
333
- unregister(pid) {
334
- this.processes.delete(pid);
335
- }
336
- /** Get a single process by PID. */
337
- get(pid) {
338
- this._pruneStale(pid);
339
- return this.processes.get(pid);
340
- }
341
- /** Get all tracked processes. */
342
- list() {
343
- this._pruneAllStale();
344
- return Array.from(this.processes.values());
345
- }
346
- /** Get processes filtered by name (e.g. 'bash', 'exec'). */
347
- byName(name) {
348
- return this.list().filter((p) => p.name === name);
349
- }
350
- /** Get processes filtered by session. */
351
- bySession(sessionId) {
352
- return this.list().filter((p) => p.sessionId === sessionId);
353
- }
354
- /** Count of active (non-killed) processes. */
355
- get activeCount() {
356
- let n = 0;
357
- for (const p of this.processes.values()) {
358
- if (!p.killed) n++;
359
- }
360
- return n;
361
- }
362
- /** Count of active jobs explicitly launched in background mode. */
363
- get activeBackgroundCount() {
364
- let n = 0;
365
- for (const p of this.processes.values()) {
366
- if (p.background && !p.killed) n++;
367
- }
368
- return n;
369
- }
370
- /**
371
- * Combined stats for observability — used by /ps and the TUI status bar.
372
- */
373
- stats() {
374
- this._pruneAllStale();
375
- return {
376
- activeCount: this.activeCount,
377
- backgroundCount: this.activeBackgroundCount,
378
- totalCount: this.processes.size,
379
- breaker: this.breaker.snapshot()
380
- };
381
- }
382
- /**
383
- * Returns true if the circuit allows a new bash/exec call to proceed.
384
- * When false, callers MUST NOT spawn a process.
385
- */
386
- get canProceed() {
387
- return this.breaker.canProceed;
388
- }
389
- /**
390
- * Called before spawning a process. Returns true if allowed; false if
391
- * the circuit breaker is open.
392
- *
393
- * @param bypass - If true, skip circuit breaker check (for background processes).
394
- */
395
- beforeCall(bypass = false) {
396
- return this.breaker.beforeCall(bypass);
397
- }
398
- /**
399
- * Called after a process finishes. `durationMs` is wall-clock time;
400
- * `failed` is true for non-zero exit codes.
401
- *
402
- * @param bypass - If true, do not update circuit breaker state (for background processes).
403
- */
404
- afterCall(durationMs, failed, bypass = false) {
405
- this.breaker.afterCall(durationMs, failed, bypass);
406
- }
407
- /** Force-open the circuit breaker (Ctrl+C, /kill force). */
408
- forceBreakerOpen() {
409
- this.breaker.forceOpen();
410
- }
411
- /** Force-reset the circuit breaker to closed (/kill reset). */
412
- forceBreakerReset() {
413
- this.breaker.forceReset();
414
- }
415
- /**
416
- * Configure circuit-breaker protection at runtime. Called from `/settings`
417
- * (instant, all modes) and on TUI mount (applies persisted config).
418
- *
419
- * - `enabled` toggles whether the breaker gates `bash`/`exec`.
420
- * - `autoKillResetMs` arms the auto kill/reset countdown when the breaker
421
- * trips (0 = manual recovery only).
422
- *
423
- * Re-applies cleanly on every call: cancels a pending countdown when the
424
- * timeout is cleared or protection disabled, and re-arms if the breaker is
425
- * currently open under the new settings.
426
- */
427
- setBreakerConfig(cfg) {
428
- if (cfg.enabled !== void 0) this.breaker.setEnabled(cfg.enabled);
429
- if (cfg.autoKillResetMs !== void 0) this.autoKillResetMs = Math.max(0, cfg.autoKillResetMs);
430
- if (this.autoKillResetMs <= 0) {
431
- this._cancelAutoKillReset();
432
- return;
433
- }
434
- if (this.breaker.isEnabled && this.breaker.snapshot().state === "open") {
435
- this._armAutoKillReset();
436
- }
437
- }
438
- /**
439
- * Live countdown to the next auto kill/reset, or null when nothing is armed.
440
- * The TUI polls this on a 1s tick while armed so the statusline decrements.
441
- */
442
- getBreakerCountdown() {
443
- if (this.autoKillArmedAt === null || this.autoKillResetMs <= 0) return null;
444
- const elapsed = Date.now() - this.autoKillArmedAt;
445
- return {
446
- remainingMs: Math.max(0, this.autoKillResetMs - elapsed),
447
- totalMs: this.autoKillResetMs
448
- };
449
- }
450
- /**
451
- * Subscribe to countdown arm/cancel events. Returns an unsubscribe function.
452
- * Use {@link getBreakerCountdown} for the live ticking value between events.
453
- */
454
- onBreakerCountdownChange(listener) {
455
- this.breakerCountdownListeners.push(listener);
456
- return () => {
457
- this.breakerCountdownListeners = this.breakerCountdownListeners.filter((l) => l !== listener);
458
- };
459
- }
460
- _emitBreakerCountdown() {
461
- const snap = this.getBreakerCountdown();
462
- for (const l of this.breakerCountdownListeners) {
463
- try {
464
- l(snap);
465
- } catch {
466
- }
467
- }
468
- }
469
- /**
470
- * Arm the auto kill/reset countdown. Idempotent: re-arming resets the window
471
- * (a fresh trip after a failed half-open probe restarts the clock). No-op
472
- * when protection is off or no timeout is configured.
473
- */
474
- _armAutoKillReset() {
475
- if (this.autoKillResetMs <= 0 || !this.breaker.isEnabled) return;
476
- this._clearAutoKillTimer();
477
- this.autoKillArmedAt = Date.now();
478
- this.autoKillTimer = setTimeout(() => {
479
- this.autoKillTimer = null;
480
- this.autoKillArmedAt = null;
481
- this.killAll({ force: false, preserveBackground: true });
482
- this.breaker.forceReset();
483
- this._emitBreakerCountdown();
484
- }, this.autoKillResetMs);
485
- this.autoKillTimer.unref?.();
486
- this._emitBreakerCountdown();
487
- }
488
- _cancelAutoKillReset() {
489
- const wasArmed = this.autoKillArmedAt !== null;
490
- this._clearAutoKillTimer();
491
- if (wasArmed) {
492
- this.autoKillArmedAt = null;
493
- this._emitBreakerCountdown();
494
- }
495
- }
496
- _clearAutoKillTimer() {
497
- if (this.autoKillTimer !== null) {
498
- clearTimeout(this.autoKillTimer);
499
- this.autoKillTimer = null;
500
- }
501
- }
502
- /** Kill a single process by PID.
503
- *
504
- * On POSIX: sends SIGTERM to the *process group* (-pid) so that
505
- * runaway grandchild processes (`sleep 9999 & disown`) are also killed.
506
- * After `graceMs` a SIGKILL is sent if the process hasn't exited.
507
- *
508
- * On Windows: `child.kill()` maps to TerminateProcess — process groups
509
- * are not meaningfully supported. A second `force=true` call sends
510
- * SIGKILL (which maps to TerminateProcess again — the distinction is
511
- * in the exit code, not the signal).
512
- *
513
- * Returns true if the process was found and kill was attempted.
514
- */
515
- kill(pid, opts = {}) {
516
- this._pruneStale(pid);
517
- const p = this.processes.get(pid);
518
- if (!p) return false;
519
- if (p.killed && opts.force !== true) return true;
520
- if (p.protected && opts.includeProtected !== true) return false;
521
- if (opts.preserveBackground && p.background) return false;
522
- const { force = false, graceMs = DEFAULT_GRACE_MS } = opts;
523
- const isWin = os.platform() === "win32";
524
- if (isWin) {
525
- const liveRealChild = p.child === null || p.child.exitCode === null && typeof p.child.pid === "number";
526
- const directFallback = () => {
527
- if (p.child && p.child.exitCode === null) {
528
- try {
529
- p.child.kill("SIGKILL");
530
- } catch {
531
- }
532
- }
533
- };
534
- if (liveRealChild && killWin32Tree(pid, {
535
- timeoutMs: Math.max(graceMs, WIN32_TASKKILL_TIMEOUT_MS),
536
- onSettled: directFallback
537
- })) {
538
- } else {
539
- this._killChildDirect(p, force ? "SIGKILL" : "SIGTERM");
540
- }
541
- p.killed = true;
542
- return true;
543
- }
544
- try {
545
- if (force) {
546
- this._killPosix(p, "SIGKILL");
547
- } else {
548
- this._killPosix(p, "SIGTERM");
549
- const timer = setTimeout(() => {
550
- if (this.processes.has(pid) && !p.child?.killed) {
551
- this._killPosix(p, "SIGKILL");
552
- }
553
- }, graceMs);
554
- timer.unref?.();
555
- }
556
- } catch {
557
- }
558
- p.killed = true;
559
- return true;
560
- }
561
- /**
562
- * Kill all tracked processes.
563
- * Returns the PIDs that were kill()ed.
564
- */
565
- killAll(opts = {}) {
566
- const pids = Array.from(this.processes.keys());
567
- const killed = [];
568
- const includeProtected = opts.includeProtected === true;
569
- for (const pid of pids) {
570
- const p = this.processes.get(pid);
571
- if (!p) continue;
572
- if (p.protected && !includeProtected) continue;
573
- if (opts.preserveBackground && p.background) continue;
574
- if (this.kill(pid, opts)) killed.push(pid);
575
- }
576
- return killed;
577
- }
578
- /**
579
- * Kill all processes for a specific session.
580
- * Returns the PIDs that were kill()ed.
581
- */
582
- killSession(sessionId, opts = {}) {
583
- const pids = this.bySession(sessionId).map((p) => p.pid);
584
- const killed = [];
585
- for (const pid of pids) {
586
- if (this.kill(pid, opts)) killed.push(pid);
587
- }
588
- return killed;
589
- }
590
- /**
591
- * Check whether a tracked process entry is stale — the child has exited
592
- * (exitCode !== null) AND it's been in the registry long enough that the
593
- * OS may have reused the PID for a new, unrelated process.
594
- *
595
- * P3 #24 (before-release.md): on POSIX, PIDs are reused after process
596
- * exit. If a tracked process exits but its 'close' event hasn't fired yet
597
- * (or was missed), the registry still holds the entry. A new process
598
- * gets the same PID, and PID-based lookups (get, kill, shouldBlockKill)
599
- * may incorrectly protect or target the wrong process.
600
- *
601
- * The 60s threshold is conservative — the OS typically waits much longer
602
- * before reusing a PID, but we want to clean up before that becomes a risk.
603
- */
604
- _isStaleEntry(entry) {
605
- if (entry.child === null) {
606
- if (Date.now() - entry.startedAt <= 6e4) return false;
607
- if (os.platform() === "win32") return false;
608
- try {
609
- process.kill(entry.pid, 0);
610
- return false;
611
- } catch (err) {
612
- return err.code !== "EPERM";
613
- }
614
- }
615
- return entry.child.exitCode !== null && Date.now() - entry.startedAt > 6e4;
616
- }
617
- /**
618
- * Remove a stale entry for a specific PID before any PID-based lookup.
619
- * This prevents PID reuse from causing the registry to act on a dead
620
- * process that has been replaced by a new one with the same PID.
621
- */
622
- _pruneStale(pid) {
623
- const entry = this.processes.get(pid);
624
- if (entry && this._isStaleEntry(entry)) {
625
- this.processes.delete(pid);
626
- }
627
- }
628
- /**
629
- * Remove every stale entry, not just one PID. `list()`/`stats()` — the
630
- * surfaces the TUI status bar and `/ps` poll — must prune too: a child
631
- * whose 'close' event never fires (e.g. Windows grandchildren holding stdio
632
- * open) would otherwise linger in the registry until someone looks up its
633
- * exact PID, and PID reuse meanwhile makes `get()`/`kill()` target the
634
- * wrong process. RAM-leak audit 2026-07-31, MEDIUM.
635
- */
636
- _pruneAllStale() {
637
- for (const [pid, entry] of this.processes) {
638
- if (this._isStaleEntry(entry)) this.processes.delete(pid);
639
- }
640
- }
641
- };
642
- var _registry;
643
- function getProcessRegistry() {
644
- if (!_registry) {
645
- _registry = new ProcessRegistryImpl();
646
- }
647
- return _registry;
648
- }
649
- function _resetProcessRegistry() {
650
- _registry = void 0;
651
- }
1
+ import {
2
+ ProcessRegistryImpl,
3
+ _resetProcessRegistry,
4
+ getProcessRegistry,
5
+ killWin32Tree,
6
+ redactCommand
7
+ } from "./chunk-3PVYQFRQ.js";
8
+ import "./chunk-HFXSNKCV.js";
652
9
  export {
653
10
  ProcessRegistryImpl,
654
11
  _resetProcessRegistry,